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 |
|---|---|---|---|---|---|---|---|---|
AlbertoSabater/Robust-and-efficient-post-processing-for-video-- | module.py | Module.data_names | data_names | A list of names for data required by this module. | [
"A",
"list",
"of",
"names",
"for",
"data",
"required",
"by",
"this",
"module."
] | def data_names(self):
return self._data_names | ['def', 'data_names(self):', 'return', 'self._data_names'] | 826,023 |
ArtificialIntelligenceToolkit/aitk.robots | lightsensors.py | LightSensor.set_position | set_position | Set the position of the light sensor with respect to the center of the robot. | [
"Set",
"the",
"position",
"of",
"the",
"light",
"sensor",
"with",
"respect",
"to",
"the",
"center",
"of",
"the",
"robot."
] | def set_position(self, position):
if len(position) != 2:
raise ValueError('position must be of length two')
self.position = position
self.dist_from_center = distance(0, 0, self.position[0], self.position[1])
self.dir_from_center = math.atan2(-self.position[0], self.position[1]) | ['def', 'set_position(self,', 'position):', 'if', 'len(position)', '!=', '2:', 'raise', "ValueError('position", 'must', 'be', 'of', 'length', "two')", 'self.position', '=', 'position', 'self.dist_from_center', '=', 'distance(0,', '0,', 'self.position[0],', 'self.position[1])', 'self.dir_from_center', '=', 'math.atan2(-... | 86,759 |
lululxvi/deepxde | optimizers.py | get | get | Retrieves an Optimizer instance. | [
"Retrieves",
"an",
"Optimizer",
"instance."
] | def get(loss, optimizer, learning_rate=None, decay=None):
if is_external_optimizer(optimizer):
if learning_rate is not None or decay is not None:
print('Warning: learning rate is ignored for {}'.format(optimizer))
return ScipyOptimizerInterface(loss, method='L-BFGS-B', options={'maxcor':... | ['def', 'get(loss,', 'optimizer,', 'learning_rate=None,', 'decay=None):', 'if', 'is_external_optimizer(optimizer):', 'if', 'learning_rate', 'is', 'not', 'None', 'or', 'decay', 'is', 'not', 'None:', "print('Warning:", 'learning', 'rate', 'is', 'ignored', 'for', "{}'.format(optimizer))", 'return', 'ScipyOptimizerInterfac... | 536,254 |
myothida/Supervised-Machine-Learning | text.py | Text.render | render | Render the text as Segments. | [
"Render",
"the",
"text",
"as",
"Segments."
] | def render(self, console: 'Console', end: str='') -> Iterable['Segment']:
_Segment = Segment
text = self.plain
if not self._spans:
yield Segment(text)
if end:
yield _Segment(end)
return
get_style = partial(console.get_style, default=Style.null())
enumerated_spans ... | ['def', 'render(self,', 'console:', "'Console',", 'end:', "str='')", '->', "Iterable['Segment']:", '_Segment', '=', 'Segment', 'text', '=', 'self.plain', 'if', 'not', 'self._spans:', 'yield', 'Segment(text)', 'if', 'end:', 'yield', '_Segment(end)', 'return', 'get_style', '=', 'partial(console.get_style,', 'default=Styl... | 445,122 |
rudranil723/mini-main | conftest.py | ordered | ordered | Boolean 'ordered' parameter for Categorical. | [
"Boolean",
"'ordered'",
"parameter",
"for",
"Categorical."
] | def ordered(request):
return request.param | ['def', 'ordered(request):', 'return', 'request.param'] | 323,106 |
wvangansbeke/Revisiting-Contrastive-SSL | functional.py | solarize | solarize | Solarize an RGB/grayscale image by inverting all pixel values above a threshold. | [
"Solarize",
"an",
"RGB/grayscale",
"image",
"by",
"inverting",
"all",
"pixel",
"values",
"above",
"a",
"threshold."
] | def solarize(img: Tensor, threshold: float) -> Tensor:
if not isinstance(img, torch.Tensor):
return F_pil.solarize(img, threshold)
return F_t.solarize(img, threshold) | ['def', 'solarize(img:', 'Tensor,', 'threshold:', 'float)', '->', 'Tensor:', 'if', 'not', 'isinstance(img,', 'torch.Tensor):', 'return', 'F_pil.solarize(img,', 'threshold)', 'return', 'F_t.solarize(img,', 'threshold)'] | 348,698 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Variable.get | get | Return value of variable. | [
"Return",
"value",
"of",
"variable."
] | def get(self):
return self._tk.globalgetvar(self._name) | ['def', 'get(self):', 'return', 'self._tk.globalgetvar(self._name)'] | 376,744 |
ifwe/digsby | infobox.py | InfoBox.OnSize | OnSize | Runs Repostion and refreshes if the infobox gets resized. | [
"Runs",
"Repostion",
"and",
"refreshes",
"if",
"the",
"infobox",
"gets",
"resized."
] | def OnSize(self, event):
event.Skip()
if self.pl and self.pr and (not self.fromTray):
self.Reposition()
self.Refresh() | ['def', 'OnSize(self,', 'event):', 'event.Skip()', 'if', 'self.pl', 'and', 'self.pr', 'and', '(not', 'self.fromTray):', 'self.Reposition()', 'self.Refresh()'] | 185,486 |
ucas-vg/PointTinyBenchmark | detr_head.py | DETRHead.simple_test_bboxes | simple_test_bboxes | Test det bboxes without test-time augmentation. | [
"Test",
"det",
"bboxes",
"without",
"test-time",
"augmentation."
] | def simple_test_bboxes(self, feats, img_metas, rescale=False):
batch_size = len(img_metas)
assert batch_size == 1, f'Currently only batch_size 1 for inference mode is supported. Found batch_size {batch_size}.'
outs = self.forward(feats, img_metas)
results_list = self.get_bboxes(*outs, img_metas, rescale... | ['def', 'simple_test_bboxes(self,', 'feats,', 'img_metas,', 'rescale=False):', 'batch_size', '=', 'len(img_metas)', 'assert', 'batch_size', '==', '1,', "f'Currently", 'only', 'batch_size', '1', 'for', 'inference', 'mode', 'is', 'supported.', 'Found', 'batch_size', "{batch_size}.'", 'outs', '=', 'self.forward(feats,', '... | 781,624 |
epfl-ml4ed/meta-transfer-learning | reptile.py | Reptile.train_step | train_step | Perform a Reptile training step. | [
"Perform",
"a",
"Reptile",
"training",
"step."
] | def train_step(self, dataset, input_ph, label_ph, minimize_op, num_classes, num_shots, inner_batch_size, inner_iters, replacement, meta_step_size, meta_batch_size):
old_vars = self._model_state.export_variables()
new_vars = []
for _ in range(meta_batch_size):
mini_dataset = _sample_mini_dataset(data... | ['def', 'train_step(self,', 'dataset,', 'input_ph,', 'label_ph,', 'minimize_op,', 'num_classes,', 'num_shots,', 'inner_batch_size,', 'inner_iters,', 'replacement,', 'meta_step_size,', 'meta_batch_size):', 'old_vars', '=', 'self._model_state.export_variables()', 'new_vars', '=', '[]', 'for', '_', 'in', 'range(meta_batch... | 633,395 |
YangRui2015/AWGCSL | util.py | transitions_in_episode_batch | transitions_in_episode_batch | Number of transitions in a given episode batch. | [
"Number",
"of",
"transitions",
"in",
"a",
"given",
"episode",
"batch."
] | def transitions_in_episode_batch(episode_batch):
shape = episode_batch['u'].shape
return shape[0] * shape[1] | ['def', 'transitions_in_episode_batch(episode_batch):', 'shape', '=', "episode_batch['u'].shape", 'return', 'shape[0]', '*', 'shape[1]'] | 93,883 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nb_007b.py | convert_weights | convert_weights | Converts the model weights to go with a new vocabulary. | [
"Converts",
"the",
"model",
"weights",
"to",
"go",
"with",
"a",
"new",
"vocabulary."
] | def convert_weights(wgts: Weights, stoi_wgts: Dict[str, int], itos_new: Collection[str]) -> Weights:
(dec_bias, enc_wgts) = (wgts['1.decoder.bias'], wgts['0.encoder.weight'])
(bias_m, wgts_m) = (dec_bias.mean(0), enc_wgts.mean(0))
new_w = enc_wgts.new_zeros((len(itos_new), enc_wgts.size(1))).zero_()
new... | ['def', 'convert_weights(wgts:', 'Weights,', 'stoi_wgts:', 'Dict[str,', 'int],', 'itos_new:', 'Collection[str])', '->', 'Weights:', '(dec_bias,', 'enc_wgts)', '=', "(wgts['1.decoder.bias'],", "wgts['0.encoder.weight'])", '(bias_m,', 'wgts_m)', '=', '(dec_bias.mean(0),', 'enc_wgts.mean(0))', 'new_w', '=', 'enc_wgts.new_... | 81,781 |
FederatedAI/FedVision | program_utils.py | program_to_code | program_to_code | Print readable codes of fluid program. | [
"Print",
"readable",
"codes",
"of",
"fluid",
"program."
] | def program_to_code(prog, fout=None, skip_op_callstack=True):
block_idx = 0
for block in prog.blocks:
block_to_code(block, block_idx, fout, skip_op_callstack)
block_idx += 1 | ['def', 'program_to_code(prog,', 'fout=None,', 'skip_op_callstack=True):', 'block_idx', '=', '0', 'for', 'block', 'in', 'prog.blocks:', 'block_to_code(block,', 'block_idx,', 'fout,', 'skip_op_callstack)', 'block_idx', '+=', '1'] | 581,834 |
kengz/SLM-Lab | __init__.py | Agent.act | act | Standard act method from algorithm. | [
"Standard",
"act",
"method",
"from",
"algorithm."
] | def act(self, state):
with torch.no_grad():
action = self.algorithm.act(state)
return action | ['def', 'act(self,', 'state):', 'with', 'torch.no_grad():', 'action', '=', 'self.algorithm.act(state)', 'return', 'action'] | 351,346 |
ahthie7u/cockpit | context.py | CockpitCTX.get | get | Get info from global step. | [
"Get",
"info",
"from",
"global",
"step."
] | def get(name, global_step):
try:
return CockpitCTX.INFO[global_step][name]
except KeyError as e:
raise KeyError(f"Please hand in '{name}' via cockpit(info=...).") from e | ['def', 'get(name,', 'global_step):', 'try:', 'return', 'CockpitCTX.INFO[global_step][name]', 'except', 'KeyError', 'as', 'e:', 'raise', 'KeyError(f"Please', 'hand', 'in', "'{name}'", 'via', 'cockpit(info=...).")', 'from', 'e'] | 492,523 |
weimin17/Object-Detection_HelmetDetection | training.py | create_learning_rate | create_learning_rate | Creates a learning rate Tensor. | [
"Creates",
"a",
"learning",
"rate",
"Tensor."
] | def create_learning_rate(hparams, global_step):
if hparams.get('learning_rate_decay_factor'):
learning_rate = tf.train.exponential_decay(learning_rate=float(hparams.learning_rate), global_step=global_step, decay_steps=hparams.learning_rate_decay_steps, decay_rate=hparams.learning_rate_decay_factor, staircas... | ['def', 'create_learning_rate(hparams,', 'global_step):', 'if', "hparams.get('learning_rate_decay_factor'):", 'learning_rate', '=', 'tf.train.exponential_decay(learning_rate=float(hparams.learning_rate),', 'global_step=global_step,', 'decay_steps=hparams.learning_rate_decay_steps,', 'decay_rate=hparams.learning_rate_de... | 749,065 |
google-research/rigl | sparse_optimizers_test.py | SparseDNWOptimizerTest.testDNWUpdates | testDNWUpdates | Checking whether mask is updated correctly. | [
"Checking",
"whether",
"mask",
"is",
"updated",
"correctly."
] | def testDNWUpdates(self, n_inp, n_out, default_sparsity):
(sess, train_op, _, mask, weights) = self._setup_graph(default_sparsity, 'random', {}, n_inp=n_inp, n_out=n_out)
for _ in range(5):
sess.run([train_op])
(mask_after, weights_after) = sess.run([mask, weights])
kept_connection_magni... | ['def', 'testDNWUpdates(self,', 'n_inp,', 'n_out,', 'default_sparsity):', '(sess,', 'train_op,', '_,', 'mask,', 'weights)', '=', 'self._setup_graph(default_sparsity,', "'random',", '{},', 'n_inp=n_inp,', 'n_out=n_out)', 'for', '_', 'in', 'range(5):', 'sess.run([train_op])', '(mask_after,', 'weights_after)', '=', 'sess.... | 841,371 |
surfriderfoundationeurope/mot | model_frcnn.py | proposal_metrics | proposal_metrics | Add summaries for RPN proposals. | [
"Add",
"summaries",
"for",
"RPN",
"proposals."
] | def proposal_metrics(iou):
best_iou = tf.reduce_max(iou, axis=0)
mean_best_iou = tf.reduce_mean(best_iou, name='best_iou_per_gt')
summaries = [mean_best_iou]
with tf.device('/cpu:0'):
for th in [0.3, 0.5]:
recall = tf.truediv(tf.count_nonzero(best_iou >= th), tf.size(best_iou, out_ty... | ['def', 'proposal_metrics(iou):', 'best_iou', '=', 'tf.reduce_max(iou,', 'axis=0)', 'mean_best_iou', '=', 'tf.reduce_mean(best_iou,', "name='best_iou_per_gt')", 'summaries', '=', '[mean_best_iou]', 'with', "tf.device('/cpu:0'):", 'for', 'th', 'in', '[0.3,', '0.5]:', 'recall', '=', 'tf.truediv(tf.count_nonzero(best_iou'... | 656,089 |
zihuitang/medical_AI_platform | shlex.py | shlex.sourcehook | sourcehook | Hook called on a filename to be sourced. | [
"Hook",
"called",
"on",
"a",
"filename",
"to",
"be",
"sourced."
] | def sourcehook(self, newfile):
if newfile[0] == '"':
newfile = newfile[1:-1]
if isinstance(self.infile, str) and (not os.path.isabs(newfile)):
newfile = os.path.join(os.path.dirname(self.infile), newfile)
return (newfile, open(newfile, 'r')) | ['def', 'sourcehook(self,', 'newfile):', 'if', 'newfile[0]', '==', '\'"\':', 'newfile', '=', 'newfile[1:-1]', 'if', 'isinstance(self.infile,', 'str)', 'and', '(not', 'os.path.isabs(newfile)):', 'newfile', '=', 'os.path.join(os.path.dirname(self.infile),', 'newfile)', 'return', '(newfile,', 'open(newfile,', "'r'))"] | 281,324 |
deepmind/dm_control | jaco_hand.py | JacoHand.finger_geoms | finger_geoms | List of geoms belonging to the fingers. | [
"List",
"of",
"geoms",
"belonging",
"to",
"the",
"fingers."
] | def finger_geoms(self):
return self._finger_geoms | ['def', 'finger_geoms(self):', 'return', 'self._finger_geoms'] | 165,017 |
facebookresearch/mtenv | env.py | build | build | Build a MTEnv comptaible variant of MetaWorld. | [
"Build",
"a",
"MTEnv",
"comptaible",
"variant",
"of",
"MetaWorld."
] | def build(benchmark: Optional[metaworld.Benchmark], benchmark_name: str, env_id_to_task_map: Optional[EnvIdToTaskMapType], should_perform_reward_normalization: bool=True, task_name: str='pick-place-v1', num_copies_per_env: int=1, initial_task_state: int=1) -> MTEnv:
(funcs_to_make_envs, env_id_to_task_map) = get_li... | ['def', 'build(benchmark:', 'Optional[metaworld.Benchmark],', 'benchmark_name:', 'str,', 'env_id_to_task_map:', 'Optional[EnvIdToTaskMapType],', 'should_perform_reward_normalization:', 'bool=True,', 'task_name:', "str='pick-place-v1',", 'num_copies_per_env:', 'int=1,', 'initial_task_state:', 'int=1)', '->', 'MTEnv:', '... | 642,693 |
facebookresearch/CompilerGym | download_test.py | test_download_failed_retry_loop | test_download_failed_retry_loop | Check that download attempts are repeated without sleep() on error. | [
"Check",
"that",
"download",
"attempts",
"are",
"repeated",
"without",
"sleep()",
"on",
"error."
] | def test_download_failed_retry_loop(mocker, max_retries: int):
def patched_download(*args):
raise DownloadFailed
mocker.patch.object(download, 'sleep')
mocker.patch.object(download, '_do_download_attempt', patched_download)
mocker.spy(download, '_do_download_attempt')
with pytest.raises(Dow... | ['def', 'test_download_failed_retry_loop(mocker,', 'max_retries:', 'int):', 'def', 'patched_download(*args):', 'raise', 'DownloadFailed', 'mocker.patch.object(download,', "'sleep')", 'mocker.patch.object(download,', "'_do_download_attempt',", 'patched_download)', 'mocker.spy(download,', "'_do_download_attempt')", 'with... | 125,993 |
airbus/scikit-decide | domain.py | FlightPlanningDomain.set_network | set_network | Creation of the airway graph. | [
"Creation",
"of",
"the",
"airway",
"graph."
] | def set_network(self, p0: LatLon, p1: LatLon, nb_forward_points: int, nb_lateral_points: int, nb_vertical_points: int, climbing_slope: float=None, descending_slope: float=None, graph_width: float=None):
cruise_alt_min = 31000 * ft
half_forward_points = nb_forward_points // 2
half_lateral_points = nb_lateral... | ['def', 'set_network(self,', 'p0:', 'LatLon,', 'p1:', 'LatLon,', 'nb_forward_points:', 'int,', 'nb_lateral_points:', 'int,', 'nb_vertical_points:', 'int,', 'climbing_slope:', 'float=None,', 'descending_slope:', 'float=None,', 'graph_width:', 'float=None):', 'cruise_alt_min', '=', '31000', '*', 'ft', 'half_forward_point... | 847,913 |
lebrice/Sequoia | policy_head_test.py | test_sanity_check_cartpole_done_vector | test_sanity_check_cartpole_done_vector | TODO: Sanity check, make sure that cartpole has done=True at some point when using a BatchedEnv. | [
"TODO:",
"Sanity",
"check,",
"make",
"sure",
"that",
"cartpole",
"has",
"done=True",
"at",
"some",
"point",
"when",
"using",
"a",
"BatchedEnv."
] | def test_sanity_check_cartpole_done_vector():
env = make_batched_env('CartPole-v0', batch_size=5, wrappers=[PixelObservationWrapper])
env = AddDoneToObservation(env)
obs = env.reset()
for i in range(100):
(obs, rewards, done, info) = env.step(env.action_space.sample())
assert all(obs['do... | ['def', 'test_sanity_check_cartpole_done_vector():', 'env', '=', "make_batched_env('CartPole-v0',", 'batch_size=5,', 'wrappers=[PixelObservationWrapper])', 'env', '=', 'AddDoneToObservation(env)', 'obs', '=', 'env.reset()', 'for', 'i', 'in', 'range(100):', '(obs,', 'rewards,', 'done,', 'info)', '=', 'env.step(env.actio... | 344,378 |
arshpreetsingh/quantopian-machinelearning | exceptions.py | ErrorTree.total_errors | total_errors | The total number of errors in the entire tree, including children. | [
"The",
"total",
"number",
"of",
"errors",
"in",
"the",
"entire",
"tree,",
"including",
"children."
] | def total_errors(self):
child_errors = sum((len(tree) for (_, tree) in iteritems(self._contents)))
return len(self.errors) + child_errors | ['def', 'total_errors(self):', 'child_errors', '=', 'sum((len(tree)', 'for', '(_,', 'tree)', 'in', 'iteritems(self._contents)))', 'return', 'len(self.errors)', '+', 'child_errors'] | 887,684 |
sklearn-theano/sklearn-theano | text_format.py | _Tokenizer.Consume | Consume | Consumes a piece of text. | [
"Consumes",
"a",
"piece",
"of",
"text."
] | def Consume(self, token):
if not self.TryConsume(token):
raise self._ParseError('Expected "%s".' % token) | ['def', 'Consume(self,', 'token):', 'if', 'not', 'self.TryConsume(token):', 'raise', "self._ParseError('Expected", '"%s".\'', '%', 'token)'] | 351,119 |
nlp-uoregon/trankit | adapter_model_mixin.py | ModelAdaptersMixin.save_all_adapters | save_all_adapters | Saves all adapters of this model together with their configuration to subfolders of the given location. | [
"Saves",
"all",
"adapters",
"of",
"this",
"model",
"together",
"with",
"their",
"configuration",
"to",
"subfolders",
"of",
"the",
"given",
"location."
] | def save_all_adapters(self, save_directory: str, meta_dict: dict=None, custom_weights_loaders: Optional[List[WeightsLoader]]=None):
for name in self.config.adapters.adapters:
(adapter_config, adapter_type) = self.config.adapters.get(name, return_type=True)
h = get_adapter_config_hash(adapter_config)... | ['def', 'save_all_adapters(self,', 'save_directory:', 'str,', 'meta_dict:', 'dict=None,', 'custom_weights_loaders:', 'Optional[List[WeightsLoader]]=None):', 'for', 'name', 'in', 'self.config.adapters.adapters:', '(adapter_config,', 'adapter_type)', '=', 'self.config.adapters.get(name,', 'return_type=True)', 'h', '=', '... | 920,040 |
alugupta/ares | loss.py | loss_adv | loss_adv | The function to create loss function. | [
"The",
"function",
"to",
"create",
"loss",
"function."
] | def loss_adv(loss_name, outputs, labels, target_labels, target, device):
if loss_name == 'ce':
loss = nn.CrossEntropyLoss()
if target:
cost = -loss(outputs, target_labels)
else:
cost = loss(outputs, labels)
elif loss_name == 'cw':
if target:
on... | ['def', 'loss_adv(loss_name,', 'outputs,', 'labels,', 'target_labels,', 'target,', 'device):', 'if', 'loss_name', '==', "'ce':", 'loss', '=', 'nn.CrossEntropyLoss()', 'if', 'target:', 'cost', '=', '-loss(outputs,', 'target_labels)', 'else:', 'cost', '=', 'loss(outputs,', 'labels)', 'elif', 'loss_name', '==', "'cw':", '... | 402,194 |
IntelLabs/nlp-architect | spacy_np_annotator.py | get_noun_phrases | get_noun_phrases | Get noun phrase tags from a spacy annotated document. | [
"Get",
"noun",
"phrase",
"tags",
"from",
"a",
"spacy",
"annotated",
"document."
] | def get_noun_phrases(doc: Doc) -> [Span]:
assert hasattr(doc._, 'noun_phrases'), 'no noun_phrase attributes in document'
return doc._.noun_phrases | ['def', 'get_noun_phrases(doc:', 'Doc)', '->', '[Span]:', 'assert', 'hasattr(doc._,', "'noun_phrases'),", "'no", 'noun_phrase', 'attributes', 'in', "document'", 'return', 'doc._.noun_phrases'] | 783,449 |
pedromzadeh/numpy-based-mnist-classifier | network.py | sigmoid_prime | sigmoid_prime | Returns d(sigmoid)/dz evaluated at z. | [
"Returns",
"d(sigmoid)/dz",
"evaluated",
"at",
"z."
] | def sigmoid_prime(z):
return np.exp(-z) * sigmoid(z) ** 2 | ['def', 'sigmoid_prime(z):', 'return', 'np.exp(-z)', '*', 'sigmoid(z)', '**', '2'] | 730,014 |
zjujdj/SuperAtomicCharge | MyUtils.py | EarlyStopping.save_checkpoint | save_checkpoint | Saves model when the metric on the validation set gets improved. | [
"Saves",
"model",
"when",
"the",
"metric",
"on",
"the",
"validation",
"set",
"gets",
"improved."
] | def save_checkpoint(self, model):
torch.save({'model_state_dict': model.state_dict()}, self.filename) | ['def', 'save_checkpoint(self,', 'model):', "torch.save({'model_state_dict':", 'model.state_dict()},', 'self.filename)'] | 880,743 |
ravenprotocol/ravenverse | model_without_padding_mask.py | GPT.from_pretrained | from_pretrained | Initialize a pretrained GPT model by copying over the weights from a huggingface/transformers checkpoint. | [
"Initialize",
"a",
"pretrained",
"GPT",
"model",
"by",
"copying",
"over",
"the",
"weights",
"from",
"a",
"huggingface/transformers",
"checkpoint."
] | def from_pretrained(cls, model_type, tokenizer_length=None):
assert model_type in {'gpt2', 'gpt2-medium', 'gpt2-large', 'gpt2-xl'}
from transformers import GPT2LMHeadModel
model_hf = GPT2LMHeadModel.from_pretrained(model_type)
if tokenizer_length is not None:
print('Tokenizer length: ', tokenize... | ['def', 'from_pretrained(cls,', 'model_type,', 'tokenizer_length=None):', 'assert', 'model_type', 'in', "{'gpt2',", "'gpt2-medium',", "'gpt2-large',", "'gpt2-xl'}", 'from', 'transformers', 'import', 'GPT2LMHeadModel', 'model_hf', '=', 'GPT2LMHeadModel.from_pretrained(model_type)', 'if', 'tokenizer_length', 'is', 'not',... | 304,303 |
ibarrien/SemiSupervisedLearning | expectation_maximization.py | EM_SSL.compute_total_words_in_class | compute_total_words_in_class | Compute total (potentially fractional) total words in current class. | [
"Compute",
"total",
"(potentially",
"fractional)",
"total",
"words",
"in",
"current",
"class."
] | def compute_total_words_in_class(self) -> None:
self.total_word_count_per_class[self.curr_class_idx] = np.sum(self.word_counts_per_class[self.curr_class_idx])
return None | ['def', 'compute_total_words_in_class(self)', '->', 'None:', 'self.total_word_count_per_class[self.curr_class_idx]', '=', 'np.sum(self.word_counts_per_class[self.curr_class_idx])', 'return', 'None'] | 343,742 |
nicknochnack/RealTimeSignLanguageTFJS | model.py | Model.build_inference_for_training | build_inference_for_training | Invokes depth and ego-motion networks and computes clouds if needed. | [
"Invokes",
"depth",
"and",
"ego-motion",
"networks",
"and",
"computes",
"clouds",
"if",
"needed."
] | def build_inference_for_training(self):
(self.image_stack, self.intrinsic_mat, self.intrinsic_mat_inv) = self.reader.read_data()
with tf.name_scope('egomotion_prediction'):
(self.egomotion, _) = nets.egomotion_net(self.image_stack, is_training=True, legacy_mode=self.legacy_mode)
with tf.variable_sco... | ['def', 'build_inference_for_training(self):', '(self.image_stack,', 'self.intrinsic_mat,', 'self.intrinsic_mat_inv)', '=', 'self.reader.read_data()', 'with', "tf.name_scope('egomotion_prediction'):", '(self.egomotion,', '_)', '=', 'nets.egomotion_net(self.image_stack,', 'is_training=True,', 'legacy_mode=self.legacy_mo... | 831,360 |
scikit-learn/scikit-learn | test_response.py | test_get_response_error | test_get_response_error | Check that we raise the proper error messages in _get_response_values_binary. | [
"Check",
"that",
"we",
"raise",
"the",
"proper",
"error",
"messages",
"in",
"_get_response_values_binary."
] | def test_get_response_error(estimator, X, y, err_msg, params):
estimator.fit(X, y)
with pytest.raises(ValueError, match=err_msg):
_get_response_values_binary(estimator, X, **params) | ['def', 'test_get_response_error(estimator,', 'X,', 'y,', 'err_msg,', 'params):', 'estimator.fit(X,', 'y)', 'with', 'pytest.raises(ValueError,', 'match=err_msg):', '_get_response_values_binary(estimator,', 'X,', '**params)'] | 854,360 |
Ruturaj123/Flowchart-Detection | configure.py | cygpath | cygpath | Convert path from posix to windows. | [
"Convert",
"path",
"from",
"posix",
"to",
"windows."
] | def cygpath(path):
return run_shell('cygpath -m "%s"' % path) | ['def', 'cygpath(path):', 'return', "run_shell('cygpath", '-m', '"%s"\'', '%', 'path)'] | 586,735 |
danamyu/hedgehog_detector | model.py | Model.episode_predict | episode_predict | Predict the labels on an episode of examples. | [
"Predict",
"the",
"labels",
"on",
"an",
"episode",
"of",
"examples."
] | def episode_predict(self, sess, x, y, clear_memory=False):
cur_memory = sess.run([self.mem_keys, self.mem_vals, self.mem_age])
if clear_memory:
self.clear_memory(sess)
outputs = [self.y_preds]
y_preds = []
for (xx, yy) in zip(x, y):
out = sess.run(outputs, feed_dict={self.x: xx, self... | ['def', 'episode_predict(self,', 'sess,', 'x,', 'y,', 'clear_memory=False):', 'cur_memory', '=', 'sess.run([self.mem_keys,', 'self.mem_vals,', 'self.mem_age])', 'if', 'clear_memory:', 'self.clear_memory(sess)', 'outputs', '=', '[self.y_preds]', 'y_preds', '=', '[]', 'for', '(xx,', 'yy)', 'in', 'zip(x,', 'y):', 'out', '... | 589,796 |
thaines/helit | student_t.py | StudentT.prob | prob | Given a vector x evaluates the density function at that point. | [
"Given",
"a",
"vector",
"x",
"evaluates",
"the",
"density",
"function",
"at",
"that",
"point."
] | def prob(self, x):
x = numpy.asarray(x)
d = self.loc.shape[0]
delta = x - self.loc
val = numpy.dot(delta, numpy.dot(self.getInvScale(), delta))
val = 1.0 + val / self.dof
return math.exp(self.getLogNorm() + math.log(val) * (-0.5 * (self.dof + d))) | ['def', 'prob(self,', 'x):', 'x', '=', 'numpy.asarray(x)', 'd', '=', 'self.loc.shape[0]', 'delta', '=', 'x', '-', 'self.loc', 'val', '=', 'numpy.dot(delta,', 'numpy.dot(self.getInvScale(),', 'delta))', 'val', '=', '1.0', '+', 'val', '/', 'self.dof', 'return', 'math.exp(self.getLogNorm()', '+', 'math.log(val)', '*', '(-... | 591,691 |
rudranil723/mini-main | password_validation.py | password_changed | password_changed | Inform all validators that have implemented a password_changed() method that the password has been changed. | [
"Inform",
"all",
"validators",
"that",
"have",
"implemented",
"a",
"password_changed()",
"method",
"that",
"the",
"password",
"has",
"been",
"changed."
] | def password_changed(password, user=None, password_validators=None):
if password_validators is None:
password_validators = get_default_password_validators()
for validator in password_validators:
password_changed = getattr(validator, 'password_changed', lambda *a: None)
password_changed(p... | ['def', 'password_changed(password,', 'user=None,', 'password_validators=None):', 'if', 'password_validators', 'is', 'None:', 'password_validators', '=', 'get_default_password_validators()', 'for', 'validator', 'in', 'password_validators:', 'password_changed', '=', 'getattr(validator,', "'password_changed',", 'lambda',... | 314,930 |
box/genty | genty_args.py | GentyArgs.args | args | Return tuple of positional arguments to be passed to the test. | [
"Return",
"tuple",
"of",
"positional",
"arguments",
"to",
"be",
"passed",
"to",
"the",
"test."
] | def args(self):
return self._args | ['def', 'args(self):', 'return', 'self._args'] | 202,320 |
google-research/batch_rl | rainbow_agent.py | FixedReplayRainbowAgent.step | step | Records the most recent transition and returns the agent's next action. | [
"Records",
"the",
"most",
"recent",
"transition",
"and",
"returns",
"the",
"agent's",
"next",
"action."
] | def step(self, reward, observation):
self._record_observation(observation)
self.action = self._select_action()
return self.action | ['def', 'step(self,', 'reward,', 'observation):', 'self._record_observation(observation)', 'self.action', '=', 'self._select_action()', 'return', 'self.action'] | 105,886 |
ofirnachum/sequence_gan | simple_demo.py | get_random_sequence | get_random_sequence | Returns random valley sequence. | [
"Returns",
"random",
"valley",
"sequence."
] | def get_random_sequence():
tokens = set(range(NUM_EMB))
tokens.discard(START_TOKEN)
tokens = list(tokens)
pivot = int(random.random() * SEQ_LENGTH)
left_of_pivot = []
right_of_pivot = []
for i in range(SEQ_LENGTH):
tok = random.choice(tokens)
if i <= pivot:
left_o... | ['def', 'get_random_sequence():', 'tokens', '=', 'set(range(NUM_EMB))', 'tokens.discard(START_TOKEN)', 'tokens', '=', 'list(tokens)', 'pivot', '=', 'int(random.random()', '*', 'SEQ_LENGTH)', 'left_of_pivot', '=', '[]', 'right_of_pivot', '=', '[]', 'for', 'i', 'in', 'range(SEQ_LENGTH):', 'tok', '=', 'random.choice(token... | 343,927 |
yogeshbalaji/InvGAN | gan.py | DefenseGANBase.generate_image | generate_image | Generates a fixed noise for visualization of generation output. | [
"Generates",
"a",
"fixed",
"noise",
"for",
"visualization",
"of",
"generation",
"output."
] | def generate_image(self, iteration=None):
samples = self.sess.run(self.fixed_noise_samples, feed_dict={self.is_training: False})
tflib.save_images.save_images(self.imsave_transform(samples), os.path.join(self.checkpoint_dir.replace('output', 'debug'), 'samples_{}.png'.format(iteration))) | ['def', 'generate_image(self,', 'iteration=None):', 'samples', '=', 'self.sess.run(self.fixed_noise_samples,', 'feed_dict={self.is_training:', 'False})', 'tflib.save_images.save_images(self.imsave_transform(samples),', "os.path.join(self.checkpoint_dir.replace('output',", "'debug'),", "'samples_{}.png'.format(iteration... | 576,743 |
google-research/tensor2robot | critic_model.py | CriticModel.pack_state_action_to_feature_spec | pack_state_action_to_feature_spec | Gets a feature spec namedtuple from the state and action. | [
"Gets",
"a",
"feature",
"spec",
"namedtuple",
"from",
"the",
"state",
"and",
"action."
] | def pack_state_action_to_feature_spec(self, state_params, action_params):
return tensorspec_utils.TensorSpecStruct(state=state_params, action=action_params) | ['def', 'pack_state_action_to_feature_spec(self,', 'state_params,', 'action_params):', 'return', 'tensorspec_utils.TensorSpecStruct(state=state_params,', 'action=action_params)'] | 908,222 |
YangRui2015/AWGCSL | util.py | convert_episode_to_batch_major | convert_episode_to_batch_major | Converts an episode to have the batch dimension in the major (first) dimension. | [
"Converts",
"an",
"episode",
"to",
"have",
"the",
"batch",
"dimension",
"in",
"the",
"major",
"(first)",
"dimension."
] | def convert_episode_to_batch_major(episode):
episode_batch = {}
for key in episode.keys():
val = np.array(episode[key]).copy()
episode_batch[key] = val.swapaxes(0, 1)
return episode_batch | ['def', 'convert_episode_to_batch_major(episode):', 'episode_batch', '=', '{}', 'for', 'key', 'in', 'episode.keys():', 'val', '=', 'np.array(episode[key]).copy()', 'episode_batch[key]', '=', 'val.swapaxes(0,', '1)', 'return', 'episode_batch'] | 93,882 |
voxel51/fiftyone | delegated.py | DelegatedOperationService.set_running | set_running | Sets the given delegated operation to running state. | [
"Sets",
"the",
"given",
"delegated",
"operation",
"to",
"running",
"state."
] | def set_running(self, doc_id):
return self._repo.update_run_state(_id=doc_id, run_state=ExecutionRunState.RUNNING) | ['def', 'set_running(self,', 'doc_id):', 'return', 'self._repo.update_run_state(_id=doc_id,', 'run_state=ExecutionRunState.RUNNING)'] | 583,730 |
PaddlePaddle/Paddle3D | grid.py | create_meshgrid3d | create_meshgrid3d | Generate a coordinate grid for an image. | [
"Generate",
"a",
"coordinate",
"grid",
"for",
"an",
"image."
] | def create_meshgrid3d(depth, height, width, normalized_coordinates=True, dtype=None):
xs = paddle.linspace(0, width - 1, width, dtype=dtype)
ys = paddle.linspace(0, height - 1, height, dtype=dtype)
zs = paddle.linspace(0, depth - 1, depth, dtype=dtype)
if normalized_coordinates:
xs = (xs / (widt... | ['def', 'create_meshgrid3d(depth,', 'height,', 'width,', 'normalized_coordinates=True,', 'dtype=None):', 'xs', '=', 'paddle.linspace(0,', 'width', '-', '1,', 'width,', 'dtype=dtype)', 'ys', '=', 'paddle.linspace(0,', 'height', '-', '1,', 'height,', 'dtype=dtype)', 'zs', '=', 'paddle.linspace(0,', 'depth', '-', '1,', 'd... | 778,052 |
Jed-Z/artificial-intelligence-lab | ggm_em.py | initCentroids | initCentroids | Init centroids with random samples. | [
"Init",
"centroids",
"with",
"random",
"samples."
] | def initCentroids(dataMat, k):
(numSamples, dim) = dataMat.shape
centroids = np.zeros((k, dim))
for i in range(k):
index = int(np.random.uniform(0, numSamples))
centroids[i, :] = dataMat[index, :]
return centroids | ['def', 'initCentroids(dataMat,', 'k):', '(numSamples,', 'dim)', '=', 'dataMat.shape', 'centroids', '=', 'np.zeros((k,', 'dim))', 'for', 'i', 'in', 'range(k):', 'index', '=', 'int(np.random.uniform(0,', 'numSamples))', 'centroids[i,', ':]', '=', 'dataMat[index,', ':]', 'return', 'centroids'] | 122,099 |
zichunhao/lgn-autoencoder | jet_recon_err.py | plot_jet_recon_err | plot_jet_recon_err | Plot reconstruction errors for jet. | [
"Plot",
"reconstruction",
"errors",
"for",
"jet."
] | def plot_jet_recon_err(jet_target_cartesian: np.ndarray, jet_recons_cartesian: np.ndarray, jet_target_polar: np.ndarray, jet_recons_polar: np.ndarray, save_dir: str, abs_coord: bool, custom_jet_recons_ranges: bool, epoch: Optional[int]=None, eps: float=1e-16, drop_zeros: bool=True, ranges: Optional[np.ndarray]=None, ge... | ['def', 'plot_jet_recon_err(jet_target_cartesian:', 'np.ndarray,', 'jet_recons_cartesian:', 'np.ndarray,', 'jet_target_polar:', 'np.ndarray,', 'jet_recons_polar:', 'np.ndarray,', 'save_dir:', 'str,', 'abs_coord:', 'bool,', 'custom_jet_recons_ranges:', 'bool,', 'epoch:', 'Optional[int]=None,', 'eps:', 'float=1e-16,', 'd... | 600,315 |
cheind/gcsl | coordinate_system.py | CoordinateSystem.set_local_transform | set_local_transform | Sets the local transform for the given object. | [
"Sets",
"the",
"local",
"transform",
"for",
"the",
"given",
"object."
] | def set_local_transform(self, object_id: ObjectId, translation: Optional[np.ndarray]=None, rotation: Optional[np.ndarray]=None):
(trans, rot) = self._check_transform(translation, rotation)
if trans is not None:
self._local_translations[object_id] = trans
if rot is not None:
self._local_rotat... | ['def', 'set_local_transform(self,', 'object_id:', 'ObjectId,', 'translation:', 'Optional[np.ndarray]=None,', 'rotation:', 'Optional[np.ndarray]=None):', '(trans,', 'rot)', '=', 'self._check_transform(translation,', 'rotation)', 'if', 'trans', 'is', 'not', 'None:', 'self._local_translations[object_id]', '=', 'trans', '... | 201,824 |
jimtin/Stock_Comparison | completer.py | CompletionSplitter.delims | delims | Return the string of delimiter characters. | [
"Return",
"the",
"string",
"of",
"delimiter",
"characters."
] | def delims(self):
return self._delims | ['def', 'delims(self):', 'return', 'self._delims'] | 384,587 |
weimin17/Object-Detection_HelmetDetection | optimizers.py | UnrollableOptimizer.compute_updates | compute_updates | Compute next step updates for a given variable list and state. | [
"Compute",
"next",
"step",
"updates",
"for",
"a",
"given",
"variable",
"list",
"and",
"state."
] | def compute_updates(self, xs, gs, state=None):
raise NotImplementedError() | ['def', 'compute_updates(self,', 'xs,', 'gs,', 'state=None):', 'raise', 'NotImplementedError()'] | 750,428 |
enuguru/artificial_intelligence_and_machine_learning | compiler.py | CodeGenerator.fail | fail | Fail with a :exc:`TemplateAssertionError`. | [
"Fail",
"with",
"a",
":exc:`TemplateAssertionError`."
] | def fail(self, msg, lineno):
raise TemplateAssertionError(msg, lineno, self.name, self.filename) | ['def', 'fail(self,', 'msg,', 'lineno):', 'raise', 'TemplateAssertionError(msg,', 'lineno,', 'self.name,', 'self.filename)'] | 129,035 |
rudranil723/mini-main | operations.py | PostGISOperations.postgis_lib_version | postgis_lib_version | Return the version number of the PostGIS library used with PostgreSQL. | [
"Return",
"the",
"version",
"number",
"of",
"the",
"PostGIS",
"library",
"used",
"with",
"PostgreSQL."
] | def postgis_lib_version(self):
return self._get_postgis_func('postgis_lib_version') | ['def', 'postgis_lib_version(self):', 'return', "self._get_postgis_func('postgis_lib_version')"] | 315,020 |
SeldonIO/MLServer | base.py | RequestCodec.decode_response | decode_response | Decode an inference response into a high-level Python object. | [
"Decode",
"an",
"inference",
"response",
"into",
"a",
"high-level",
"Python",
"object."
] | def decode_response(cls, response: InferenceResponse) -> Any:
raise NotImplementedError() | ['def', 'decode_response(cls,', 'response:', 'InferenceResponse)', '->', 'Any:', 'raise', 'NotImplementedError()'] | 630,908 |
eddylau328/fyp-artificial-intelligence-ac-control-device | containers.py | RepeatedCompositeFieldContainer.insert | insert | Inserts the item at the specified position by copying. | [
"Inserts",
"the",
"item",
"at",
"the",
"specified",
"position",
"by",
"copying."
] | def insert(self, key, value):
new_element = self._message_descriptor._concrete_class()
new_element._SetListener(self._message_listener)
new_element.CopyFrom(value)
self._values.insert(key, new_element)
if not self._message_listener.dirty:
self._message_listener.Modified() | ['def', 'insert(self,', 'key,', 'value):', 'new_element', '=', 'self._message_descriptor._concrete_class()', 'new_element._SetListener(self._message_listener)', 'new_element.CopyFrom(value)', 'self._values.insert(key,', 'new_element)', 'if', 'not', 'self._message_listener.dirty:', 'self._message_listener.Modified()'] | 215,289 |
rudranil723/mini-main | formsets.py | BaseFormSet.has_changed | has_changed | Return True if data in any form differs from initial. | [
"Return",
"True",
"if",
"data",
"in",
"any",
"form",
"differs",
"from",
"initial."
] | def has_changed(self):
return any((form.has_changed() for form in self)) | ['def', 'has_changed(self):', 'return', 'any((form.has_changed()', 'for', 'form', 'in', 'self))'] | 316,271 |
athms/evaluating-deeplight-transfer | paths.py | path_bids_anat_mni | path_bids_anat_mni | Return the path to the local anatomical scan of a subject. | [
"Return",
"the",
"path",
"to",
"the",
"local",
"anatomical",
"scan",
"of",
"a",
"subject."
] | def path_bids_anat_mni(subject, path):
return os.path.join(path, 'sub-{}'.format(subject), 'anat', 'sub-{}_space-MNI152NLin6Asym_res-2_desc-preproc_T1w.nii.gz'.format(subject)) | ['def', 'path_bids_anat_mni(subject,', 'path):', 'return', 'os.path.join(path,', "'sub-{}'.format(subject),", "'anat',", "'sub-{}_space-MNI152NLin6Asym_res-2_desc-preproc_T1w.nii.gz'.format(subject))"] | 563,482 |
ldkong1205/LaserMix | test_monoflex_head.py | TestMonoFlexHead.test_monoflex_head_loss | test_monoflex_head_loss | Tests MonoFlex head loss and inference. | [
"Tests",
"MonoFlex",
"head",
"loss",
"and",
"inference."
] | def test_monoflex_head_loss(self):
input_metas = [dict(img_shape=(110, 110), pad_shape=(128, 128))]
monoflex_head = MonoFlexHead(num_classes=3, in_channels=64, use_edge_fusion=True, edge_fusion_inds=[(1, 0)], edge_heatmap_ratio=1 / 8, stacked_convs=0, feat_channels=64, use_direction_classifier=False, diff_rad_b... | ['def', 'test_monoflex_head_loss(self):', 'input_metas', '=', '[dict(img_shape=(110,', '110),', 'pad_shape=(128,', '128))]', 'monoflex_head', '=', 'MonoFlexHead(num_classes=3,', 'in_channels=64,', 'use_edge_fusion=True,', 'edge_fusion_inds=[(1,', '0)],', 'edge_heatmap_ratio=1', '/', '8,', 'stacked_convs=0,', 'feat_chan... | 624,604 |
angeladai/ScanComplete | model.py | process_previous_geo_groups | process_previous_geo_groups | Processes previous voxel groups from scan/geometry tensor. | [
"Processes",
"previous",
"voxel",
"groups",
"from",
"scan/geometry",
"tensor."
] | def process_previous_geo_groups(groups, batch_size, num_channels):
num_groups = len(groups)
groups = [tf.expand_dims(x, 1) for x in groups]
groups = tf.concat(groups, 1)
context_groups = tf.reshape(groups, [-1] + groups.get_shape().as_list()[2:])
context_groups = slim.conv3d(context_groups, num_outp... | ['def', 'process_previous_geo_groups(groups,', 'batch_size,', 'num_channels):', 'num_groups', '=', 'len(groups)', 'groups', '=', '[tf.expand_dims(x,', '1)', 'for', 'x', 'in', 'groups]', 'groups', '=', 'tf.concat(groups,', '1)', 'context_groups', '=', 'tf.reshape(groups,', '[-1]', '+', 'groups.get_shape().as_list()[2:])... | 845,854 |
rlberry-py/rlberry | models.py | default_policy_net_fn | default_policy_net_fn | Returns a default policy network. | [
"Returns",
"a",
"default",
"policy",
"network."
] | def default_policy_net_fn(env):
while type(env) in [SyncVectorEnv, AsyncVectorEnv]:
env = env.envs[0]
if isinstance(env.observation_space, spaces.Box):
obs_shape = env.observation_space.shape
elif isinstance(env.observation_space, spaces.Tuple):
obs_shape = env.observation_space.spac... | ['def', 'default_policy_net_fn(env):', 'while', 'type(env)', 'in', '[SyncVectorEnv,', 'AsyncVectorEnv]:', 'env', '=', 'env.envs[0]', 'if', 'isinstance(env.observation_space,', 'spaces.Box):', 'obs_shape', '=', 'env.observation_space.shape', 'elif', 'isinstance(env.observation_space,', 'spaces.Tuple):', 'obs_shape', '='... | 862,102 |
Ruturaj123/Flowchart-Detection | imperative_test.py | ImperativeTest.testVariable | testVariable | Makes sure that variables can be evaluated before running initializer. | [
"Makes",
"sure",
"that",
"variables",
"can",
"be",
"evaluated",
"before",
"running",
"initializer."
] | def testVariable(self):
with imperative_mode.ImperativeMode(self._target):
x = variables.Variable(1, name='xy')
self.assertEqual(x.value().value, 1)
x = x.assign_add(41)
self.assertEqual(x.value, 1 + 41)
y = variables.Variable(3, name='y')
self.assertEqual(y.value().v... | ['def', 'testVariable(self):', 'with', 'imperative_mode.ImperativeMode(self._target):', 'x', '=', 'variables.Variable(1,', "name='xy')", 'self.assertEqual(x.value().value,', '1)', 'x', '=', 'x.assign_add(41)', 'self.assertEqual(x.value,', '1', '+', '41)', 'y', '=', 'variables.Variable(3,', "name='y')", 'self.assertEqua... | 603,215 |
Anjok07/ultimatevocalremovergui | UVR.py | MainWindow.selection_action_models | selection_action_models | Accepts model names and verifies their state. | [
"Accepts",
"model",
"names",
"and",
"verifies",
"their",
"state."
] | def selection_action_models(self, selection):
if selection in CHOOSE_MODEL:
self.update_stem_checkbox_labels(PRIMARY_STEM, disable_boxes=True)
else:
self.is_stem_only_Options_Enable()
self._handle_model_by_chosen_method(selection)
if self.chosen_process_method_var.get() == ENSEMBLE_MODE:... | ['def', 'selection_action_models(self,', 'selection):', 'if', 'selection', 'in', 'CHOOSE_MODEL:', 'self.update_stem_checkbox_labels(PRIMARY_STEM,', 'disable_boxes=True)', 'else:', 'self.is_stem_only_Options_Enable()', 'self._handle_model_by_chosen_method(selection)', 'if', 'self.chosen_process_method_var.get()', '==', ... | 947,524 |
ForrestPi/ObjectDetectionTricks | wavelet.py | get_max_num_levels | get_max_num_levels | Returns the maximum number of levels that construct() can support. | [
"Returns",
"the",
"maximum",
"number",
"of",
"levels",
"that",
"construct()",
"can",
"support."
] | def get_max_num_levels(sz):
min_sz = np.minimum(sz[1], sz[2])
log2 = lambda x: np.log(np.float32(x)) / np.log(np.float32(2.0))
max_num_levels = int(np.ceil(log2(np.maximum(1, min_sz))))
return max_num_levels | ['def', 'get_max_num_levels(sz):', 'min_sz', '=', 'np.minimum(sz[1],', 'sz[2])', 'log2', '=', 'lambda', 'x:', 'np.log(np.float32(x))', '/', 'np.log(np.float32(2.0))', 'max_num_levels', '=', 'int(np.ceil(log2(np.maximum(1,', 'min_sz))))', 'return', 'max_num_levels'] | 744,668 |
heynemann/pyvows | commands.py | VowsCommand.initialize_options | initialize_options | Set default values for options. | [
"Set",
"default",
"values",
"for",
"options."
] | def initialize_options(self):
self.pyvows_pattern = '*_vows.py'
self.pyvows_path = 'tests/' | ['def', 'initialize_options(self):', 'self.pyvows_pattern', '=', "'*_vows.py'", 'self.pyvows_path', '=', "'tests/'"] | 302,599 |
omonimus1/super-computer- | git.py | Git.get_revision_sha | get_revision_sha | Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. | [
"Return",
"(sha_or_none,",
"is_branch),",
"where",
"sha_or_none",
"is",
"a",
"commit",
"hash",
"if",
"the",
"revision",
"names",
"a",
"remote",
"branch",
"or",
"tag,",
"otherwise",
"None."
] | def get_revision_sha(cls, dest, rev):
output = cls.run_command(['show-ref', rev], cwd=dest, show_stdout=False, on_returncode='ignore')
refs = {}
for line in output.strip().splitlines():
try:
(sha, ref) = line.split()
except ValueError:
raise ValueError('unexpected sho... | ['def', 'get_revision_sha(cls,', 'dest,', 'rev):', 'output', '=', "cls.run_command(['show-ref',", 'rev],', 'cwd=dest,', 'show_stdout=False,', "on_returncode='ignore')", 'refs', '=', '{}', 'for', 'line', 'in', 'output.strip().splitlines():', 'try:', '(sha,', 'ref)', '=', 'line.split()', 'except', 'ValueError:', 'raise',... | 913,301 |
NoGameNoLife00/mybolg | __init__.py | Pagination.prev | prev | Returns a :class:`Pagination` object for the previous page. | [
"Returns",
"a",
":class:`Pagination`",
"object",
"for",
"the",
"previous",
"page."
] | def prev(self, error_out=False):
assert self.query is not None, 'a query object is required for this method to work'
return self.query.paginate(self.page - 1, self.per_page, error_out) | ['def', 'prev(self,', 'error_out=False):', 'assert', 'self.query', 'is', 'not', 'None,', "'a", 'query', 'object', 'is', 'required', 'for', 'this', 'method', 'to', "work'", 'return', 'self.query.paginate(self.page', '-', '1,', 'self.per_page,', 'error_out)'] | 289,357 |
pycroscopy/atomai | trainer.py | clsTrainer.set_data | set_data | Sets training and test data. | [
"Sets",
"training",
"and",
"test",
"data."
] | def set_data(self, X_train: Tuple[np.ndarray, torch.Tensor], y_train: Tuple[np.ndarray, torch.Tensor], X_test: Optional[Tuple[np.ndarray, torch.Tensor]]=None, y_test: Optional[Tuple[np.ndarray, torch.Tensor]]=None, **kwargs: Union[float, int]) -> None:
if X_test is None or y_test is None:
(X_train, X_test, ... | ['def', 'set_data(self,', 'X_train:', 'Tuple[np.ndarray,', 'torch.Tensor],', 'y_train:', 'Tuple[np.ndarray,', 'torch.Tensor],', 'X_test:', 'Optional[Tuple[np.ndarray,', 'torch.Tensor]]=None,', 'y_test:', 'Optional[Tuple[np.ndarray,', 'torch.Tensor]]=None,', '**kwargs:', 'Union[float,', 'int])', '->', 'None:', 'if', 'X_... | 402,888 |
ekalinicheva/Unsupervised-CD-in-SITS-using-DL-and-Graphs | pytorchtools.py | EarlyStopping.save_checkpoint | save_checkpoint | Saves model when validation loss decrease. | [
"Saves",
"model",
"when",
"validation",
"loss",
"decrease."
] | def save_checkpoint(self, val_loss, model):
if self.verbose:
print(f'Validation loss decreased ({self.val_loss_min:.6f} --> {val_loss:.6f}). Saving model ...')
torch.save(model.state_dict(), 'checkpoint.pt')
self.val_loss_min = val_loss | ['def', 'save_checkpoint(self,', 'val_loss,', 'model):', 'if', 'self.verbose:', "print(f'Validation", 'loss', 'decreased', '({self.val_loss_min:.6f}', '-->', '{val_loss:.6f}).', 'Saving', 'model', "...')", 'torch.save(model.state_dict(),', "'checkpoint.pt')", 'self.val_loss_min', '=', 'val_loss'] | 378,787 |
neurospin/pylearn-parsimony | properties.py | NesterovFunction.phi | phi | Function value with known alpha. | [
"Function",
"value",
"with",
"known",
"alpha."
] | def phi(self, alpha, beta):
raise NotImplementedError('Abstract method "phi" must be specialised!') | ['def', 'phi(self,', 'alpha,', 'beta):', 'raise', "NotImplementedError('Abstract", 'method', '"phi"', 'must', 'be', "specialised!')"] | 820,171 |
HKUDS/SSLRec | dcrec_seq.py | DCRec_seq.get_attention_mask | get_attention_mask | Generate bidirectional attention mask for multi-head attention. | [
"Generate",
"bidirectional",
"attention",
"mask",
"for",
"multi-head",
"attention."
] | def get_attention_mask(self, item_seq, task_label=False):
if task_label:
label_pos = torch.ones((item_seq.size(0), 1), device=self.device)
item_seq = torch.cat((label_pos, item_seq), dim=1)
attention_mask = (item_seq > 0).long()
extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze... | ['def', 'get_attention_mask(self,', 'item_seq,', 'task_label=False):', 'if', 'task_label:', 'label_pos', '=', 'torch.ones((item_seq.size(0),', '1),', 'device=self.device)', 'item_seq', '=', 'torch.cat((label_pos,', 'item_seq),', 'dim=1)', 'attention_mask', '=', '(item_seq', '>', '0).long()', 'extended_attention_mask', ... | 382,039 |
PacktPublishing/Hands-On-Artificial--for-Banking | conftest.py | not_hourly | not_hourly | Several timedelta-like and DateOffset instances that are _not_ compatible with Hourly frequencies. | [
"Several",
"timedelta-like",
"and",
"DateOffset",
"instances",
"that",
"are",
"_not_",
"compatible",
"with",
"Hourly",
"frequencies."
] | def not_hourly(request):
return request.param | ['def', 'not_hourly(request):', 'return', 'request.param'] | 237,095 |
vghost2008/wml1 | bifpn.py | build_shufflenetv2_bifpn_backbone | build_shufflenetv2_bifpn_backbone | Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. | [
"Returns:",
"backbone",
"(Backbone):",
"backbone",
"module,",
"must",
"be",
"a",
"subclass",
"of",
":class:`Backbone`."
] | def build_shufflenetv2_bifpn_backbone(cfg, *args, **kwargs):
bottom_up = build_shufflenetv2_backbone(cfg, *args, **kwargs)
in_features = cfg.MODEL.BIFPN.IN_FEATURES
out_channels = cfg.MODEL.BIFPN.OUT_CHANNELS
backbone = BIFPN(*args, bottom_up=bottom_up, in_features=in_features, out_channels=out_channels... | ['def', 'build_shufflenetv2_bifpn_backbone(cfg,', '*args,', '**kwargs):', 'bottom_up', '=', 'build_shufflenetv2_backbone(cfg,', '*args,', '**kwargs)', 'in_features', '=', 'cfg.MODEL.BIFPN.IN_FEATURES', 'out_channels', '=', 'cfg.MODEL.BIFPN.OUT_CHANNELS', 'backbone', '=', 'BIFPN(*args,', 'bottom_up=bottom_up,', 'in_feat... | 960,124 |
tanmayshankar/RCNN_MDP | _setup_util.py | prepend_env_variables | prepend_env_variables | Generate shell code to prepend environment variables for the all workspaces. | [
"Generate",
"shell",
"code",
"to",
"prepend",
"environment",
"variables",
"for",
"the",
"all",
"workspaces."
] | def prepend_env_variables(environ, env_var_subfolders, workspaces):
lines = []
lines.append(comment('prepend folders of workspaces to environment variables'))
paths = [path for path in workspaces.split(os.pathsep) if path]
prefix = _prefix_env_variable(environ, 'CMAKE_PREFIX_PATH', paths, '')
lines.... | ['def', 'prepend_env_variables(environ,', 'env_var_subfolders,', 'workspaces):', 'lines', '=', '[]', "lines.append(comment('prepend", 'folders', 'of', 'workspaces', 'to', 'environment', "variables'))", 'paths', '=', '[path', 'for', 'path', 'in', 'workspaces.split(os.pathsep)', 'if', 'path]', 'prefix', '=', '_prefix_env... | 304,397 |
Eric3911/OpenAGI | download.py | download_multi | download_multi | Download multiple files from url to target_dir. | [
"Download",
"multiple",
"files",
"from",
"url",
"to",
"target_dir."
] | def download_multi(url, target_dir, extra_args):
if not os.path.exists(target_dir):
os.makedirs(target_dir)
print('Downloading %s ...' % url)
ret_code = os.system('wget -c ' + url + ' ' + extra_args + ' -P ' + target_dir)
return ret_code | ['def', 'download_multi(url,', 'target_dir,', 'extra_args):', 'if', 'not', 'os.path.exists(target_dir):', 'os.makedirs(target_dir)', "print('Downloading", '%s', "...'", '%', 'url)', 'ret_code', '=', "os.system('wget", '-c', "'", '+', 'url', '+', "'", "'", '+', 'extra_args', '+', "'", '-P', "'", '+', 'target_dir)', 'ret... | 251,156 |
yfpeng/object_detection_metrics | visualize.py | plot_precision_recall_curve | plot_precision_recall_curve | PlotPrecisionRecallCurve Plot the Precision x Recall curve for a given class. | [
"PlotPrecisionRecallCurve",
"Plot",
"the",
"Precision",
"x",
"Recall",
"curve",
"for",
"a",
"given",
"class."
] | def plot_precision_recall_curve(result: MetricPerClass, dest, method: MethodAveragePrecision=MethodAveragePrecision.AllPointsInterpolation, show_ap: bool=False, show_interpolated_precision: bool=False):
mpre = result.interpolated_precision
mrec = result.interpolated_recall
plt.close()
if show_interpolat... | ['def', 'plot_precision_recall_curve(result:', 'MetricPerClass,', 'dest,', 'method:', 'MethodAveragePrecision=MethodAveragePrecision.AllPointsInterpolation,', 'show_ap:', 'bool=False,', 'show_interpolated_precision:', 'bool=False):', 'mpre', '=', 'result.interpolated_precision', 'mrec', '=', 'result.interpolated_recall... | 795,915 |
PacktPublishing/Hands-on-Supervised-Machine-Learning-with-Python | metrics.py | VarianceReduction.compute_uncertainty | compute_uncertainty | Compute the variance of a target. | [
"Compute",
"the",
"variance",
"of",
"a",
"target."
] | def compute_uncertainty(self, y):
return np.var(y) | ['def', 'compute_uncertainty(self,', 'y):', 'return', 'np.var(y)'] | 205,336 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_os.py | TestSendfile.sendfile_wrapper | sendfile_wrapper | A higher level wrapper representing how an application is supposed to use sendfile(). | [
"A",
"higher",
"level",
"wrapper",
"representing",
"how",
"an",
"application",
"is",
"supposed",
"to",
"use",
"sendfile()."
] | def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
while 1:
try:
if self.SUPPORT_HEADERS_TRAILERS:
return os.sendfile(sock, file, offset, nbytes, headers, trailers)
else:
return os.sendfile(sock, file, offset, nbytes)
... | ['def', 'sendfile_wrapper(self,', 'sock,', 'file,', 'offset,', 'nbytes,', 'headers=[],', 'trailers=[]):', 'while', '1:', 'try:', 'if', 'self.SUPPORT_HEADERS_TRAILERS:', 'return', 'os.sendfile(sock,', 'file,', 'offset,', 'nbytes,', 'headers,', 'trailers)', 'else:', 'return', 'os.sendfile(sock,', 'file,', 'offset,', 'nby... | 376,258 |
mj-will/nessai | test_plot.py | test_plot_1d_comparison_unstructured_missing_flag | test_plot_1d_comparison_unstructured_missing_flag | Test plotting live points in arrays are not structured. | [
"Test",
"plotting",
"live",
"points",
"in",
"arrays",
"are",
"not",
"structured."
] | def test_plot_1d_comparison_unstructured_missing_flag():
live_points = np.random.randn(10, 2)
with pytest.raises(RuntimeError) as excinfo:
plot.plot_1d_comparison(live_points, convert_to_live_points=False)
assert 'not structured array' in str(excinfo.value) | ['def', 'test_plot_1d_comparison_unstructured_missing_flag():', 'live_points', '=', 'np.random.randn(10,', '2)', 'with', 'pytest.raises(RuntimeError)', 'as', 'excinfo:', 'plot.plot_1d_comparison(live_points,', 'convert_to_live_points=False)', 'assert', "'not", 'structured', "array'", 'in', 'str(excinfo.value)'] | 292,368 |
jingjingli01/TGLS | utils_sent_min_kw_min.py | get_idf_dict | get_idf_dict | Returns mapping from word piece index to its inverse document frequency. | [
"Returns",
"mapping",
"from",
"word",
"piece",
"index",
"to",
"its",
"inverse",
"document",
"frequency."
] | def get_idf_dict(arr, tokenizer, nthreads=4):
idf_count = Counter()
num_docs = len(arr)
process_partial = partial(process, tokenizer=tokenizer)
with Pool(nthreads) as p:
idf_count.update(chain.from_iterable(p.map(process_partial, arr)))
idf_dict = defaultdict(lambda : log((num_docs + 1) / 1)... | ['def', 'get_idf_dict(arr,', 'tokenizer,', 'nthreads=4):', 'idf_count', '=', 'Counter()', 'num_docs', '=', 'len(arr)', 'process_partial', '=', 'partial(process,', 'tokenizer=tokenizer)', 'with', 'Pool(nthreads)', 'as', 'p:', 'idf_count.update(chain.from_iterable(p.map(process_partial,', 'arr)))', 'idf_dict', '=', 'defa... | 354,336 |
TerenceCYJ/S2HAND | fh_utils.py | plot_hand | plot_hand | Plots a hand stick figure into a matplotlib figure. | [
"Plots",
"a",
"hand",
"stick",
"figure",
"into",
"a",
"matplotlib",
"figure."
] | def plot_hand(axis, coords_hw, vis=None, color_fixed=None, linewidth='1', markersize=1, order='hw', draw_kp=True, dataset_name='FreiHand'):
if order == 'uv':
coords_hw = coords_hw[:, ::-1]
colors = np.array([[0.4, 0.4, 0.4], [0.4, 0.0, 0.0], [0.6, 0.0, 0.0], [0.8, 0.0, 0.0], [1.0, 0.0, 0.0], [0.4, 0.4, ... | ['def', 'plot_hand(axis,', 'coords_hw,', 'vis=None,', 'color_fixed=None,', "linewidth='1',", 'markersize=1,', "order='hw',", 'draw_kp=True,', "dataset_name='FreiHand'):", 'if', 'order', '==', "'uv':", 'coords_hw', '=', 'coords_hw[:,', '::-1]', 'colors', '=', 'np.array([[0.4,', '0.4,', '0.4],', '[0.4,', '0.0,', '0.0],',... | 327,300 |
enuguru/artificial_intelligence_and_machine_ | sql.py | Identifier.get_typecast | get_typecast | Returns the typecast or ``None`` of this object as a string. | [
"Returns",
"the",
"typecast",
"or",
"``None``",
"of",
"this",
"object",
"as",
"a",
"string."
] | def get_typecast(self):
marker = self.token_next_match(0, T.Punctuation, '::')
if marker is None:
return None
next_ = self.token_next(self.token_index(marker), False)
if next_ is None:
return None
return str(next_) | ['def', 'get_typecast(self):', 'marker', '=', 'self.token_next_match(0,', 'T.Punctuation,', "'::')", 'if', 'marker', 'is', 'None:', 'return', 'None', 'next_', '=', 'self.token_next(self.token_index(marker),', 'False)', 'if', 'next_', 'is', 'None:', 'return', 'None', 'return', 'str(next_)'] | 131,952 |
weimin17/Object-Detection_HelmetDetection | converter.py | get_image_format | get_image_format | Returns image format from filename. | [
"Returns",
"image",
"format",
"from",
"filename."
] | def get_image_format(filename):
filename = filename.lower()
if filename.endswith('jpeg') or filename.endswith('jpg'):
return 'jpeg'
elif filename.endswith('png'):
return 'png'
else:
raise ValueError('Unrecognized file format: %s' % filename) | ['def', 'get_image_format(filename):', 'filename', '=', 'filename.lower()', 'if', "filename.endswith('jpeg')", 'or', "filename.endswith('jpg'):", 'return', "'jpeg'", 'elif', "filename.endswith('png'):", 'return', "'png'", 'else:', 'raise', "ValueError('Unrecognized", 'file', 'format:', "%s'", '%', 'filename)'] | 761,425 |
facebookresearch/CompilerGym | compiler_env.py | CompilerEnv.compiler_version | compiler_version | The version string of the underlying compiler that this service supports. | [
"The",
"version",
"string",
"of",
"the",
"underlying",
"compiler",
"that",
"this",
"service",
"supports."
] | def compiler_version(self) -> str:
raise NotImplementedError('abstract method') | ['def', 'compiler_version(self)', '->', 'str:', 'raise', "NotImplementedError('abstract", "method')"] | 125,435 |
deepmind/dm_control | viewer.py | ManipulationController.set_rotate_mode | set_rotate_mode | Begins/ends an object rotation action. | [
"Begins/ends",
"an",
"object",
"rotation",
"action."
] | def set_rotate_mode(self, enable):
if enable:
self._action.begin(mujoco.mjtMouse.mjMOUSE_ROTATE_H)
else:
self._action.end(mujoco.mjtMouse.mjMOUSE_ROTATE_H) | ['def', 'set_rotate_mode(self,', 'enable):', 'if', 'enable:', 'self._action.begin(mujoco.mjtMouse.mjMOUSE_ROTATE_H)', 'else:', 'self._action.end(mujoco.mjtMouse.mjMOUSE_ROTATE_H)'] | 166,637 |
yekeren/Cap2Det | cap2det_model.py | Model.build_evaluation | build_evaluation | Build tf graph to evaluate the model. | [
"Build",
"tf",
"graph",
"to",
"evaluate",
"the",
"model."
] | def build_evaluation(self, predictions, examples, **kwargs):
return {} | ['def', 'build_evaluation(self,', 'predictions,', 'examples,', '**kwargs):', 'return', '{}'] | 108,955 |
jbwang1997/CrossKD | d2_wrapper.py | convert_d2_pred_to_datasample | convert_d2_pred_to_datasample | Convert the Detectron2's result to DetDataSample. | [
"Convert",
"the",
"Detectron2's",
"result",
"to",
"DetDataSample."
] | def convert_d2_pred_to_datasample(data_samples: SampleList, d2_results_list: list) -> SampleList:
assert len(data_samples) == len(d2_results_list)
for (data_sample, d2_results) in zip(data_samples, d2_results_list):
d2_instance = d2_results['instances']
results = InstanceData()
results.b... | ['def', 'convert_d2_pred_to_datasample(data_samples:', 'SampleList,', 'd2_results_list:', 'list)', '->', 'SampleList:', 'assert', 'len(data_samples)', '==', 'len(d2_results_list)', 'for', '(data_sample,', 'd2_results)', 'in', 'zip(data_samples,', 'd2_results_list):', 'd2_instance', '=', "d2_results['instances']", 'resu... | 491,226 |
ibarrien/SemiSupervisedLearning | expectation_maximization.py | EM_SSL.set_in_class_mask | set_in_class_mask | Data mask of class label. | [
"Data",
"mask",
"of",
"class",
"label."
] | def set_in_class_mask(self) -> None:
self.class_mask = self.label_vals == self.curr_class_idx
return None | ['def', 'set_in_class_mask(self)', '->', 'None:', 'self.class_mask', '=', 'self.label_vals', '==', 'self.curr_class_idx', 'return', 'None'] | 343,736 |
tensorflow/hub | export.py | parse_line | parse_line | Parses a line of a text embedding file. | [
"Parses",
"a",
"line",
"of",
"a",
"text",
"embedding",
"file."
] | def parse_line(line):
columns = line.split()
token = columns.pop(0)
values = [float(column) for column in columns]
return (token, values) | ['def', 'parse_line(line):', 'columns', '=', 'line.split()', 'token', '=', 'columns.pop(0)', 'values', '=', '[float(column)', 'for', 'column', 'in', 'columns]', 'return', '(token,', 'values)'] | 570,902 |
RLE-Foundation/rllte | utils.py | get_actor | get_actor | Get actor network based on action type. | [
"Get",
"actor",
"network",
"based",
"on",
"action",
"type."
] | def get_actor(action_type: str, actor_kwargs: Dict) -> nn.Module:
if action_type in ['Discrete', 'MultiBinary']:
actor_class = OnPolicyDiscreteActor
elif action_type == 'Box':
actor_class = OnPolicyBoxActor
elif action_type == 'MultiDiscrete':
actor_class = OnPolicyMultiDiscreteActor... | ['def', 'get_actor(action_type:', 'str,', 'actor_kwargs:', 'Dict)', '->', 'nn.Module:', 'if', 'action_type', 'in', "['Discrete',", "'MultiBinary']:", 'actor_class', '=', 'OnPolicyDiscreteActor', 'elif', 'action_type', '==', "'Box':", 'actor_class', '=', 'OnPolicyBoxActor', 'elif', 'action_type', '==', "'MultiDiscrete':... | 333,329 |
Nocami/PythonComputerVision-9-Image-Content-Classification | imtools.py | compute_average | compute_average | Compute the average of a list of images. | [
"Compute",
"the",
"average",
"of",
"a",
"list",
"of",
"images."
] | def compute_average(imlist):
averageim = array(Image.open(imlist[0]), 'f')
skipped = 0
for imname in imlist[1:]:
try:
averageim += array(Image.open(imname))
except:
print(imname + '...skipped')
skipped += 1
averageim /= len(imlist) - skipped
return... | ['def', 'compute_average(imlist):', 'averageim', '=', 'array(Image.open(imlist[0]),', "'f')", 'skipped', '=', '0', 'for', 'imname', 'in', 'imlist[1:]:', 'try:', 'averageim', '+=', 'array(Image.open(imname))', 'except:', 'print(imname', '+', "'...skipped')", 'skipped', '+=', '1', 'averageim', '/=', 'len(imlist)', '-', '... | 863,734 |
rajpurkarlab/CheXzero | zero_shot.py | predict | predict | FUNCTION: predict --------------------------------- This function runs the cxr images through the model and computes the cosine similarities between the images and the text embeddings. | [
"FUNCTION:",
"predict",
"---------------------------------",
"This",
"function",
"runs",
"the",
"cxr",
"images",
"through",
"the",
"model",
"and",
"computes",
"the",
"cosine",
"similarities",
"between",
"the",
"images",
"and",
"the",
"text",
"embeddings."
] | def predict(loader, model, zeroshot_weights, softmax_eval=True, verbose=0):
y_pred = []
with torch.no_grad():
for (i, data) in enumerate(tqdm(loader)):
images = data['img']
image_features = model.encode_image(images)
image_features /= image_features.norm(dim=-1, keepd... | ['def', 'predict(loader,', 'model,', 'zeroshot_weights,', 'softmax_eval=True,', 'verbose=0):', 'y_pred', '=', '[]', 'with', 'torch.no_grad():', 'for', '(i,', 'data)', 'in', 'enumerate(tqdm(loader)):', 'images', '=', "data['img']", 'image_features', '=', 'model.encode_image(images)', 'image_features', '/=', 'image_featu... | 105,177 |
jxhe/unify-parameter-efficient-tuning | check_copies.py | find_code_in_transformers | find_code_in_transformers | Find and return the code source code of `object_name`. | [
"Find",
"and",
"return",
"the",
"code",
"source",
"code",
"of",
"`object_name`."
] | def find_code_in_transformers(object_name):
parts = object_name.split('.')
i = 0
module = parts[i]
while i < len(parts) and (not os.path.isfile(os.path.join(TRANSFORMERS_PATH, f'{module}.py'))):
i += 1
if i < len(parts):
module = os.path.join(module, parts[i])
if i >= len... | ['def', 'find_code_in_transformers(object_name):', 'parts', '=', "object_name.split('.')", 'i', '=', '0', 'module', '=', 'parts[i]', 'while', 'i', '<', 'len(parts)', 'and', '(not', 'os.path.isfile(os.path.join(TRANSFORMERS_PATH,', "f'{module}.py'))):", 'i', '+=', '1', 'if', 'i', '<', 'len(parts):', 'module', '=', 'os.p... | 949,551 |
jshilong/DDQ | contour_expand.py | contour_expand | contour_expand | Expand kernel contours so that foreground pixels are assigned into instances. | [
"Expand",
"kernel",
"contours",
"so",
"that",
"foreground",
"pixels",
"are",
"assigned",
"into",
"instances."
] | def contour_expand(kernel_mask, internal_kernel_label, min_kernel_area, kernel_num):
assert isinstance(kernel_mask, (torch.Tensor, np.ndarray))
assert isinstance(internal_kernel_label, (torch.Tensor, np.ndarray))
assert isinstance(min_kernel_area, int)
assert isinstance(kernel_num, int)
if isinstanc... | ['def', 'contour_expand(kernel_mask,', 'internal_kernel_label,', 'min_kernel_area,', 'kernel_num):', 'assert', 'isinstance(kernel_mask,', '(torch.Tensor,', 'np.ndarray))', 'assert', 'isinstance(internal_kernel_label,', '(torch.Tensor,', 'np.ndarray))', 'assert', 'isinstance(min_kernel_area,', 'int)', 'assert', 'isinsta... | 499,082 |
roboflow/supervision | file.py | read_yaml_file | read_yaml_file | Read a yaml file and return a dict. | [
"Read",
"a",
"yaml",
"file",
"and",
"return",
"a",
"dict."
] | def read_yaml_file(file_path: str) -> dict:
with open(file_path, 'r') as file:
data = yaml.safe_load(file)
return data | ['def', 'read_yaml_file(file_path:', 'str)', '->', 'dict:', 'with', 'open(file_path,', "'r')", 'as', 'file:', 'data', '=', 'yaml.safe_load(file)', 'return', 'data'] | 882,106 |
feast-dev/feast | rockset.py | RocksetOnlineStore.online_write_batch | online_write_batch | Write a batch of feature rows to online Rockset store. | [
"Write",
"a",
"batch",
"of",
"feature",
"rows",
"to",
"online",
"Rockset",
"store."
] | def online_write_batch(self, config: RepoConfig, table: FeatureView, data: List[Tuple[EntityKeyProto, Dict[str, ValueProto], datetime, Optional[datetime]]], progress: Optional[Callable[[int], Any]]) -> None:
online_config = config.online_store
assert isinstance(online_config, RocksetOnlineStoreConfig)
rs = ... | ['def', 'online_write_batch(self,', 'config:', 'RepoConfig,', 'table:', 'FeatureView,', 'data:', 'List[Tuple[EntityKeyProto,', 'Dict[str,', 'ValueProto],', 'datetime,', 'Optional[datetime]]],', 'progress:', 'Optional[Callable[[int],', 'Any]])', '->', 'None:', 'online_config', '=', 'config.online_store', 'assert', 'isin... | 544,483 |
ahirsharan/MTL-Segmentation | misc.py | ensure_path | ensure_path | The function to make log path. | [
"The",
"function",
"to",
"make",
"log",
"path."
] | def ensure_path(path):
if os.path.exists(path):
pass
else:
os.mkdir(path) | ['def', 'ensure_path(path):', 'if', 'os.path.exists(path):', 'pass', 'else:', 'os.mkdir(path)'] | 642,896 |
dongliangcao/Self-Supervised-Multimodal-Shape-Matching | __init__.py | build_loss | build_loss | Build loss from options. | [
"Build",
"loss",
"from",
"options."
] | def build_loss(opt):
loss_type = opt.pop('type')
loss = LOSS_REGISTRY.get(loss_type)(**opt)
logger = get_root_logger()
logger.info(f'Loss [{loss.__class__.__name__}] is created.')
return loss | ['def', 'build_loss(opt):', 'loss_type', '=', "opt.pop('type')", 'loss', '=', 'LOSS_REGISTRY.get(loss_type)(**opt)', 'logger', '=', 'get_root_logger()', "logger.info(f'Loss", '[{loss.__class__.__name__}]', 'is', "created.')", 'return', 'loss'] | 342,107 |
uber/causalml | utils.py | make_tarreg_loss | make_tarreg_loss | Given a specified loss function, returns the same loss function with targeted regularization. | [
"Given",
"a",
"specified",
"loss",
"function,",
"returns",
"the",
"same",
"loss",
"function",
"with",
"targeted",
"regularization."
] | def make_tarreg_loss(ratio=1.0, dragonnet_loss=dragonnet_loss_binarycross):
def tarreg_ATE_unbounded_domain_loss(concat_true, concat_pred):
vanilla_loss = dragonnet_loss(concat_true, concat_pred)
y_true = concat_true[:, 0]
t_true = concat_true[:, 1]
y0_pred = concat_pred[:, 0]
... | ['def', 'make_tarreg_loss(ratio=1.0,', 'dragonnet_loss=dragonnet_loss_binarycross):', 'def', 'tarreg_ATE_unbounded_domain_loss(concat_true,', 'concat_pred):', 'vanilla_loss', '=', 'dragonnet_loss(concat_true,', 'concat_pred)', 'y_true', '=', 'concat_true[:,', '0]', 't_true', '=', 'concat_true[:,', '1]', 'y0_pred', '=',... | 456,475 |
ryu-ed/SpaceInvaders_Ros | math2html.py | ContainerSize.setmax | setmax | Set max width and/or height. | [
"Set",
"max",
"width",
"and/or",
"height."
] | def setmax(self, maxwidth=None, maxheight=None):
self.setvalue('maxwidth', maxwidth)
self.setvalue('maxheight', maxheight)
return self | ['def', 'setmax(self,', 'maxwidth=None,', 'maxheight=None):', "self.setvalue('maxwidth',", 'maxwidth)', "self.setvalue('maxheight',", 'maxheight)', 'return', 'self'] | 395,250 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.