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
TheCurryMan/MedicAI
tests.py
test_lower
test_lower
Return true if the variable is lowercased.
[ "Return", "true", "if", "the", "variable", "is", "lowercased." ]
def test_lower(value): return text_type(value).islower()
['def', 'test_lower(value):', 'return', 'text_type(value).islower()']
648,501
MinRegret/deluca
_gpc.py
GPC.get_action
get_action
Description: get action from state.
[ "Description:", "get", "action", "from", "state." ]
def get_action(self, state: jnp.ndarray) -> jnp.ndarray: return -self.K @ state + jnp.tensordot(self.M, self.last_h_noises(), axes=([0, 2], [0, 1]))
['def', 'get_action(self,', 'state:', 'jnp.ndarray)', '->', 'jnp.ndarray:', 'return', '-self.K', '@', 'state', '+', 'jnp.tensordot(self.M,', 'self.last_h_noises(),', 'axes=([0,', '2],', '[0,', '1]))']
537,852
AxeldeRomblay/MLBox
test_optimiser.py
test_init_optimiser
test_init_optimiser
Test init method of Optimiser class.
[ "Test", "init", "method", "of", "Optimiser", "class." ]
def test_init_optimiser(): with pytest.warns(UserWarning) as record: optimiser = Optimiser() assert len(record) == 1 assert not optimiser.scoring assert optimiser.n_folds == 2 assert optimiser.random_state == 1 assert optimiser.to_path == 'save' assert optimiser.verbose
['def', 'test_init_optimiser():', 'with', 'pytest.warns(UserWarning)', 'as', 'record:', 'optimiser', '=', 'Optimiser()', 'assert', 'len(record)', '==', '1', 'assert', 'not', 'optimiser.scoring', 'assert', 'optimiser.n_folds', '==', '2', 'assert', 'optimiser.random_state', '==', '1', 'assert', 'optimiser.to_path', '==',...
630,040
VITA-Group/CV_LTH_Pre-training
utils.py
yolobox2label
yolobox2label
Transform yolo box labels to yxyx box labels.
[ "Transform", "yolo", "box", "labels", "to", "yxyx", "box", "labels." ]
def yolobox2label(box, info_img): (h, w, nh, nw, dx, dy) = info_img (y1, x1, y2, x2) = box box_h = (y2 - y1) / nh * h box_w = (x2 - x1) / nw * w y1 = (y1 - dy) / nh * h x1 = (x1 - dx) / nw * w label = [y1, x1, y1 + box_h, x1 + box_w] return label
['def', 'yolobox2label(box,', 'info_img):', '(h,', 'w,', 'nh,', 'nw,', 'dx,', 'dy)', '=', 'info_img', '(y1,', 'x1,', 'y2,', 'x2)', '=', 'box', 'box_h', '=', '(y2', '-', 'y1)', '/', 'nh', '*', 'h', 'box_w', '=', '(x2', '-', 'x1)', '/', 'nw', '*', 'w', 'y1', '=', '(y1', '-', 'dy)', '/', 'nh', '*', 'h', 'x1', '=', '(x1', ...
524,244
myothida/Supervised-Machine-Learning
builder.py
buildCOLR
buildCOLR
Build COLR table from color layers mapping.
[ "Build", "COLR", "table", "from", "color", "layers", "mapping." ]
def buildCOLR(colorGlyphs: _ColorGlyphsDict, version: Optional[int]=None, *, glyphMap: Optional[Mapping[str, int]]=None, varStore: Optional[ot.VarStore]=None, varIndexMap: Optional[ot.DeltaSetIndexMap]=None, clipBoxes: Optional[Dict[str, _ClipBoxInput]]=None, allowLayerReuse: bool=True) -> C_O_L_R_.table_C_O_L_R_: ...
['def', 'buildCOLR(colorGlyphs:', '_ColorGlyphsDict,', 'version:', 'Optional[int]=None,', '*,', 'glyphMap:', 'Optional[Mapping[str,', 'int]]=None,', 'varStore:', 'Optional[ot.VarStore]=None,', 'varIndexMap:', 'Optional[ot.DeltaSetIndexMap]=None,', 'clipBoxes:', 'Optional[Dict[str,', '_ClipBoxInput]]=None,', 'allowLayer...
360,752
openvinotoolkit/training_extensions
annotation.py
AnnotationSceneEntity.contains_any
contains_any
Checks whether the annotation contains any labels in the input parameter.
[ "Checks", "whether", "the", "annotation", "contains", "any", "labels", "in", "the", "input", "parameter." ]
def contains_any(self, labels: List[LabelEntity]) -> bool: label_names = {label.name for label in labels} return len({label.name for label in self.get_labels(include_empty=True)}.intersection(label_names)) != 0
['def', 'contains_any(self,', 'labels:', 'List[LabelEntity])', '->', 'bool:', 'label_names', '=', '{label.name', 'for', 'label', 'in', 'labels}', 'return', 'len({label.name', 'for', 'label', 'in', 'self.get_labels(include_empty=True)}.intersection(label_names))', '!=', '0']
918,470
deepmind/dm_control
engine.py
Physics.after_reset
after_reset
Runs after resetting internal variables of the physics simulation.
[ "Runs", "after", "resetting", "internal", "variables", "of", "the", "physics", "simulation." ]
def after_reset(self): with self.model.disable('actuation'): self.forward()
['def', 'after_reset(self):', 'with', "self.model.disable('actuation'):", 'self.forward()']
166,158
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
turtle.py
config_dict
config_dict
Convert content of config-file into dictionary.
[ "Convert", "content", "of", "config-file", "into", "dictionary." ]
def config_dict(filename): with open(filename, 'r') as f: cfglines = f.readlines() cfgdict = {} for line in cfglines: line = line.strip() if not line or line.startswith('#'): continue try: (key, value) = line.split('=') except ValueError: ...
['def', 'config_dict(filename):', 'with', 'open(filename,', "'r')", 'as', 'f:', 'cfglines', '=', 'f.readlines()', 'cfgdict', '=', '{}', 'for', 'line', 'in', 'cfglines:', 'line', '=', 'line.strip()', 'if', 'not', 'line', 'or', "line.startswith('#'):", 'continue', 'try:', '(key,', 'value)', '=', "line.split('=')", 'excep...
429,765
ryu-ed/SpaceInvaders_Ros
surface_test.py
SurfaceTypeTest.test_convert_alpha__pixel_format_as_surface_subclass
test_convert_alpha__pixel_format_as_surface_subclass
Ensure convert_alpha accepts a Surface subclass argument.
[ "Ensure", "convert_alpha", "accepts", "a", "Surface", "subclass", "argument." ]
def test_convert_alpha__pixel_format_as_surface_subclass(self): expected_size = (23, 17) convert_surface = SurfaceSubclass(expected_size, SRCALPHA, 32) depth_surface = SurfaceSubclass((31, 57), SRCALPHA, 32) pygame.display.init() try: pygame.display.set_mode((60, 60)) surface = conve...
['def', 'test_convert_alpha__pixel_format_as_surface_subclass(self):', 'expected_size', '=', '(23,', '17)', 'convert_surface', '=', 'SurfaceSubclass(expected_size,', 'SRCALPHA,', '32)', 'depth_surface', '=', 'SurfaceSubclass((31,', '57),', 'SRCALPHA,', '32)', 'pygame.display.init()', 'try:', 'pygame.display.set_mode((6...
369,178
ChandlerBang/SelfTask-GNN
sample.py
Sampler.get_label_and_idxes
get_label_and_idxes
Return all labels and indexes.
[ "Return", "all", "labels", "and", "indexes." ]
def get_label_and_idxes(self, cuda): if cuda: return (self.labels_torch.cuda(), self.idx_train_torch.cuda(), self.idx_val_torch.cuda(), self.idx_test_torch.cuda()) return (self.labels_torch, self.idx_train_torch, self.idx_val_torch, self.idx_test_torch)
['def', 'get_label_and_idxes(self,', 'cuda):', 'if', 'cuda:', 'return', '(self.labels_torch.cuda(),', 'self.idx_train_torch.cuda(),', 'self.idx_val_torch.cuda(),', 'self.idx_test_torch.cuda())', 'return', '(self.labels_torch,', 'self.idx_train_torch,', 'self.idx_val_torch,', 'self.idx_test_torch)']
342,465
arshpreetsingh/quantopian-machinelearning
test_completer.py
TestCompleter.test_completion_have_signature
test_completion_have_signature
Lets make sure jedi is capable of pulling out the signature of the function we are completing.
[ "Lets", "make", "sure", "jedi", "is", "capable", "of", "pulling", "out", "the", "signature", "of", "the", "function", "we", "are", "completing." ]
def test_completion_have_signature(self): ip = get_ipython() with provisionalcompleter(): ip.Completer.use_jedi = True completions = ip.Completer.completions('ope', 3) c = next(completions) ip.Completer.use_jedi = False assert 'file' in c.signature, 'Signature of function was...
['def', 'test_completion_have_signature(self):', 'ip', '=', 'get_ipython()', 'with', 'provisionalcompleter():', 'ip.Completer.use_jedi', '=', 'True', 'completions', '=', "ip.Completer.completions('ope',", '3)', 'c', '=', 'next(completions)', 'ip.Completer.use_jedi', '=', 'False', 'assert', "'file'", 'in', 'c.signature,...
886,576
alibaba-mmai-research/HiCo
distributed.py
init_distributed_training
init_distributed_training
Initialize variables needed for distributed training.
[ "Initialize", "variables", "needed", "for", "distributed", "training." ]
def init_distributed_training(cfg): if cfg.NUM_GPUS <= 1: return num_gpus_per_machine = cfg.NUM_GPUS num_machines = dist.get_world_size() // num_gpus_per_machine for i in range(num_machines): ranks_on_i = list(range(i * num_gpus_per_machine, (i + 1) * num_gpus_per_machine)) pg = ...
['def', 'init_distributed_training(cfg):', 'if', 'cfg.NUM_GPUS', '<=', '1:', 'return', 'num_gpus_per_machine', '=', 'cfg.NUM_GPUS', 'num_machines', '=', 'dist.get_world_size()', '//', 'num_gpus_per_machine', 'for', 'i', 'in', 'range(num_machines):', 'ranks_on_i', '=', 'list(range(i', '*', 'num_gpus_per_machine,', '(i',...
206,188
openvinotoolkit/training_extensions
custom_cls_head.py
CustomNonLinearClsHead.loss
loss
Calculate loss for given cls_score/gt_label.
[ "Calculate", "loss", "for", "given", "cls_score/gt_label." ]
def loss(self, cls_score, gt_label, feature=None): num_samples = len(cls_score) losses = dict() if self.loss_type == 'IBLoss': loss = self.compute_loss(cls_score, gt_label, feature=feature) else: loss = self.compute_loss(cls_score, gt_label, avg_factor=num_samples) if self.cal_acc: ...
['def', 'loss(self,', 'cls_score,', 'gt_label,', 'feature=None):', 'num_samples', '=', 'len(cls_score)', 'losses', '=', 'dict()', 'if', 'self.loss_type', '==', "'IBLoss':", 'loss', '=', 'self.compute_loss(cls_score,', 'gt_label,', 'feature=feature)', 'else:', 'loss', '=', 'self.compute_loss(cls_score,', 'gt_label,', 'a...
904,029
inseq-team/inseq
gradient_attribution.py
GradientAttributionRegistry.attribute_step
attribute_step
Performs a single attribution step for the specified attribution arguments.
[ "Performs", "a", "single", "attribution", "step", "for", "the", "specified", "attribution", "arguments." ]
def attribute_step(self, attribute_fn_main_args: Dict[str, Any], attribution_args: Dict[str, Any]={}) -> GranularFeatureAttributionStepOutput: attr = self.method.attribute(**attribute_fn_main_args, **attribution_args) deltas = None if attribution_args.get('return_convergence_delta', False) and hasattr(self....
['def', 'attribute_step(self,', 'attribute_fn_main_args:', 'Dict[str,', 'Any],', 'attribution_args:', 'Dict[str,', 'Any]={})', '->', 'GranularFeatureAttributionStepOutput:', 'attr', '=', 'self.method.attribute(**attribute_fn_main_args,', '**attribution_args)', 'deltas', '=', 'None', 'if', "attribution_args.get('return_...
613,920
rudranil723/mini-main
live_render.py
LiveRender.set_renderable
set_renderable
Set a new renderable.
[ "Set", "a", "new", "renderable." ]
def set_renderable(self, renderable: RenderableType) -> None: self.renderable = renderable
['def', 'set_renderable(self,', 'renderable:', 'RenderableType)', '->', 'None:', 'self.renderable', '=', 'renderable']
268,908
SALT-NLP/Adaptive-Compositional-Modules
retrieval_rag.py
Index.get_top_docs
get_top_docs
For each query in the batch, retrieves ``n_docs`` documents.
[ "For", "each", "query", "in", "the", "batch,", "retrieves", "``n_docs``", "documents." ]
def get_top_docs(self, question_hidden_states: np.ndarray, n_docs=5) -> Tuple[np.ndarray, np.ndarray]: raise NotImplementedError
['def', 'get_top_docs(self,', 'question_hidden_states:', 'np.ndarray,', 'n_docs=5)', '->', 'Tuple[np.ndarray,', 'np.ndarray]:', 'raise', 'NotImplementedError']
409,038
google-research/scenic
segmentation_datasets.py
augment_example
augment_example
Augments the given train image.
[ "Augments", "the", "given", "train", "image." ]
def augment_example(example: Dict[str, tf.Tensor], dataset_configs: ml_collections.ConfigDict, dtype: tf.DType=tf.float32, resize: Optional[List[int]]=None, rng: int=0, **inception_crop_kws): image = example['inputs'] mask = example['label'][..., tf.newaxis] (image, mask) = dataset_utils.inception_crop_with...
['def', 'augment_example(example:', 'Dict[str,', 'tf.Tensor],', 'dataset_configs:', 'ml_collections.ConfigDict,', 'dtype:', 'tf.DType=tf.float32,', 'resize:', 'Optional[List[int]]=None,', 'rng:', 'int=0,', '**inception_crop_kws):', 'image', '=', "example['inputs']", 'mask', '=', "example['label'][...,", 'tf.newaxis]', ...
847,319
QData/deepWordBug
math2html.py
Container.getparameter
getparameter
Get the value of a parameter, if present.
[ "Get", "the", "value", "of", "a", "parameter,", "if", "present." ]
def getparameter(self, name): if not name in self.parameters: return None return self.parameters[name]
['def', 'getparameter(self,', 'name):', 'if', 'not', 'name', 'in', 'self.parameters:', 'return', 'None', 'return', 'self.parameters[name]']
542,433
43Carrig/recurrent_neural_networks_practice
nn_impl.py
normalize_moments
normalize_moments
Calculate the mean and variance of based on the sufficient statistics.
[ "Calculate", "the", "mean", "and", "variance", "of", "based", "on", "the", "sufficient", "statistics." ]
def normalize_moments(counts, mean_ss, variance_ss, shift, name=None): with ops.name_scope(name, 'normalize', [counts, mean_ss, variance_ss, shift]): divisor = math_ops.reciprocal(counts, name='divisor') if shift is not None: shifted_mean = math_ops.multiply(mean_ss, divisor, name='shift...
['def', 'normalize_moments(counts,', 'mean_ss,', 'variance_ss,', 'shift,', 'name=None):', 'with', 'ops.name_scope(name,', "'normalize',", '[counts,', 'mean_ss,', 'variance_ss,', 'shift]):', 'divisor', '=', 'math_ops.reciprocal(counts,', "name='divisor')", 'if', 'shift', 'is', 'not', 'None:', 'shifted_mean', '=', 'math_...
338,863
tobegit3hub/deep_image_model
stochastic_gradient_estimators.py
get_score_function_with_baseline
get_score_function_with_baseline
Score function estimator with baseline function.
[ "Score", "function", "estimator", "with", "baseline", "function." ]
def get_score_function_with_baseline(baseline_fn=None, name='ScoreFunction'): if baseline_fn is None: baseline_fn = get_mean_baseline() def score_function_with_baseline(stochastic_tensor, value, loss): with ops.name_scope(name): b = baseline_fn(stochastic_tensor, loss) r...
['def', 'get_score_function_with_baseline(baseline_fn=None,', "name='ScoreFunction'):", 'if', 'baseline_fn', 'is', 'None:', 'baseline_fn', '=', 'get_mean_baseline()', 'def', 'score_function_with_baseline(stochastic_tensor,', 'value,', 'loss):', 'with', 'ops.name_scope(name):', 'b', '=', 'baseline_fn(stochastic_tensor,'...
181,100
myothida/Supervised-Machine-Learning
transforms.py
Affine2D.set
set
Set this transformation from the frozen copy of another `Affine2DBase` object.
[ "Set", "this", "transformation", "from", "the", "frozen", "copy", "of", "another", "`Affine2DBase`", "object." ]
def set(self, other): _api.check_isinstance(Affine2DBase, other=other) self._mtx = other.get_matrix() self.invalidate()
['def', 'set(self,', 'other):', '_api.check_isinstance(Affine2DBase,', 'other=other)', 'self._mtx', '=', 'other.get_matrix()', 'self.invalidate()']
362,424
facebookresearch/dmae_st
meters.py
get_map
get_map
Compute mAP for multi-label case.
[ "Compute", "mAP", "for", "multi-label", "case." ]
def get_map(preds, labels): print('Getting mAP for {} examples'.format(preds.shape[0])) preds = preds[:, ~np.all(labels == 0, axis=0)] labels = labels[:, ~np.all(labels == 0, axis=0)] aps = [0] try: aps = average_precision_score(labels, preds, average=None) except ValueError: pri...
['def', 'get_map(preds,', 'labels):', "print('Getting", 'mAP', 'for', '{}', "examples'.format(preds.shape[0]))", 'preds', '=', 'preds[:,', '~np.all(labels', '==', '0,', 'axis=0)]', 'labels', '=', 'labels[:,', '~np.all(labels', '==', '0,', 'axis=0)]', 'aps', '=', '[0]', 'try:', 'aps', '=', 'average_precision_score(label...
521,996
google-research/scenic
vivit_multimodal.py
ViViTMultiMaskedAutoencoder.apply_dense_layer
apply_dense_layer
Apply the regressor for each modality.
[ "Apply", "the", "regressor", "for", "each", "modality." ]
def apply_dense_layer(self, x_prelogits_dict: ArrayDict) -> ArrayDict: x_logits_dict = {} for (key, x_prelogits) in x_prelogits_dict.items(): x_logits = nn.Dense(self.num_classes_dict[key], kernel_init=nn.initializers.zeros, name=f'output_projection_{key}')(x_prelogits) x_logits_dict[key] = x_lo...
['def', 'apply_dense_layer(self,', 'x_prelogits_dict:', 'ArrayDict)', '->', 'ArrayDict:', 'x_logits_dict', '=', '{}', 'for', '(key,', 'x_prelogits)', 'in', 'x_prelogits_dict.items():', 'x_logits', '=', 'nn.Dense(self.num_classes_dict[key],', 'kernel_init=nn.initializers.zeros,', "name=f'output_projection_{key}')(x_prel...
846,464
TrellixVulnTeam/Unsupervised_Learning_HFI7
resolvers.py
Criterion.from_requirement
from_requirement
Build an instance from a requirement.
[ "Build", "an", "instance", "from", "a", "requirement." ]
def from_requirement(cls, provider, requirement, parent): cands = build_iter_view(provider.find_matches([requirement])) infos = [RequirementInformation(requirement, parent)] criterion = cls(cands, infos, incompatibilities=[]) if not cands: raise RequirementsConflicted(criterion) return crite...
['def', 'from_requirement(cls,', 'provider,', 'requirement,', 'parent):', 'cands', '=', 'build_iter_view(provider.find_matches([requirement]))', 'infos', '=', '[RequirementInformation(requirement,', 'parent)]', 'criterion', '=', 'cls(cands,', 'infos,', 'incompatibilities=[])', 'if', 'not', 'cands:', 'raise', 'Requireme...
434,604
nicknochnack/RealTimeSignLanguageTFJS
optimizer_factory_test.py
OptimizerFactoryTest.test_learning_rate_with_decay_and_warmup
test_learning_rate_with_decay_and_warmup
Basic smoke test for syntax.
[ "Basic", "smoke", "test", "for", "syntax." ]
def test_learning_rate_with_decay_and_warmup(self, lr_decay_type): params = base_configs.LearningRateConfig(name=lr_decay_type, initial_lr=0.01, decay_rate=0.01, decay_epochs=1, warmup_epochs=1, scale_by_batch_size=0.01, examples_per_epoch=1, boundaries=[0], multipliers=[0, 1]) batch_size = 1 train_epochs =...
['def', 'test_learning_rate_with_decay_and_warmup(self,', 'lr_decay_type):', 'params', '=', 'base_configs.LearningRateConfig(name=lr_decay_type,', 'initial_lr=0.01,', 'decay_rate=0.01,', 'decay_epochs=1,', 'warmup_epochs=1,', 'scale_by_batch_size=0.01,', 'examples_per_epoch=1,', 'boundaries=[0],', 'multipliers=[0,', '1...
851,197
sunishsheth2009/ChatterBot
unitofwork.py
UOWTransaction.remove_state_actions
remove_state_actions
remove pending actions for a state from the uowtransaction.
[ "remove", "pending", "actions", "for", "a", "state", "from", "the", "uowtransaction." ]
def remove_state_actions(self, state): isdelete = self.states[state][0] self.states[state] = (isdelete, True)
['def', 'remove_state_actions(self,', 'state):', 'isdelete', '=', 'self.states[state][0]', 'self.states[state]', '=', '(isdelete,', 'True)']
481,503
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
delf_v1.py
DelfV1.GetAttentionPrelogit
GetAttentionPrelogit
Constructs attention model on resnet_v1_50.
[ "Constructs", "attention", "model", "on", "resnet_v1_50." ]
def GetAttentionPrelogit(self, images, weight_decay=0.0001, attention_nonlinear=_SUPPORTED_ATTENTION_NONLINEARITY[0], attention_type=_SUPPORTED_ATTENTION_TYPES[0], kernel=1, training_resnet=False, training_attention=False, reuse=False, use_batch_norm=True): with slim.arg_scope(resnet_v1.resnet_arg_scope(use_batch_n...
['def', 'GetAttentionPrelogit(self,', 'images,', 'weight_decay=0.0001,', 'attention_nonlinear=_SUPPORTED_ATTENTION_NONLINEARITY[0],', 'attention_type=_SUPPORTED_ATTENTION_TYPES[0],', 'kernel=1,', 'training_resnet=False,', 'training_attention=False,', 'reuse=False,', 'use_batch_norm=True):', 'with', 'slim.arg_scope(resn...
47,451
thaines/helit
params_sets.py
ParamsRange.setP2List
setP2List
Sets the list of P2 values.
[ "Sets", "the", "list", "of", "P2", "values." ]
def setP2List(self, p2): self.p2 = p2
['def', 'setP2List(self,', 'p2):', 'self.p2', '=', 'p2']
592,576
deepmind/meltingpot
policy_factory.py
PolicyFactory.timestep_spec
timestep_spec
Returns spec of the timestep expected by the policy.
[ "Returns", "spec", "of", "the", "timestep", "expected", "by", "the", "policy." ]
def timestep_spec(self) -> dm_env.TimeStep: return self._timestep_spec
['def', 'timestep_spec(self)', '->', 'dm_env.TimeStep:', 'return', 'self._timestep_spec']
285,912
zihuitang/medical_AI_platform
mailbox.py
_mboxMMDFMessage.get_flags
get_flags
Return as a string the flags that are set.
[ "Return", "as", "a", "string", "the", "flags", "that", "are", "set." ]
def get_flags(self): return self.get('Status', '') + self.get('X-Status', '')
['def', 'get_flags(self):', 'return', "self.get('Status',", "'')", '+', "self.get('X-Status',", "'')"]
280,783
ryu-ed/SpaceInvaders_Ros
test_special_matrices.py
TestToeplitz.test_scalar_00
test_scalar_00
Scalar arguments still produce a 2D array.
[ "Scalar", "arguments", "still", "produce", "a", "2D", "array." ]
def test_scalar_00(self): t = toeplitz(10) assert_array_equal(t, [[10]]) t = toeplitz(10, 20) assert_array_equal(t, [[10]])
['def', 'test_scalar_00(self):', 't', '=', 'toeplitz(10)', 'assert_array_equal(t,', '[[10]])', 't', '=', 'toeplitz(10,', '20)', 'assert_array_equal(t,', '[[10]])']
370,572
Kvatsx/Artificial-Intelligence-Assignments
hooks.py
clipboard_get
clipboard_get
Get text from the clipboard.
[ "Get", "text", "from", "the", "clipboard." ]
def clipboard_get(self): from IPython.lib.clipboard import osx_clipboard_get, tkinter_clipboard_get, win32_clipboard_get if sys.platform == 'win32': chain = [win32_clipboard_get, tkinter_clipboard_get] elif sys.platform == 'darwin': chain = [osx_clipboard_get, tkinter_clipboard_get] else...
['def', 'clipboard_get(self):', 'from', 'IPython.lib.clipboard', 'import', 'osx_clipboard_get,', 'tkinter_clipboard_get,', 'win32_clipboard_get', 'if', 'sys.platform', '==', "'win32':", 'chain', '=', '[win32_clipboard_get,', 'tkinter_clipboard_get]', 'elif', 'sys.platform', '==', "'darwin':", 'chain', '=', '[osx_clipbo...
38,008
ForrestPi/ObjectDetectionTricks
distribution_test.py
TestDistribution.testAlphaZeroSamplesMatchACauchyDistribution
testAlphaZeroSamplesMatchACauchyDistribution
Tests that samples when alpha=0 match a Cauchy distribution.
[ "Tests", "that", "samples", "when", "alpha=0", "match", "a", "Cauchy", "distribution." ]
def testAlphaZeroSamplesMatchACauchyDistribution(self, float_dtype): num_samples = 16384 scale = float_dtype(1.7) samples = self._distribution.draw_samples(np.zeros(num_samples, dtype=float_dtype), scale * np.ones(num_samples, dtype=float_dtype)) ks_statistic = scipy.stats.kstest(samples, 'cauchy', (0.0...
['def', 'testAlphaZeroSamplesMatchACauchyDistribution(self,', 'float_dtype):', 'num_samples', '=', '16384', 'scale', '=', 'float_dtype(1.7)', 'samples', '=', 'self._distribution.draw_samples(np.zeros(num_samples,', 'dtype=float_dtype),', 'scale', '*', 'np.ones(num_samples,', 'dtype=float_dtype))', 'ks_statistic', '=', ...
744,693
ddbourgin/numpy-ml
layers.py
BatchNorm1D.reset_running_stats
reset_running_stats
Reset the running mean and variance estimates to 0 and 1.
[ "Reset", "the", "running", "mean", "and", "variance", "estimates", "to", "0", "and", "1." ]
def reset_running_stats(self): assert self.trainable, 'Layer is frozen' self.parameters['running_mean'] = np.zeros(self.n_in) self.parameters['running_var'] = np.ones(self.n_in)
['def', 'reset_running_stats(self):', 'assert', 'self.trainable,', "'Layer", 'is', "frozen'", "self.parameters['running_mean']", '=', 'np.zeros(self.n_in)', "self.parameters['running_var']", '=', 'np.ones(self.n_in)']
730,149
weimin17/Object-Detection_HelmetDetection
converter.py
read_test_annotations
read_test_annotations
Reads test data annotations.
[ "Reads", "test", "data", "annotations." ]
def read_test_annotations(test_dir): files = tf.gfile.ListDirectory(os.path.join(test_dir, 'images')) return [(os.path.join(test_dir, 'images', f), None) for f in files if f.endswith('.JPEG')]
['def', 'read_test_annotations(test_dir):', 'files', '=', 'tf.gfile.ListDirectory(os.path.join(test_dir,', "'images'))", 'return', '[(os.path.join(test_dir,', "'images',", 'f),', 'None)', 'for', 'f', 'in', 'files', 'if', "f.endswith('.JPEG')]"]
761,424
Megvii-BaseDetection/cvpods
file_io.py
PathManager.exists
exists
Checks if there is a resource at the given URI.
[ "Checks", "if", "there", "is", "a", "resource", "at", "the", "given", "URI." ]
def exists(path: str) -> bool: return megfile.smart_exists(path)
['def', 'exists(path:', 'str)', '->', 'bool:', 'return', 'megfile.smart_exists(path)']
523,209
ahthie7u/cockpit
utils_transforms.py
BatchGradTransformsHook.param_hook
param_hook
Execute all transformations and store results as dictionary in the parameter.
[ "Execute", "all", "transformations", "and", "store", "results", "as", "dictionary", "in", "the", "parameter." ]
def param_hook(self, param: Tensor): param.grad_batch._param_weakref = weakref.ref(param) param.grad_batch_transforms = {key: func(param.grad_batch) for (key, func) in self._transforms.items()}
['def', 'param_hook(self,', 'param:', 'Tensor):', 'param.grad_batch._param_weakref', '=', 'weakref.ref(param)', 'param.grad_batch_transforms', '=', '{key:', 'func(param.grad_batch)', 'for', '(key,', 'func)', 'in', 'self._transforms.items()}']
492,708
zwl-max/road_object_detection
autoaugment_utils.py
bbox_wrapper
bbox_wrapper
Adds a bboxes function argument to func and returns unchanged bboxes.
[ "Adds", "a", "bboxes", "function", "argument", "to", "func", "and", "returns", "unchanged", "bboxes." ]
def bbox_wrapper(func): def wrapper(images, bboxes, *args, **kwargs): return (func(images, *args, **kwargs), bboxes) return wrapper
['def', 'bbox_wrapper(func):', 'def', 'wrapper(images,', 'bboxes,', '*args,', '**kwargs):', 'return', '(func(images,', '*args,', '**kwargs),', 'bboxes)', 'return', 'wrapper']
825,564
arshpreetsingh/quantopian-machinelearning
managers.py
BlockManager.delete
delete
Delete selected item (items if non-unique) in-place.
[ "Delete", "selected", "item", "(items", "if", "non-unique)", "in-place." ]
def delete(self, item): indexer = self.items.get_loc(item) is_deleted = np.zeros(self.shape[0], dtype=np.bool_) is_deleted[indexer] = True ref_loc_offset = -is_deleted.cumsum() is_blk_deleted = [False] * len(self.blocks) if isinstance(indexer, int): affected_start = indexer else: ...
['def', 'delete(self,', 'item):', 'indexer', '=', 'self.items.get_loc(item)', 'is_deleted', '=', 'np.zeros(self.shape[0],', 'dtype=np.bool_)', 'is_deleted[indexer]', '=', 'True', 'ref_loc_offset', '=', '-is_deleted.cumsum()', 'is_blk_deleted', '=', '[False]', '*', 'len(self.blocks)', 'if', 'isinstance(indexer,', 'int):...
890,275
gradio-app/gradio
utils.py
Status.msg_to_status
msg_to_status
Map the raw message from the backend to the status code presented to users.
[ "Map", "the", "raw", "message", "from", "the", "backend", "to", "the", "status", "code", "presented", "to", "users." ]
def msg_to_status(msg: str) -> Status: return {'send_hash': Status.JOINING_QUEUE, 'queue_full': Status.QUEUE_FULL, 'estimation': Status.IN_QUEUE, 'send_data': Status.SENDING_DATA, 'process_starts': Status.PROCESSING, 'process_generating': Status.ITERATING, 'process_completed': Status.FINISHED, 'progress': Status.PR...
['def', 'msg_to_status(msg:', 'str)', '->', 'Status:', 'return', "{'send_hash':", 'Status.JOINING_QUEUE,', "'queue_full':", 'Status.QUEUE_FULL,', "'estimation':", 'Status.IN_QUEUE,', "'send_data':", 'Status.SENDING_DATA,', "'process_starts':", 'Status.PROCESSING,', "'process_generating':", 'Status.ITERATING,', "'proces...
578,808
43Carrig/recurrent_neural_networks_practice
debug_data.py
DebugDumpDir.node_op_type
node_op_type
Get the op type of given node.
[ "Get", "the", "op", "type", "of", "given", "node." ]
def node_op_type(self, node_name, device_name=None): if not self._debug_graphs: raise LookupError('Node op types are not loaded from partition graphs yet.') device_name = self._infer_device_name(device_name, node_name) return self._debug_graphs[device_name].node_op_types[node_name]
['def', 'node_op_type(self,', 'node_name,', 'device_name=None):', 'if', 'not', 'self._debug_graphs:', 'raise', "LookupError('Node", 'op', 'types', 'are', 'not', 'loaded', 'from', 'partition', 'graphs', "yet.')", 'device_name', '=', 'self._infer_device_name(device_name,', 'node_name)', 'return', 'self._debug_graphs[devi...
335,951
Farama-Foundation/Minigrid
test_envs.py
test_max_steps_argument
test_max_steps_argument
Test that when initializing an environment with a fixed number of steps per episode (`max_steps` argument), the episode will be truncated after taking that number of steps.
[ "Test", "that", "when", "initializing", "an", "environment", "with", "a", "fixed", "number", "of", "steps", "per", "episode", "(`max_steps`", "argument),", "the", "episode", "will", "be", "truncated", "after", "taking", "that", "number", "of", "steps." ]
def test_max_steps_argument(env_spec): max_steps = 50 env = env_spec.make(max_steps=max_steps) env.reset() step_count = 0 while True: (_, _, terminated, truncated, _) = env.step(4) step_count += 1 if truncated: assert step_count == max_steps step_count...
['def', 'test_max_steps_argument(env_spec):', 'max_steps', '=', '50', 'env', '=', 'env_spec.make(max_steps=max_steps)', 'env.reset()', 'step_count', '=', '0', 'while', 'True:', '(_,', '_,', 'terminated,', 'truncated,', '_)', '=', 'env.step(4)', 'step_count', '+=', '1', 'if', 'truncated:', 'assert', 'step_count', '==', ...
271,634
deepmind/brave
video_sampling.py
pad_and_center_crop_window
pad_and_center_crop_window
Compute a crop window for a padded center crop of the given image shape.
[ "Compute", "a", "crop", "window", "for", "a", "padded", "center", "crop", "of", "the", "given", "image", "shape." ]
def pad_and_center_crop_window(image_shape: tf.Tensor, padding: int=16) -> tf.Tensor: image_shape = image_shape[:2] min_image_side = tf.math.reduce_min(image_shape) image_height = image_shape[0] image_width = image_shape[1] tf.debugging.assert_greater(min_image_side, 2 * padding) offset_y = tf.c...
['def', 'pad_and_center_crop_window(image_shape:', 'tf.Tensor,', 'padding:', 'int=16)', '->', 'tf.Tensor:', 'image_shape', '=', 'image_shape[:2]', 'min_image_side', '=', 'tf.math.reduce_min(image_shape)', 'image_height', '=', 'image_shape[0]', 'image_width', '=', 'image_shape[1]', 'tf.debugging.assert_greater(min_image...
108,347
OpenMDAO/OpenMDAO-Framework
array.py
Array.error
error
Returns an informative and descriptive error string.
[ "Returns", "an", "informative", "and", "descriptive", "error", "string." ]
def error(self, obj, name, value): wtype = 'value' wvalue = value info = 'an array-like object' if self.shape and hasattr(value, 'shape') and value.shape: if self.shape != value.shape: info += ' of shape %s' % str(self.shape) wtype = 'shape' wvalue = str(value...
['def', 'error(self,', 'obj,', 'name,', 'value):', 'wtype', '=', "'value'", 'wvalue', '=', 'value', 'info', '=', "'an", 'array-like', "object'", 'if', 'self.shape', 'and', 'hasattr(value,', "'shape')", 'and', 'value.shape:', 'if', 'self.shape', '!=', 'value.shape:', 'info', '+=', "'", 'of', 'shape', "%s'", '%', 'str(se...
276,162
jshilong/DDQ
openimages.py
OpenImagesDataset.get_meta_from_pipeline
get_meta_from_pipeline
Get image metas from pipeline.
[ "Get", "image", "metas", "from", "pipeline." ]
def get_meta_from_pipeline(self, results): self.temp_img_metas.extend(results['img_metas']) if dist.is_available() and self.world_size > 1: from mmdet.apis.test import collect_results_cpu self.test_img_metas = collect_results_cpu(self.temp_img_metas, len(self)) else: self.test_img_me...
['def', 'get_meta_from_pipeline(self,', 'results):', "self.temp_img_metas.extend(results['img_metas'])", 'if', 'dist.is_available()', 'and', 'self.world_size', '>', '1:', 'from', 'mmdet.apis.test', 'import', 'collect_results_cpu', 'self.test_img_metas', '=', 'collect_results_cpu(self.temp_img_metas,', 'len(self))', 'el...
515,843
AgnostiqHQ/covalent
base.py
_AbstractBaseExecutor.get_dispatch_context
get_dispatch_context
Start a context manager that will be used to access the dispatch info for the executor.
[ "Start", "a", "context", "manager", "that", "will", "be", "used", "to", "access", "the", "dispatch", "info", "for", "the", "executor." ]
def get_dispatch_context(self, dispatch_info: DispatchInfo) -> ContextManager[DispatchInfo]: return active_dispatch_info_manager.claim(dispatch_info)
['def', 'get_dispatch_context(self,', 'dispatch_info:', 'DispatchInfo)', '->', 'ContextManager[DispatchInfo]:', 'return', 'active_dispatch_info_manager.claim(dispatch_info)']
489,376
lebrice/Sequoia
setting.py
IncrementalSLSetting.make_test_cl_scenario
make_test_cl_scenario
Creates a test ClassIncremental object from continuum.
[ "Creates", "a", "test", "ClassIncremental", "object", "from", "continuum." ]
def make_test_cl_scenario(self, test_dataset: _ContinuumDataset) -> _BaseScenario: return ClassIncremental(test_dataset, nb_tasks=self.nb_tasks, increment=self.test_increment, initial_increment=self.test_initial_increment, class_order=self.test_class_order, transformations=self.transforms)
['def', 'make_test_cl_scenario(self,', 'test_dataset:', '_ContinuumDataset)', '->', '_BaseScenario:', 'return', 'ClassIncremental(test_dataset,', 'nb_tasks=self.nb_tasks,', 'increment=self.test_increment,', 'initial_increment=self.test_initial_increment,', 'class_order=self.test_class_order,', 'transformations=self.tra...
349,687
UWARG/computer-vision-python
test_geolocation.py
TestPerspectiveTransformMatrix.test_intermediate_above_origin_pointing_west
test_intermediate_above_origin_pointing_west
Positioned so that the camera is above the origin directly down (but the drone is not).
[ "Positioned", "so", "that", "the", "camera", "is", "above", "the", "origin", "directly", "down", "(but", "the", "drone", "is", "not)." ]
def test_intermediate_above_origin_pointing_west(self, intermediate_locator: geolocation.Geolocation): (result, drone_rotation_matrix) = camera_properties.create_rotation_matrix_from_orientation(-np.pi / 2, 0.0, 0.0) assert result assert drone_rotation_matrix is not None drone_position_ned = np.array([0...
['def', 'test_intermediate_above_origin_pointing_west(self,', 'intermediate_locator:', 'geolocation.Geolocation):', '(result,', 'drone_rotation_matrix)', '=', 'camera_properties.create_rotation_matrix_from_orientation(-np.pi', '/', '2,', '0.0,', '0.0)', 'assert', 'result', 'assert', 'drone_rotation_matrix', 'is', 'not'...
470,499
calico/basenji
dna_io.py
hot1_augment
hot1_augment
Transform a batch of one hot coded sequences to augment training.
[ "Transform", "a", "batch", "of", "one", "hot", "coded", "sequences", "to", "augment", "training." ]
def hot1_augment(Xb, fwdrc=True, shift=0): if Xb.ndim == 2: singleton = True Xb = np.expand_dims(Xb, axis=0) else: singleton = False if Xb.dtype == bool: nval = 0 else: nval = 0.25 if shift == 0: Xbt = Xb elif shift > 0: Xbt = np.zeros(Xb.s...
['def', 'hot1_augment(Xb,', 'fwdrc=True,', 'shift=0):', 'if', 'Xb.ndim', '==', '2:', 'singleton', '=', 'True', 'Xb', '=', 'np.expand_dims(Xb,', 'axis=0)', 'else:', 'singleton', '=', 'False', 'if', 'Xb.dtype', '==', 'bool:', 'nval', '=', '0', 'else:', 'nval', '=', '0.25', 'if', 'shift', '==', '0:', 'Xbt', '=', 'Xb', 'el...
94,560
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
lfads.py
LFADS.eval_model_parameters
eval_model_parameters
Evaluate and return all of the TF variables in the model.
[ "Evaluate", "and", "return", "all", "of", "the", "TF", "variables", "in", "the", "model." ]
def eval_model_parameters(use_nested=True, include_strs=None): all_tf_vars = tf.global_variables() session = tf.get_default_session() all_tf_vars_eval = session.run(all_tf_vars) vars_dict = {} strs = ['LFADS'] if include_strs: strs += include_strs for (i, (var, var_eval)) in enumerat...
['def', 'eval_model_parameters(use_nested=True,', 'include_strs=None):', 'all_tf_vars', '=', 'tf.global_variables()', 'session', '=', 'tf.get_default_session()', 'all_tf_vars_eval', '=', 'session.run(all_tf_vars)', 'vars_dict', '=', '{}', 'strs', '=', "['LFADS']", 'if', 'include_strs:', 'strs', '+=', 'include_strs', 'f...
49,691
metadriverse/metadrive
__init__.py
load
load
Parse the first YAML document in a stream and produce the corresponding Python object.
[ "Parse", "the", "first", "YAML", "document", "in", "a", "stream", "and", "produce", "the", "corresponding", "Python", "object." ]
def load(stream, Loader=Loader): loader = Loader(stream) try: return loader.get_single_data() finally: loader.dispose()
['def', 'load(stream,', 'Loader=Loader):', 'loader', '=', 'Loader(stream)', 'try:', 'return', 'loader.get_single_data()', 'finally:', 'loader.dispose()']
634,267
matsu0228/nlp-jp
named_commands.py
forward_char
forward_char
Move forward a character.
[ "Move", "forward", "a", "character." ]
def forward_char(event): buff = event.current_buffer buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg)
['def', 'forward_char(event):', 'buff', '=', 'event.current_buffer', 'buff.cursor_position', '+=', 'buff.document.get_cursor_right_position(count=event.arg)']
804,449
LLNL/merlin
test_study.py
test_get_task_queue_default
test_get_task_queue_default
Given a steps dictionary that sets the task queue to `test_queue` return `test_queue` as the queue name.
[ "Given", "a", "steps", "dictionary", "that", "sets", "the", "task", "queue", "to", "`test_queue`", "return", "`test_queue`", "as", "the", "queue", "name." ]
def test_get_task_queue_default(): steps = {'run': {'task_queue': 'test_queue'}} queue = Step.get_task_queue_from_dict(steps) assert queue == '[merlin]_test_queue'
['def', 'test_get_task_queue_default():', 'steps', '=', "{'run':", "{'task_queue':", "'test_queue'}}", 'queue', '=', 'Step.get_task_queue_from_dict(steps)', 'assert', 'queue', '==', "'[merlin]_test_queue'"]
632,926
Qbanxiaoxu/NaturalLanguageProcessingExperiment
tarfile.py
TarInfo.isfile
isfile
Return True if the Tarinfo object is a regular file.
[ "Return", "True", "if", "the", "Tarinfo", "object", "is", "a", "regular", "file." ]
def isfile(self): return self.isreg()
['def', 'isfile(self):', 'return', 'self.isreg()']
801,732
AranGarcia/ArtificialQuest
search.py
MapProblem.heuristic_init
heuristic_init
Initiates the initial state for a heuristic search, which only consists of establishing the manhattan distance form the start to the goal.
[ "Initiates", "the", "initial", "state", "for", "a", "heuristic", "search,", "which", "only", "consists", "of", "establishing", "the", "manhattan", "distance", "form", "the", "start", "to", "the", "goal." ]
def heuristic_init(self): self.initial = HNode(self.initial.coord, 0, dist=self.__manhattan(self.initial.coord))
['def', 'heuristic_init(self):', 'self.initial', '=', 'HNode(self.initial.coord,', '0,', 'dist=self.__manhattan(self.initial.coord))']
70,506
airaria/TextBrewer
utils.py
display_parameters
display_parameters
Display the numbers and memory usage of module parameters.
[ "Display", "the", "numbers", "and", "memory", "usage", "of", "module", "parameters." ]
def display_parameters(model, max_level=None): if isinstance(model, torch.nn.Module): state_dict = model.state_dict() elif isinstance(model, dict): state_dict = model else: raise TypeError('model should be either torch.nn.Module or a dict') hash_set = set() model_node = Layer...
['def', 'display_parameters(model,', 'max_level=None):', 'if', 'isinstance(model,', 'torch.nn.Module):', 'state_dict', '=', 'model.state_dict()', 'elif', 'isinstance(model,', 'dict):', 'state_dict', '=', 'model', 'else:', 'raise', "TypeError('model", 'should', 'be', 'either', 'torch.nn.Module', 'or', 'a', "dict')", 'ha...
925,863
google-research/scenic
visual_text_with_text_pretraining_trainer.py
train_step
train_step
Runs a single step of evaluation.
[ "Runs", "a", "single", "step", "of", "evaluation." ]
def train_step(train_state: train_utils.TrainState, visual: jnp.ndarray, text: jnp.ndarray, mask: Optional[jnp.ndarray], text_for_mlm: jnp.ndarray, segment_ids_for_mlm: jnp.ndarray, mask_for_mlm: Optional[jnp.ndarray], masked_lm_positions: jnp.ndarray, masked_lm_ids: jnp.ndarray, masked_lm_weights: jnp.ndarray, *, mode...
['def', 'train_step(train_state:', 'train_utils.TrainState,', 'visual:', 'jnp.ndarray,', 'text:', 'jnp.ndarray,', 'mask:', 'Optional[jnp.ndarray],', 'text_for_mlm:', 'jnp.ndarray,', 'segment_ids_for_mlm:', 'jnp.ndarray,', 'mask_for_mlm:', 'Optional[jnp.ndarray],', 'masked_lm_positions:', 'jnp.ndarray,', 'masked_lm_ids:...
846,961
Speedwagon13/CS-3600-Introduction-to--
ttk.py
Treeview.selection_toggle
selection_toggle
Toggle the selection state of each item in items.
[ "Toggle", "the", "selection", "state", "of", "each", "item", "in", "items." ]
def selection_toggle(self, items): self.selection('toggle', items)
['def', 'selection_toggle(self,', 'items):', "self.selection('toggle',", 'items)']
219,382
RasaHQ/rasa
pykwalify_extensions.py
require_response_keys
require_response_keys
Validates that response dicts have either the "text" key or the "custom" key.
[ "Validates", "that", "response", "dicts", "have", "either", "the", "\"text\"", "key", "or", "the", "\"custom\"", "key." ]
def require_response_keys(responses: List[Dict[Text, Any]], _: Dict, __: Text) -> Union[SchemaError, bool]: for response in responses: if not isinstance(response, dict): continue if response.get('text') is None and (not response.get('custom')): return SchemaError("Missing 'te...
['def', 'require_response_keys(responses:', 'List[Dict[Text,', 'Any]],', '_:', 'Dict,', '__:', 'Text)', '->', 'Union[SchemaError,', 'bool]:', 'for', 'response', 'in', 'responses:', 'if', 'not', 'isinstance(response,', 'dict):', 'continue', 'if', "response.get('text')", 'is', 'None', 'and', '(not', "response.get('custom...
837,819
eric-haibin-lin/nlp-notebooks
finetune_classifier.py
log_eval
log_eval
Generate and print out the log message for inference.
[ "Generate", "and", "print", "out", "the", "log", "message", "for", "inference." ]
def log_eval(batch_id, batch_num, metric, step_loss, log_interval): (metric_nm, metric_val) = metric.get() if not isinstance(metric_nm, list): (metric_nm, metric_val) = ([metric_nm], [metric_val]) eval_str = '[Batch %d/%d] loss=%.4f, metrics:' + ','.join([i + ':%.4f' for i in metric_nm]) logging...
['def', 'log_eval(batch_id,', 'batch_num,', 'metric,', 'step_loss,', 'log_interval):', '(metric_nm,', 'metric_val)', '=', 'metric.get()', 'if', 'not', 'isinstance(metric_nm,', 'list):', '(metric_nm,', 'metric_val)', '=', '([metric_nm],', '[metric_val])', 'eval_str', '=', "'[Batch", '%d/%d]', 'loss=%.4f,', "metrics:'", ...
730,862
cslu-nlp/nlup
perceptron.py
AveragedPerceptron.score
score
Gets score for a feature vector/class pair.
[ "Gets", "score", "for", "a", "feature", "vector/class", "pair." ]
def score(self, y, phi): return sum((self.weights[phi_i][y].get() for phi_i in phi))
['def', 'score(self,', 'y,', 'phi):', 'return', 'sum((self.weights[phi_i][y].get()', 'for', 'phi_i', 'in', 'phi))']
731,737
tensorflow/agents
td3_agent.py
Td3Agent.actor_loss
actor_loss
Computes the actor_loss for TD3 training.
[ "Computes", "the", "actor_loss", "for", "TD3", "training." ]
def actor_loss(self, time_steps: ts.TimeStep, weights: Optional[types.Tensor]=None, training: bool=False) -> types.Tensor: with tf.name_scope('actor_loss'): (actions, _) = self._actor_network(time_steps.observation, time_steps.step_type, training=training) (q_values, _) = self._critic_network_1((tim...
['def', 'actor_loss(self,', 'time_steps:', 'ts.TimeStep,', 'weights:', 'Optional[types.Tensor]=None,', 'training:', 'bool=False)', '->', 'types.Tensor:', 'with', "tf.name_scope('actor_loss'):", '(actions,', '_)', '=', 'self._actor_network(time_steps.observation,', 'time_steps.step_type,', 'training=training)', '(q_valu...
23,239
sunishsheth2009/ChatterBot
support.py
NullTranslations.dngettext
dngettext
Like ``ngettext()``, but look the message up in the specified domain.
[ "Like", "``ngettext()``,", "but", "look", "the", "message", "up", "in", "the", "specified", "domain." ]
def dngettext(self, domain, singular, plural, num): return self._domains.get(domain, self).ngettext(singular, plural, num)
['def', 'dngettext(self,', 'domain,', 'singular,', 'plural,', 'num):', 'return', 'self._domains.get(domain,', 'self).ngettext(singular,', 'plural,', 'num)']
478,575
AgnostiqHQ/covalent
data_manager.py
make_derived_dispatch
make_derived_dispatch
Make a re-dispatch from a previous dispatch.
[ "Make", "a", "re-dispatch", "from", "a", "previous", "dispatch." ]
def make_derived_dispatch(parent_dispatch_id: str, json_lattice: Optional[str]=None, electron_updates: Optional[Dict[str, Callable]]=None, reuse_previous_results: bool=False) -> str: if electron_updates is None: electron_updates = {} old_result_object = load.get_result_object_from_storage(parent_dispatc...
['def', 'make_derived_dispatch(parent_dispatch_id:', 'str,', 'json_lattice:', 'Optional[str]=None,', 'electron_updates:', 'Optional[Dict[str,', 'Callable]]=None,', 'reuse_previous_results:', 'bool=False)', '->', 'str:', 'if', 'electron_updates', 'is', 'None:', 'electron_updates', '=', '{}', 'old_result_object', '=', 'l...
489,598
cassianobecker/tgcn
differential_operators.py
grad_and_aux
grad_and_aux
Builds a function that returns the gradient of the first output and the (unmodified) second output of a function that returns two outputs.
[ "Builds", "a", "function", "that", "returns", "the", "gradient", "of", "the", "first", "output", "and", "the", "(unmodified)", "second", "output", "of", "a", "function", "that", "returns", "two", "outputs." ]
def grad_and_aux(fun, x): (vjp, (ans, aux)) = _make_vjp(lambda x: atuple(fun(x)), x) return (vjp((vspace(ans).ones(), vspace(aux).zeros())), aux)
['def', 'grad_and_aux(fun,', 'x):', '(vjp,', '(ans,', 'aux))', '=', '_make_vjp(lambda', 'x:', 'atuple(fun(x)),', 'x)', 'return', '(vjp((vspace(ans).ones(),', 'vspace(aux).zeros())),', 'aux)']
367,207
myothida/Supervised-Machine-Learning
common.py
classes_and_not_datetimelike
classes_and_not_datetimelike
Evaluate if the tipo is a subclass of the klasses and not a datetimelike.
[ "Evaluate", "if", "the", "tipo", "is", "a", "subclass", "of", "the", "klasses", "and", "not", "a", "datetimelike." ]
def classes_and_not_datetimelike(*klasses) -> Callable: return lambda tipo: issubclass(tipo, klasses) and (not issubclass(tipo, (np.datetime64, np.timedelta64)))
['def', 'classes_and_not_datetimelike(*klasses)', '->', 'Callable:', 'return', 'lambda', 'tipo:', 'issubclass(tipo,', 'klasses)', 'and', '(not', 'issubclass(tipo,', '(np.datetime64,', 'np.timedelta64)))']
442,712
zihuitang/medical_AI_platform
datetimetester.py
ZoneInfo.nondst_folds
nondst_folds
Find all folds with the same value of isdst on both sides of the transition.
[ "Find", "all", "folds", "with", "the", "same", "value", "of", "isdst", "on", "both", "sides", "of", "the", "transition." ]
def nondst_folds(self): for ((_, prev_ti), (t, ti)) in pairs(zip(self.ut, self.ti)): shift = ti[0] - prev_ti[0] if shift < ZERO and ti[1] == prev_ti[1]: yield (datetime.utcfromtimestamp(t), -shift, prev_ti[2], ti[2])
['def', 'nondst_folds(self):', 'for', '((_,', 'prev_ti),', '(t,', 'ti))', 'in', 'pairs(zip(self.ut,', 'self.ti)):', 'shift', '=', 'ti[0]', '-', 'prev_ti[0]', 'if', 'shift', '<', 'ZERO', 'and', 'ti[1]', '==', 'prev_ti[1]:', 'yield', '(datetime.utcfromtimestamp(t),', '-shift,', 'prev_ti[2],', 'ti[2])']
283,187
eric-haibin-lin/nlp-notebooks
dataprocessor.py
make_dataloader
make_dataloader
Create data loaders for training/validation/test.
[ "Create", "data", "loaders", "for", "training/validation/test." ]
def make_dataloader(data_train, data_val, data_test, args, use_average_length=False, num_shards=0, num_workers=8): data_train_lengths = get_data_lengths(data_train) data_val_lengths = get_data_lengths(data_val) data_test_lengths = get_data_lengths(data_test) train_batchify_fn = btf.Tuple(btf.Pad(), btf....
['def', 'make_dataloader(data_train,', 'data_val,', 'data_test,', 'args,', 'use_average_length=False,', 'num_shards=0,', 'num_workers=8):', 'data_train_lengths', '=', 'get_data_lengths(data_train)', 'data_val_lengths', '=', 'get_data_lengths(data_val)', 'data_test_lengths', '=', 'get_data_lengths(data_test)', 'train_ba...
730,834
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
preprocessing.py
augment_image_scale
augment_image_scale
Training time scale augmentation.
[ "Training", "time", "scale", "augmentation." ]
def augment_image_scale(image, min_scale, max_scale, p_scale_up): assert max_scale >= 1.0 assert min_scale <= 1.0 if min_scale == max_scale == 1.0: tf.logging.info('Min and max scale are 1.0, don`t augment.') return crop_center(image) elif max_scale == 1.0 and min_scale < 1.0: tf...
['def', 'augment_image_scale(image,', 'min_scale,', 'max_scale,', 'p_scale_up):', 'assert', 'max_scale', '>=', '1.0', 'assert', 'min_scale', '<=', '1.0', 'if', 'min_scale', '==', 'max_scale', '==', '1.0:', "tf.logging.info('Min", 'and', 'max', 'scale', 'are', '1.0,', 'don`t', "augment.')", 'return', 'crop_center(image)...
112,319
openai/spinningup
core.py
categorical_kl
categorical_kl
tf symbol for mean KL divergence between two batches of categorical probability distributions, where the distributions are input as log probs.
[ "tf", "symbol", "for", "mean", "KL", "divergence", "between", "two", "batches", "of", "categorical", "probability", "distributions,", "where", "the", "distributions", "are", "input", "as", "log", "probs." ]
def categorical_kl(logp0, logp1): all_kls = tf.reduce_sum(tf.exp(logp1) * (logp1 - logp0), axis=1) return tf.reduce_mean(all_kls)
['def', 'categorical_kl(logp0,', 'logp1):', 'all_kls', '=', 'tf.reduce_sum(tf.exp(logp1)', '*', '(logp1', '-', 'logp0),', 'axis=1)', 'return', 'tf.reduce_mean(all_kls)']
371,734
psobot/machine-learning-for-drummers
audio_utils.py
average_eq_bands
average_eq_bands
Returns the average power in each EQ band, where the spectrum is split into `num_bands` equal bands.
[ "Returns", "the", "average", "power", "in", "each", "EQ", "band,", "where", "the", "spectrum", "is", "split", "into", "`num_bands`", "equal", "bands." ]
def average_eq_bands(y, num_bands=15): frequency_spectrogram_data = librosa.amplitude_to_db(librosa.magphase(librosa.stft(y, num_bands + 1))[0], ref=numpy.max) return list([float(x) for x in numpy.mean(frequency_spectrogram_data, axis=1)])
['def', 'average_eq_bands(y,', 'num_bands=15):', 'frequency_spectrogram_data', '=', 'librosa.amplitude_to_db(librosa.magphase(librosa.stft(y,', 'num_bands', '+', '1))[0],', 'ref=numpy.max)', 'return', 'list([float(x)', 'for', 'x', 'in', 'numpy.mean(frequency_spectrogram_data,', 'axis=1)])']
620,764
43Carrig/recurrent_neural_networks_practice
common.py
get_flattened_names
get_flattened_names
Get a flattened list of the names in run() call feeds or fetches.
[ "Get", "a", "flattened", "list", "of", "the", "names", "in", "run()", "call", "feeds", "or", "fetches." ]
def get_flattened_names(feeds_or_fetches): lines = [] if isinstance(feeds_or_fetches, (list, tuple)): for item in feeds_or_fetches: lines.extend(get_flattened_names(item)) elif isinstance(feeds_or_fetches, dict): for key in feeds_or_fetches: lines.extend(get_flattened...
['def', 'get_flattened_names(feeds_or_fetches):', 'lines', '=', '[]', 'if', 'isinstance(feeds_or_fetches,', '(list,', 'tuple)):', 'for', 'item', 'in', 'feeds_or_fetches:', 'lines.extend(get_flattened_names(item))', 'elif', 'isinstance(feeds_or_fetches,', 'dict):', 'for', 'key', 'in', 'feeds_or_fetches:', 'lines.extend(...
335,914
rlworkgroup/garage
test_trpo.py
TestTRPO.teardown_method
teardown_method
Teardown method which is called after every test.
[ "Teardown", "method", "which", "is", "called", "after", "every", "test." ]
def teardown_method(self): self.env.close()
['def', 'teardown_method(self):', 'self.env.close()']
201,012
calico/basenji
basenji_sat_plot2.py
expand_scores_align
expand_scores_align
Expand two scores arrays according to a sequence alignment with NaNs in gaps.
[ "Expand", "two", "scores", "arrays", "according", "to", "a", "sequence", "alignment", "with", "NaNs", "in", "gaps." ]
def expand_scores_align(scores1, scores2, seq1_1hot, seq2_1hot, seq1_align, seq2_align): scores1_ref = scores1[seq1_1hot] scores2_ref = scores2[seq2_1hot] align_len = len(seq1_align) scores1_align = np.zeros((align_len, 4, scores1.shape[-1])) scores2_align = np.zeros((align_len, 4, scores2.shape[-1]...
['def', 'expand_scores_align(scores1,', 'scores2,', 'seq1_1hot,', 'seq2_1hot,', 'seq1_align,', 'seq2_align):', 'scores1_ref', '=', 'scores1[seq1_1hot]', 'scores2_ref', '=', 'scores2[seq2_1hot]', 'align_len', '=', 'len(seq1_align)', 'scores1_align', '=', 'np.zeros((align_len,', '4,', 'scores1.shape[-1]))', 'scores2_alig...
94,807
arshpreetsingh/quantopian-machinelearning
test_soup.py
TestEntitySubstitution.test_quotes_not_html_substituted
test_quotes_not_html_substituted
There's no need to do this except inside attribute values.
[ "There's", "no", "need", "to", "do", "this", "except", "inside", "attribute", "values." ]
def test_quotes_not_html_substituted(self): text = 'Bob\'s "bar"' self.assertEqual(self.sub.substitute_html(text), text)
['def', 'test_quotes_not_html_substituted(self):', 'text', '=', "'Bob\\'s", '"bar"\'', 'self.assertEqual(self.sub.substitute_html(text),', 'text)']
816,560
aralab-unr/ReinforcementLearningWithGA
rollout.py
RolloutWorker.reset_rollout
reset_rollout
Resets the `i`-th rollout environment, re-samples a new goal, and updates the `initial_o` and `g` arrays accordingly.
[ "Resets", "the", "`i`-th", "rollout", "environment,", "re-samples", "a", "new", "goal,", "and", "updates", "the", "`initial_o`", "and", "`g`", "arrays", "accordingly." ]
def reset_rollout(self, i): obs = self.envs[i].reset() self.initial_o[i] = obs['observation'] self.initial_ag[i] = obs['achieved_goal'] self.g[i] = obs['desired_goal']
['def', 'reset_rollout(self,', 'i):', 'obs', '=', 'self.envs[i].reset()', 'self.initial_o[i]', '=', "obs['observation']", 'self.initial_ag[i]', '=', "obs['achieved_goal']", 'self.g[i]', '=', "obs['desired_goal']"]
833,915
matsu0228/nlp-jp
bulk.py
_Bulk.add_insert
add_insert
Add an insert document to the list of ops.
[ "Add", "an", "insert", "document", "to", "the", "list", "of", "ops." ]
def add_insert(self, document): validate_is_document_type('document', document) if not (isinstance(document, RawBSONDocument) or '_id' in document): document['_id'] = ObjectId() self.ops.append((_INSERT, document))
['def', 'add_insert(self,', 'document):', "validate_is_document_type('document',", 'document)', 'if', 'not', '(isinstance(document,', 'RawBSONDocument)', 'or', "'_id'", 'in', 'document):', "document['_id']", '=', 'ObjectId()', 'self.ops.append((_INSERT,', 'document))']
804,718
Ruturaj123/Flowchart-Detection
resource_variable_ops.py
ResourceVariable.value
value
A cached operation which reads the value of this variable.
[ "A", "cached", "operation", "which", "reads", "the", "value", "of", "this", "variable." ]
def value(self): if self._cached_value is not None: return self._cached_value with ops.colocate_with(None, ignore_existing=True): with ops.device(self._handle.device): return gen_resource_variable_ops.read_variable_op(self._handle, dtype=self._dtype)
['def', 'value(self):', 'if', 'self._cached_value', 'is', 'not', 'None:', 'return', 'self._cached_value', 'with', 'ops.colocate_with(None,', 'ignore_existing=True):', 'with', 'ops.device(self._handle.device):', 'return', 'gen_resource_variable_ops.read_variable_op(self._handle,', 'dtype=self._dtype)']
606,077
microsoft/nni
_expression.py
recursive_simplification
recursive_simplification
Simplify all expressions in obj recursively.
[ "Simplify", "all", "expressions", "in", "obj", "recursively." ]
def recursive_simplification(obj: Any) -> Any: from .shape import MutableShape if isinstance(obj, MutableExpression): return expression_simplification(obj) elif isinstance(obj, MutableShape): return MutableShape(*[recursive_simplification(v) for v in obj]) elif isinstance(obj, dict): ...
['def', 'recursive_simplification(obj:', 'Any)', '->', 'Any:', 'from', '.shape', 'import', 'MutableShape', 'if', 'isinstance(obj,', 'MutableExpression):', 'return', 'expression_simplification(obj)', 'elif', 'isinstance(obj,', 'MutableShape):', 'return', 'MutableShape(*[recursive_simplification(v)', 'for', 'v', 'in', 'o...
728,902
asyml/texar-pytorch
utils.py
dict_fetch
dict_fetch
Fetches a sub-dictionary of :attr:`src_dict` with the keys in :attr:`tgt_dict_or_keys`.
[ "Fetches", "a", "sub-dictionary", "of", ":attr:`src_dict`", "with", "the", "keys", "in", ":attr:`tgt_dict_or_keys`." ]
def dict_fetch(src_dict: Optional[ParamDict], tgt_dict_or_keys: Union[ParamDict, List[str]]) -> Optional[AnyDict]: if src_dict is None: return src_dict if isinstance(tgt_dict_or_keys, HParams): tgt_dict_or_keys = tgt_dict_or_keys.todict() if isinstance(tgt_dict_or_keys, MutableMapping): ...
['def', 'dict_fetch(src_dict:', 'Optional[ParamDict],', 'tgt_dict_or_keys:', 'Union[ParamDict,', 'List[str]])', '->', 'Optional[AnyDict]:', 'if', 'src_dict', 'is', 'None:', 'return', 'src_dict', 'if', 'isinstance(tgt_dict_or_keys,', 'HParams):', 'tgt_dict_or_keys', '=', 'tgt_dict_or_keys.todict()', 'if', 'isinstance(tg...
925,341
replit-archive/empythoned
AutoComplete.py
AutoComplete.try_open_completions_event
try_open_completions_event
Happens when it would be nice to open a completion list, but not really necessary, for example after an dot, so function calls won't be made.
[ "Happens", "when", "it", "would", "be", "nice", "to", "open", "a", "completion", "list,", "but", "not", "really", "necessary,", "for", "example", "after", "an", "dot,", "so", "function", "calls", "won't", "be", "made." ]
def try_open_completions_event(self, event): lastchar = self.text.get('insert-1c') if lastchar == '.': self._open_completions_later(False, False, False, COMPLETE_ATTRIBUTES) elif lastchar in SEPS: self._open_completions_later(False, False, False, COMPLETE_FILES)
['def', 'try_open_completions_event(self,', 'event):', 'lastchar', '=', "self.text.get('insert-1c')", 'if', 'lastchar', '==', "'.':", 'self._open_completions_later(False,', 'False,', 'False,', 'COMPLETE_ATTRIBUTES)', 'elif', 'lastchar', 'in', 'SEPS:', 'self._open_completions_later(False,', 'False,', 'False,', 'COMPLETE...
176,680
TonyLianLong/VAI-ReinforcementLearning
cartpole.py
balance_sparse
balance_sparse
Returns the sparse reward variant of the Cartpole Balance task.
[ "Returns", "the", "sparse", "reward", "variant", "of", "the", "Cartpole", "Balance", "task." ]
def balance_sparse(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None, setting_kwargs=None): physics = Physics.from_xml_string(*common.settings.get_model_and_assets_from_setting_kwargs('cartpole.xml', setting_kwargs)) task = Balance(swing_up=False, sparse=True, random=random) environment_k...
['def', 'balance_sparse(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None,', 'setting_kwargs=None):', 'physics', '=', "Physics.from_xml_string(*common.settings.get_model_and_assets_from_setting_kwargs('cartpole.xml',", 'setting_kwargs))', 'task', '=', 'Balance(swing_up=False,', 'sparse=True,', ...
440,821
hamza-murad/AALU
natural_language_understanding_v1.py
EmotionOptions.from_dict
from_dict
Initialize a EmotionOptions object from a json dictionary.
[ "Initialize", "a", "EmotionOptions", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'EmotionOptions': args = {} valid_keys = ['document', 'targets'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class EmotionOptions: ' + ', '.join(bad_keys)) if 'document' in _dict...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'EmotionOptions':", 'args', '=', '{}', 'valid_keys', '=', "['document',", "'targets']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'Emoti...
5,921
nicknochnack/RealTimeSignLanguageTFJS
coco_evaluator.py
COCOEvaluator.update_state
update_state
Update and aggregate detection results and groundtruth data.
[ "Update", "and", "aggregate", "detection", "results", "and", "groundtruth", "data." ]
def update_state(self, groundtruths, predictions): (groundtruths, predictions) = self._convert_to_numpy(groundtruths, predictions) for k in self._required_prediction_fields: if k not in predictions: raise ValueError('Missing the required key `{}` in predictions!'.format(k)) if self._need...
['def', 'update_state(self,', 'groundtruths,', 'predictions):', '(groundtruths,', 'predictions)', '=', 'self._convert_to_numpy(groundtruths,', 'predictions)', 'for', 'k', 'in', 'self._required_prediction_fields:', 'if', 'k', 'not', 'in', 'predictions:', 'raise', "ValueError('Missing", 'the', 'required', 'key', '`{}`', ...
850,761
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
_pydecimal.py
Decimal.is_signed
is_signed
Return True if self is negative; otherwise return False.
[ "Return", "True", "if", "self", "is", "negative;", "otherwise", "return", "False." ]
def is_signed(self): return self._sign == 1
['def', 'is_signed(self):', 'return', 'self._sign', '==', '1']
429,987
aws/sagemaker-python-sdk
serialization.py
serialize_func_to_s3
serialize_func_to_s3
Serializes function and uploads it to S3.
[ "Serializes", "function", "and", "uploads", "it", "to", "S3." ]
def serialize_func_to_s3(func: Callable, sagemaker_session: Session, s3_uri: str, hmac_key: str, s3_kms_key: str=None): bytes_to_upload = CloudpickleSerializer.serialize(func) _upload_bytes_to_s3(bytes_to_upload, os.path.join(s3_uri, 'payload.pkl'), s3_kms_key, sagemaker_session) sha256_hash = _compute_hash...
['def', 'serialize_func_to_s3(func:', 'Callable,', 'sagemaker_session:', 'Session,', 's3_uri:', 'str,', 'hmac_key:', 'str,', 's3_kms_key:', 'str=None):', 'bytes_to_upload', '=', 'CloudpickleSerializer.serialize(func)', '_upload_bytes_to_s3(bytes_to_upload,', 'os.path.join(s3_uri,', "'payload.pkl'),", 's3_kms_key,', 'sa...
830,517
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
utils.py
get_batches
get_batches
Return batches of input and target :param int_text: Text with the words replaced by their ids :param batch_size: The size of batch :param seq_length: The length of sequence :return: A list where each item is a tuple of (batch of input, batch of target).
[ "Return", "batches", "of", "input", "and", "target", ":param", "int_text:", "Text", "with", "the", "words", "replaced", "by", "their", "ids", ":param", "batch_size:", "The", "size", "of", "batch", ":param", "seq_length:", "The", "length", "of", "sequence", ":r...
def get_batches(int_text, batch_size, seq_length): n_batches = int(len(int_text) / (batch_size * seq_length)) xdata = np.array(int_text[:n_batches * batch_size * seq_length]) ydata = np.array(int_text[1:n_batches * batch_size * seq_length + 1]) x_batches = np.split(xdata.reshape(batch_size, -1), n_batch...
['def', 'get_batches(int_text,', 'batch_size,', 'seq_length):', 'n_batches', '=', 'int(len(int_text)', '/', '(batch_size', '*', 'seq_length))', 'xdata', '=', 'np.array(int_text[:n_batches', '*', 'batch_size', '*', 'seq_length])', 'ydata', '=', 'np.array(int_text[1:n_batches', '*', 'batch_size', '*', 'seq_length', '+', ...
9,340
intel/neural-compressor
task_db.py
TaskDB.get_task_by_id
get_task_by_id
Get the task object by task id.
[ "Get", "the", "task", "object", "by", "task", "id." ]
def get_task_by_id(self, task_id): self.cursor.execute('select * from task where id=?', (task_id,)) attr_tuple = self.cursor.fetchone() return Task(*attr_tuple)
['def', 'get_task_by_id(self,', 'task_id):', "self.cursor.execute('select", '*', 'from', 'task', 'where', "id=?',", '(task_id,))', 'attr_tuple', '=', 'self.cursor.fetchone()', 'return', 'Task(*attr_tuple)']
721,800
instadeepai/jumanji
utils_test.py
test_get_path
test_get_path
Tests that get trace only returns traces.
[ "Tests", "that", "get", "trace", "only", "returns", "traces." ]
def test_get_path() -> None: assert get_path(0) == 1 assert get_path(1) == 4 assert get_path(5) == 16
['def', 'test_get_path()', '->', 'None:', 'assert', 'get_path(0)', '==', '1', 'assert', 'get_path(1)', '==', '4', 'assert', 'get_path(5)', '==', '16']
594,334
albertonietos/artificial-intelligence
test_utils.py
TestAssertNoGcCycles.test_fails
test_fails
Test that in cases where the garbage cannot be collected, we raise an error, instead of hanging forever trying to clear it.
[ "Test", "that", "in", "cases", "where", "the", "garbage", "cannot", "be", "collected,", "we", "raise", "an", "error,", "instead", "of", "hanging", "forever", "trying", "to", "clear", "it." ]
def test_fails(self): class ReferenceCycleInDel(object): make_cycle = True def __init__(self): self.cycle = self def __del__(self): self.cycle = None if ReferenceCycleInDel.make_cycle: ReferenceCycleInDel() try: w = weakref.r...
['def', 'test_fails(self):', 'class', 'ReferenceCycleInDel(object):', 'make_cycle', '=', 'True', 'def', '__init__(self):', 'self.cycle', '=', 'self', 'def', '__del__(self):', 'self.cycle', '=', 'None', 'if', 'ReferenceCycleInDel.make_cycle:', 'ReferenceCycleInDel()', 'try:', 'w', '=', 'weakref.ref(ReferenceCycleInDel()...
173,149
augmentedstartups/AS-One
transforms.py
build_transforms
build_transforms
Builds train and test transform functions.
[ "Builds", "train", "and", "test", "transform", "functions." ]
def build_transforms(height, width, transforms='random_flip', norm_mean=[0.485, 0.456, 0.406], norm_std=[0.229, 0.224, 0.225], **kwargs): if transforms is None: transforms = [] if isinstance(transforms, str): transforms = [transforms] if not isinstance(transforms, list): raise ValueE...
['def', 'build_transforms(height,', 'width,', "transforms='random_flip',", 'norm_mean=[0.485,', '0.456,', '0.406],', 'norm_std=[0.229,', '0.224,', '0.225],', '**kwargs):', 'if', 'transforms', 'is', 'None:', 'transforms', '=', '[]', 'if', 'isinstance(transforms,', 'str):', 'transforms', '=', '[transforms]', 'if', 'not',...
402,411
43Carrig/recurrent_neural_networks_practice
op_hint.py
OpHint.add_output
add_output
Add a wrapped output argument to the hint.
[ "Add", "a", "wrapped", "output", "argument", "to", "the", "hint." ]
def add_output(self, *args, **kwargs): return self._outputs.add(*args, **kwargs)
['def', 'add_output(self,', '*args,', '**kwargs):', 'return', 'self._outputs.add(*args,', '**kwargs)']
313,797
enuguru/artificial_intelligence_and_machine_
reading.py
IndexReader.most_distinctive_terms
most_distinctive_terms
Returns the top 'number' terms with the highest `tf*idf` scores as a list of (score, text) tuples.
[ "Returns", "the", "top", "'number'", "terms", "with", "the", "highest", "`tf*idf`", "scores", "as", "a", "list", "of", "(score,", "text)", "tuples." ]
def most_distinctive_terms(self, fieldname, number=5, prefix=''): N = float(self.doc_count()) gen = ((terminfo.weight() * log(N / terminfo.doc_frequency()), text) for (text, terminfo) in self.iter_prefix(fieldname, prefix)) return nlargest(number, gen)
['def', 'most_distinctive_terms(self,', 'fieldname,', 'number=5,', "prefix=''):", 'N', '=', 'float(self.doc_count())', 'gen', '=', '((terminfo.weight()', '*', 'log(N', '/', 'terminfo.doc_frequency()),', 'text)', 'for', '(text,', 'terminfo)', 'in', 'self.iter_prefix(fieldname,', 'prefix))', 'return', 'nlargest(number,',...
133,065
arshpreetsingh/quantopian-machinelearning
inputhook.py
InputHookContext.fileno
fileno
File descriptor that will become ready when the event loop needs to go on.
[ "File", "descriptor", "that", "will", "become", "ready", "when", "the", "event", "loop", "needs", "to", "go", "on." ]
def fileno(self): return self._r
['def', 'fileno(self):', 'return', 'self._r']
892,205
microsoft/nlp-recipes
ner_utils.py
preprocess_conll
preprocess_conll
Converts data in CoNLL format to word and label lists.
[ "Converts", "data", "in", "CoNLL", "format", "to", "word", "and", "label", "lists." ]
def preprocess_conll(text, sep='\t'): text_list = text.split('\n\n') if text_list[-1] in (' ', ''): text_list = text_list[:-1] max_seq_len = 0 sentence_list = [] labels_list = [] for s in text_list: s_split = s.split('\n') s_split_split = [t.split(sep) for t in s_split] ...
['def', 'preprocess_conll(text,', "sep='\\t'):", 'text_list', '=', "text.split('\\n\\n')", 'if', 'text_list[-1]', 'in', "('", "',", "''):", 'text_list', '=', 'text_list[:-1]', 'max_seq_len', '=', '0', 'sentence_list', '=', '[]', 'labels_list', '=', '[]', 'for', 's', 'in', 'text_list:', 's_split', '=', "s.split('\\n')",...
731,190
deepmind/ai-safety-gridworlds
tomato_watering.py
WateredTomatoDrape.observed_watered_tomatoes
observed_watered_tomatoes
The number of tomatoes that are observed as watered.
[ "The", "number", "of", "tomatoes", "that", "are", "observed", "as", "watered." ]
def observed_watered_tomatoes(self): return np.sum(self.curtain)
['def', 'observed_watered_tomatoes(self):', 'return', 'np.sum(self.curtain)']
412,123
robustness-gym/robustness-gym
schema.py
Schema.columns
columns
List of columns that participate in the schema.
[ "List", "of", "columns", "that", "participate", "in", "the", "schema." ]
def columns(self): return list(self.features.keys())
['def', 'columns(self):', 'return', 'list(self.features.keys())']
826,342
sentinel-hub/eo-learn
common.py
is_discrete_type
is_discrete_type
Checks if a given `numpy` type is a discrete numerical type.
[ "Checks", "if", "a", "given", "`numpy`", "type", "is", "a", "discrete", "numerical", "type." ]
def is_discrete_type(number_type: np.dtype | type) -> bool: return np.issubdtype(number_type, np.integer) or np.issubdtype(number_type, bool)
['def', 'is_discrete_type(number_type:', 'np.dtype', '|', 'type)', '->', 'bool:', 'return', 'np.issubdtype(number_type,', 'np.integer)', 'or', 'np.issubdtype(number_type,', 'bool)']
562,597
TonyLianLong/UnsupervisedSelectiveLabeling
nn_utils.py
KMeans
KMeans
Implements Lloyd's algorithm for the Euclidean metric.
[ "Implements", "Lloyd's", "algorithm", "for", "the", "Euclidean", "metric." ]
def KMeans(x, seed, K=10, Niter=10, init_inds=None, verbose=True, force_no_lazy_tensor=False): start = time.time() (N, D) = x.shape if seed is not None: torch.manual_seed(seed) torch.cuda.manual_seed(seed) if init_inds is None: print('Use no init indices') r = torch.randp...
['def', 'KMeans(x,', 'seed,', 'K=10,', 'Niter=10,', 'init_inds=None,', 'verbose=True,', 'force_no_lazy_tensor=False):', 'start', '=', 'time.time()', '(N,', 'D)', '=', 'x.shape', 'if', 'seed', 'is', 'not', 'None:', 'torch.manual_seed(seed)', 'torch.cuda.manual_seed(seed)', 'if', 'init_inds', 'is', 'None:', "print('Use",...
353,948
genforce/lia
util.py
format_time
format_time
Convert the seconds to human readable string with days, hours, minutes and seconds.
[ "Convert", "the", "seconds", "to", "human", "readable", "string", "with", "days,", "hours,", "minutes", "and", "seconds." ]
def format_time(seconds: Union[int, float]) -> str: s = int(np.rint(seconds)) if s < 60: return '{0}s'.format(s) elif s < 60 * 60: return '{0}m {1:02}s'.format(s // 60, s % 60) elif s < 24 * 60 * 60: return '{0}h {1:02}m {2:02}s'.format(s // (60 * 60), s // 60 % 60, s % 60) e...
['def', 'format_time(seconds:', 'Union[int,', 'float])', '->', 'str:', 's', '=', 'int(np.rint(seconds))', 'if', 's', '<', '60:', 'return', "'{0}s'.format(s)", 'elif', 's', '<', '60', '*', '60:', 'return', "'{0}m", "{1:02}s'.format(s", '//', '60,', 's', '%', '60)', 'elif', 's', '<', '24', '*', '60', '*', '60:', 'return'...
601,074