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
google-research/batch-ppo
in_graph_batch_env.py
InGraphBatchEnv.action
action
Access the variable holding the last received action.
[ "Access", "the", "variable", "holding", "the", "last", "received", "action." ]
def action(self): return self._action
['def', 'action(self):', 'return', 'self._action']
94,962
nicknochnack/RealTimeSignLanguageTFJS
autoaugment_utils.py
translate_bbox
translate_bbox
Equivalent of PIL Translate in X/Y dimension that shifts image and bbox.
[ "Equivalent", "of", "PIL", "Translate", "in", "X/Y", "dimension", "that", "shifts", "image", "and", "bbox." ]
def translate_bbox(image, bboxes, pixels, replace, shift_horizontal): if shift_horizontal: image = translate_x(image, pixels, replace) else: image = translate_y(image, pixels, replace) image_height = tf.shape(image)[0] image_width = tf.shape(image)[1] wrapped_shift_bbox = lambda bbox...
['def', 'translate_bbox(image,', 'bboxes,', 'pixels,', 'replace,', 'shift_horizontal):', 'if', 'shift_horizontal:', 'image', '=', 'translate_x(image,', 'pixels,', 'replace)', 'else:', 'image', '=', 'translate_y(image,', 'pixels,', 'replace)', 'image_height', '=', 'tf.shape(image)[0]', 'image_width', '=', 'tf.shape(imag...
830,816
FilipMiscevic/random_walk
rw.py
irt_self_longterm_avg
irt_self_longterm_avg
Determine IRTs for each patch entry positions using fluid categories normalized to the long-term average IRT accross all trials in the experiment.
[ "Determine", "IRTs", "for", "each", "patch", "entry", "positions", "using", "fluid", "categories", "normalized", "to", "the", "long-term", "average", "IRT", "accross", "all", "trials", "in", "the", "experiment." ]
def irt_self_longterm_avg(b, cat, multi=True): orders = [] n = [] p = [] irts = [] if multi == True: size = len(cat) for (q, w) in enumerate(cat): neg_order = [] pos_order = [] for (j, kk) in enumerate(w): if kk >= max(w): ...
['def', 'irt_self_longterm_avg(b,', 'cat,', 'multi=True):', 'orders', '=', '[]', 'n', '=', '[]', 'p', '=', '[]', 'irts', '=', '[]', 'if', 'multi', '==', 'True:', 'size', '=', 'len(cat)', 'for', '(q,', 'w)', 'in', 'enumerate(cat):', 'neg_order', '=', '[]', 'pos_order', '=', '[]', 'for', '(j,', 'kk)', 'in', 'enumerate(w)...
304,284
nkthiebaut/zeugma
test_texttransformers.py
test_item_selector
test_item_selector
Test selecting items in a mappable from previous pipeline step.
[ "Test", "selecting", "items", "in", "a", "mappable", "from", "previous", "pipeline", "step." ]
def test_item_selector(): test_case = {'a': 1, 'b': 2} item_selector = ItemSelector('a') out = item_selector.fit_transform(test_case) assert out == test_case['a']
['def', 'test_item_selector():', 'test_case', '=', "{'a':", '1,', "'b':", '2}', 'item_selector', '=', "ItemSelector('a')", 'out', '=', 'item_selector.fit_transform(test_case)', 'assert', 'out', '==', "test_case['a']"]
971,818
facebookresearch/CompilerGym
gcc_env.py
GccEnv.obj
obj
Get the object code.
[ "Get", "the", "object", "code." ]
def obj(self) -> bytes: return self.observation['obj']
['def', 'obj(self)', '->', 'bytes:', 'return', "self.observation['obj']"]
125,463
amazon-science/gluonmm
image_classification_config.py
get_cfg_defaults
get_cfg_defaults
Get a yacs CfgNode object with default values for your project.
[ "Get", "a", "yacs", "CfgNode", "object", "with", "default", "values", "for", "your", "project." ]
def get_cfg_defaults(): return _C.clone()
['def', 'get_cfg_defaults():', 'return', '_C.clone()']
578,291
YuYaoYang2333/SyntaLinker
misc.py
set_random_seed
set_random_seed
Sets the random seed.
[ "Sets", "the", "random", "seed." ]
def set_random_seed(seed, is_cuda): if seed > 0: torch.manual_seed(seed) random.seed(seed) torch.backends.cudnn.deterministic = True if is_cuda and seed > 0: torch.cuda.manual_seed(seed)
['def', 'set_random_seed(seed,', 'is_cuda):', 'if', 'seed', '>', '0:', 'torch.manual_seed(seed)', 'random.seed(seed)', 'torch.backends.cudnn.deterministic', '=', 'True', 'if', 'is_cuda', 'and', 'seed', '>', '0:', 'torch.cuda.manual_seed(seed)']
905,975
enlite-ai/maze
test_export_gif_wrapper.py
assert_gif_export
assert_gif_export
Checks if gif got exported correctly.
[ "Checks", "if", "gif", "got", "exported", "correctly." ]
def assert_gif_export(env: MazeEnv) -> None: env.reset() for _ in range(3): env.step(env.action_space.sample()) env.close() gif_files = glob.glob('*.gif') assert len(gif_files) == 1
['def', 'assert_gif_export(env:', 'MazeEnv)', '->', 'None:', 'env.reset()', 'for', '_', 'in', 'range(3):', 'env.step(env.action_space.sample())', 'env.close()', 'gif_files', '=', "glob.glob('*.gif')", 'assert', 'len(gif_files)', '==', '1']
647,176
rudranil723/mini-main
runner.py
partition_suite_by_case
partition_suite_by_case
Partition a test suite by test case, preserving the order of tests.
[ "Partition", "a", "test", "suite", "by", "test", "case,", "preserving", "the", "order", "of", "tests." ]
def partition_suite_by_case(suite): groups = [] suite_class = type(suite) for (test_type, test_group) in itertools.groupby(suite, type): if issubclass(test_type, unittest.TestCase): groups.append(suite_class(test_group)) else: for item in test_group: g...
['def', 'partition_suite_by_case(suite):', 'groups', '=', '[]', 'suite_class', '=', 'type(suite)', 'for', '(test_type,', 'test_group)', 'in', 'itertools.groupby(suite,', 'type):', 'if', 'issubclass(test_type,', 'unittest.TestCase):', 'groups.append(suite_class(test_group))', 'else:', 'for', 'item', 'in', 'test_group:',...
316,553
rlgraph/rlgraph
openai_gym.py
OpenAIGymEnv.translate_space
translate_space
Translates openAI spaces into RLGraph Space classes.
[ "Translates", "openAI", "spaces", "into", "RLGraph", "Space", "classes." ]
def translate_space(space, dtype=None, force_float32=False): if isinstance(space, gym.spaces.Discrete): return IntBox(space.n) elif isinstance(space, gym.spaces.MultiBinary): return BoolBox(shape=(space.n,)) elif isinstance(space, gym.spaces.MultiDiscrete): return IntBox(low=np.zeros...
['def', 'translate_space(space,', 'dtype=None,', 'force_float32=False):', 'if', 'isinstance(space,', 'gym.spaces.Discrete):', 'return', 'IntBox(space.n)', 'elif', 'isinstance(space,', 'gym.spaces.MultiBinary):', 'return', 'BoolBox(shape=(space.n,))', 'elif', 'isinstance(space,', 'gym.spaces.MultiDiscrete):', 'return', ...
862,542
rlworkgroup/garage
_environment.py
EnvStep.last
last
bool: Whether this `TimeStep` is the last of a sequence.
[ "bool:", "Whether", "this", "`TimeStep`", "is", "the", "last", "of", "a", "sequence." ]
def last(self): return self.step_type is StepType.TERMINAL or self.step_type is StepType.TIMEOUT
['def', 'last(self):', 'return', 'self.step_type', 'is', 'StepType.TERMINAL', 'or', 'self.step_type', 'is', 'StepType.TIMEOUT']
200,163
Deeplite/deeplite-torch-zoo
utils.py
verify_image_label
verify_image_label
Verify one image-label pair.
[ "Verify", "one", "image-label", "pair." ]
def verify_image_label(args): (im_file, lb_file, prefix, keypoint, num_cls, nkpt, ndim) = args (nm, nf, ne, nc, msg, segments, keypoints) = (0, 0, 0, 0, '', [], None) try: im = Image.open(im_file) im.verify() shape = exif_size(im) shape = (shape[1], shape[0]) assert (...
['def', 'verify_image_label(args):', '(im_file,', 'lb_file,', 'prefix,', 'keypoint,', 'num_cls,', 'nkpt,', 'ndim)', '=', 'args', '(nm,', 'nf,', 'ne,', 'nc,', 'msg,', 'segments,', 'keypoints)', '=', '(0,', '0,', '0,', '0,', "'',", '[],', 'None)', 'try:', 'im', '=', 'Image.open(im_file)', 'im.verify()', 'shape', '=', 'ex...
538,843
Speech-Lab-IITM/CCC-wav2vec-2.0
online_backtranslation.py
OnlineBackTranslationTask.load_train_dataset
load_train_dataset
The training dataset is made of backtranslation dataset and denoising dataset.
[ "The", "training", "dataset", "is", "made", "of", "backtranslation", "dataset", "and", "denoising", "dataset." ]
def load_train_dataset(self, data_path: str) -> FairseqDataset: data = [] for lang in self.mono_langs: train_path = os.path.join(data_path, lang, 'train') data.append((f'{lang}-BT', self.load_bt_dataset(train_path, lang))) data.append((f'{lang}-DENOISE', self.load_denoise_dataset(train_p...
['def', 'load_train_dataset(self,', 'data_path:', 'str)', '->', 'FairseqDataset:', 'data', '=', '[]', 'for', 'lang', 'in', 'self.mono_langs:', 'train_path', '=', 'os.path.join(data_path,', 'lang,', "'train')", "data.append((f'{lang}-BT',", 'self.load_bt_dataset(train_path,', 'lang)))', "data.append((f'{lang}-DENOISE',"...
104,150
openvinotoolkit/training_extensions
f_measure.py
FMeasure.f_measure_per_confidence
f_measure_per_confidence
Returns the curve for f-measure per confidence as CurveMetric if exists.
[ "Returns", "the", "curve", "for", "f-measure", "per", "confidence", "as", "CurveMetric", "if", "exists." ]
def f_measure_per_confidence(self) -> Optional[CurveMetric]: return self._f_measure_per_confidence
['def', 'f_measure_per_confidence(self)', '->', 'Optional[CurveMetric]:', 'return', 'self._f_measure_per_confidence']
918,762
lektor/lektor-archive
dash.py
generic_endpoint
generic_endpoint
This function is invoked by all dash endpoints.
[ "This", "function", "is", "invoked", "by", "all", "dash", "endpoints." ]
def generic_endpoint(**kwargs): return render_template('dash.html')
['def', 'generic_endpoint(**kwargs):', 'return', "render_template('dash.html')"]
216,516
open-mmlab/mmrotate
gmm.py
GaussianMixture.check_size
check_size
Make sure that the shape of x is (T, n, 1, d).
[ "Make", "sure", "that", "the", "shape", "of", "x", "is", "(T,", "n,", "1,", "d)." ]
def check_size(self, x): if len(x.size()) == 3: x = x.unsqueeze(2) return x
['def', 'check_size(self,', 'x):', 'if', 'len(x.size())', '==', '3:', 'x', '=', 'x.unsqueeze(2)', 'return', 'x']
625,055
tryolabs/luminoth
fasterrcnn.py
FasterRCNN.summary
summary
Generate merged summary of all the sub-summaries used inside the Faster R-CNN network.
[ "Generate", "merged", "summary", "of", "all", "the", "sub-summaries", "used", "inside", "the", "Faster", "R-CNN", "network." ]
def summary(self): summaries = [tf.summary.merge_all(key='rpn')] summaries.append(tf.summary.merge_all(key=self._losses_collections[0])) if self._with_rcnn: summaries.append(tf.summary.merge_all(key='rcnn')) return tf.summary.merge(summaries)
['def', 'summary(self):', 'summaries', '=', "[tf.summary.merge_all(key='rpn')]", 'summaries.append(tf.summary.merge_all(key=self._losses_collections[0]))', 'if', 'self._with_rcnn:', "summaries.append(tf.summary.merge_all(key='rcnn'))", 'return', 'tf.summary.merge(summaries)']
617,470
ahottung/CVAE-Opt
tsp.py
update_mask
update_mask
Marks the visited city, so it can't be selected a second time.
[ "Marks", "the", "visited", "city,", "so", "it", "can't", "be", "selected", "a", "second", "time." ]
def update_mask(mask, dynamic, chosen_idx): mask.scatter_(1, chosen_idx.unsqueeze(1), 0) return mask
['def', 'update_mask(mask,', 'dynamic,', 'chosen_idx):', 'mask.scatter_(1,', 'chosen_idx.unsqueeze(1),', '0)', 'return', 'mask']
509,425
ifwe/digsby
imwin_ctrl.py
ImWinCtrl.on_send_message_im
on_send_message_im
Invoked when enter is pressed in the message input box during IM mode.
[ "Invoked", "when", "enter", "is", "pressed", "in", "the", "message", "input", "box", "during", "IM", "mode." ]
def on_send_message_im(self): val = self.input_area.GetFormattedValue() if not val.format_as('plaintext'): return self.history.commit(val.format_as('plaintext')) if self.set_conversation_from_combos(): self.convo.send_message(val) self.ClearAndFocus() return True
['def', 'on_send_message_im(self):', 'val', '=', 'self.input_area.GetFormattedValue()', 'if', 'not', "val.format_as('plaintext'):", 'return', "self.history.commit(val.format_as('plaintext'))", 'if', 'self.set_conversation_from_combos():', 'self.convo.send_message(val)', 'self.ClearAndFocus()', 'return', 'True']
185,382
43Carrig/recurrent_neural_networks_practice
gbdt_batch.py
GradientBoostedDecisionTreeModel.update_stats
update_stats
Update the accumulators with stats from this batch.
[ "Update", "the", "accumulators", "with", "stats", "from", "this", "batch." ]
def update_stats(self, loss, predictions_dict): input_deps = self._dense_floats + self._sparse_float_indices + self._sparse_int_indices worker_device = input_deps[0].device predictions = predictions_dict[PREDICTIONS] partition_ids = predictions_dict[PARTITION_IDS] ensemble_stamp = predictions_dict[E...
['def', 'update_stats(self,', 'loss,', 'predictions_dict):', 'input_deps', '=', 'self._dense_floats', '+', 'self._sparse_float_indices', '+', 'self._sparse_int_indices', 'worker_device', '=', 'input_deps[0].device', 'predictions', '=', 'predictions_dict[PREDICTIONS]', 'partition_ids', '=', 'predictions_dict[PARTITION_I...
312,593
rudranil723/mini-main
builder.py
PairPosBuilder.addClassPair
addClassPair
Add a class pair positioning rule to the current lookup.
[ "Add", "a", "class", "pair", "positioning", "rule", "to", "the", "current", "lookup." ]
def addClassPair(self, location, glyphclass1, value1, glyphclass2, value2): self.pairs.append((glyphclass1, value1, glyphclass2, value2))
['def', 'addClassPair(self,', 'location,', 'glyphclass1,', 'value1,', 'glyphclass2,', 'value2):', 'self.pairs.append((glyphclass1,', 'value1,', 'glyphclass2,', 'value2))']
317,315
arshpreetsingh/quantopian-machinelearning
frontend_widget.py
FrontendWidget.append_stream
append_stream
Appends text to the output stream.
[ "Appends", "text", "to", "the", "output", "stream." ]
def append_stream(self, text): text = text.expandtabs(8) self._append_plain_text(text, before_prompt=True)
['def', 'append_stream(self,', 'text):', 'text', '=', 'text.expandtabs(8)', 'self._append_plain_text(text,', 'before_prompt=True)']
892,880
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
AutoExpand.py
AutoExpand.getprevword
getprevword
Return the word prefix before the cursor.
[ "Return", "the", "word", "prefix", "before", "the", "cursor." ]
def getprevword(self): line = self.text.get('insert linestart', 'insert') i = len(line) while i > 0 and line[i - 1] in self.wordchars: i = i - 1 return line[i:]
['def', 'getprevword(self):', 'line', '=', "self.text.get('insert", "linestart',", "'insert')", 'i', '=', 'len(line)', 'while', 'i', '>', '0', 'and', 'line[i', '-', '1]', 'in', 'self.wordchars:', 'i', '=', 'i', '-', '1', 'return', 'line[i:]']
430,763
scikit-learn-contrib/imbalanced-learn
test_weight_boosting.py
test_rus_boost_classifier_base_estimator
test_rus_boost_classifier_base_estimator
Check that we raise a FutureWarning when accessing `base_estimator_`.
[ "Check", "that", "we", "raise", "a", "FutureWarning", "when", "accessing", "`base_estimator_`." ]
def test_rus_boost_classifier_base_estimator(): (X, y) = load_iris(return_X_y=True) estimator = RUSBoostClassifier().fit(X, y) with pytest.warns(FutureWarning, match='`base_estimator_` was deprecated'): estimator.base_estimator_
['def', 'test_rus_boost_classifier_base_estimator():', '(X,', 'y)', '=', 'load_iris(return_X_y=True)', 'estimator', '=', 'RUSBoostClassifier().fit(X,', 'y)', 'with', 'pytest.warns(FutureWarning,', "match='`base_estimator_`", 'was', "deprecated'):", 'estimator.base_estimator_']
610,652
Novartis/ChemBioMultimodalAutoencoders
joint_trainer.py
JointTrainer.translate
translate
Utility function allowing to translate a numpy array between any two registered modalities/models.
[ "Utility", "function", "allowing", "to", "translate", "a", "numpy", "array", "between", "any", "two", "registered", "modalities/models." ]
def translate(self, from_key: str, to_key: str, from_X: np.array, batch_size: int=256, use_gpu: bool=False) -> np.array: dataloader = self._dataloader_from_numpy(from_X, batch_size, False) from_model = self.model_dict[from_key] to_model = self.model_dict[to_key] from_model.eval() to_model.eval() ...
['def', 'translate(self,', 'from_key:', 'str,', 'to_key:', 'str,', 'from_X:', 'np.array,', 'batch_size:', 'int=256,', 'use_gpu:', 'bool=False)', '->', 'np.array:', 'dataloader', '=', 'self._dataloader_from_numpy(from_X,', 'batch_size,', 'False)', 'from_model', '=', 'self.model_dict[from_key]', 'to_model', '=', 'self.mo...
486,116
aws/sagemaker-python-sdk
estimator.py
TensorFlow.hyperparameters
hyperparameters
Return hyperparameters used by your custom TensorFlow code during model training.
[ "Return", "hyperparameters", "used", "by", "your", "custom", "TensorFlow", "code", "during", "model", "training." ]
def hyperparameters(self): hyperparameters = super(TensorFlow, self).hyperparameters() additional_hyperparameters = self._distribution_configuration(self.distribution) if self.model_dir is not False: self.model_dir = self.model_dir or self._default_s3_path('model', mpi=additional_hyperparameters.get...
['def', 'hyperparameters(self):', 'hyperparameters', '=', 'super(TensorFlow,', 'self).hyperparameters()', 'additional_hyperparameters', '=', 'self._distribution_configuration(self.distribution)', 'if', 'self.model_dir', 'is', 'not', 'False:', 'self.model_dir', '=', 'self.model_dir', 'or', "self._default_s3_path('model'...
830,553
dibyaghosh/gcsl
mjpy_renderer.py
MjPyRenderer.render_offscreen
render_offscreen
Renders the camera view as a numpy array of pixels.
[ "Renders", "the", "camera", "view", "as", "a", "numpy", "array", "of", "pixels." ]
def render_offscreen(self, width: int, height: int, mode: RenderMode=RenderMode.RGB, camera_id: int=-1) -> np.ndarray: assert width > 0 and height > 0 if not self._offscreen_renderer: self._offscreen_renderer = mujoco_py.MjRenderContextOffscreen(self._sim, device_id=-1) if camera_id == -1: s...
['def', 'render_offscreen(self,', 'width:', 'int,', 'height:', 'int,', 'mode:', 'RenderMode=RenderMode.RGB,', 'camera_id:', 'int=-1)', '->', 'np.ndarray:', 'assert', 'width', '>', '0', 'and', 'height', '>', '0', 'if', 'not', 'self._offscreen_renderer:', 'self._offscreen_renderer', '=', 'mujoco_py.MjRenderContextOffscre...
202,019
tanshen/SubCNN
layer.py
GtDataLayer.set_roidb
set_roidb
Set the roidb to be used by this layer during training.
[ "Set", "the", "roidb", "to", "be", "used", "by", "this", "layer", "during", "training." ]
def set_roidb(self, roidb): self._roidb = roidb self._shuffle_roidb_inds()
['def', 'set_roidb(self,', 'roidb):', 'self._roidb', '=', 'roidb', 'self._shuffle_roidb_inds()']
359,959
enuguru/artificial_intelligence_and_machine_
debug.py
dump_stack_frames
dump_stack_frames
Print a summary of the stack to stdout, or some place else.
[ "Print", "a", "summary", "of", "the", "stack", "to", "stdout,", "or", "some", "place", "else." ]
def dump_stack_frames(out=None): out = out or sys.stdout out.write(short_stack()) out.write('\n')
['def', 'dump_stack_frames(out=None):', 'out', '=', 'out', 'or', 'sys.stdout', 'out.write(short_stack())', "out.write('\\n')"]
157,367
microsoft/InnerEye-DeepLearning
lightning_loggers.py
StoringLogger.epochs
epochs
Gets the epochs for which the present object holds any results.
[ "Gets", "the", "epochs", "for", "which", "the", "present", "object", "holds", "any", "results." ]
def epochs(self) -> Iterable[int]: return self.results_per_epoch.keys()
['def', 'epochs(self)', '->', 'Iterable[int]:', 'return', 'self.results_per_epoch.keys()']
612,916
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Menu.tk_popup
tk_popup
Post the menu at position X,Y with entry ENTRY.
[ "Post", "the", "menu", "at", "position", "X,Y", "with", "entry", "ENTRY." ]
def tk_popup(self, x, y, entry=''): self.tk.call('tk_popup', self._w, x, y, entry)
['def', 'tk_popup(self,', 'x,', 'y,', "entry=''):", "self.tk.call('tk_popup',", 'self._w,', 'x,', 'y,', 'entry)']
377,010
rifqind/Agent-Programs-3KS1
builtin_trap.py
BuiltinTrap.deactivate
deactivate
Remove any builtins which might have been added by add_builtins, or restore overwritten ones to their previous values.
[ "Remove", "any", "builtins", "which", "might", "have", "been", "added", "by", "add_builtins,", "or", "restore", "overwritten", "ones", "to", "their", "previous", "values." ]
def deactivate(self): remove_builtin = self.remove_builtin for (key, val) in self._orig_builtins.items(): remove_builtin(key, val) self._orig_builtins.clear() self._builtins_added = False
['def', 'deactivate(self):', 'remove_builtin', '=', 'self.remove_builtin', 'for', '(key,', 'val)', 'in', 'self._orig_builtins.items():', 'remove_builtin(key,', 'val)', 'self._orig_builtins.clear()', 'self._builtins_added', '=', 'False']
40,892
open-mmlab/mmcv
iou3d.py
boxes_overlap_bev
boxes_overlap_bev
Calculate boxes BEV overlap.
[ "Calculate", "boxes", "BEV", "overlap." ]
def boxes_overlap_bev(boxes_a: Tensor, boxes_b: Tensor) -> Tensor: ans_overlap = boxes_a.new_zeros(torch.Size((boxes_a.shape[0], boxes_b.shape[0]))) ext_module.iou3d_boxes_overlap_bev_forward(boxes_a.contiguous(), boxes_b.contiguous(), ans_overlap) return ans_overlap
['def', 'boxes_overlap_bev(boxes_a:', 'Tensor,', 'boxes_b:', 'Tensor)', '->', 'Tensor:', 'ans_overlap', '=', 'boxes_a.new_zeros(torch.Size((boxes_a.shape[0],', 'boxes_b.shape[0])))', 'ext_module.iou3d_boxes_overlap_bev_forward(boxes_a.contiguous(),', 'boxes_b.contiguous(),', 'ans_overlap)', 'return', 'ans_overlap']
631,527
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
trainer_model_based.py
rl_modelrl_xentcutoff_range
rl_modelrl_xentcutoff_range
Cross entropy cutoff tuning grid.
[ "Cross", "entropy", "cutoff", "tuning", "grid." ]
def rl_modelrl_xentcutoff_range(rhp): rhp.set_float('model.video_modality_loss_cutoff', 0.01, 0.05)
['def', 'rl_modelrl_xentcutoff_range(rhp):', "rhp.set_float('model.video_modality_loss_cutoff',", '0.01,', '0.05)']
966,012
jimtin/Stock_Comparison
inputtransformer.py
InputTransformer.wrap
wrap
Can be used by subclasses as a decorator, to return a factory that will allow instantiation with the decorated object.
[ "Can", "be", "used", "by", "subclasses", "as", "a", "decorator,", "to", "return", "a", "factory", "that", "will", "allow", "instantiation", "with", "the", "decorated", "object." ]
def wrap(cls, func): @functools.wraps(func) def transformer_factory(**kwargs): return cls(func, **kwargs) return transformer_factory
['def', 'wrap(cls,', 'func):', '@functools.wraps(func)', 'def', 'transformer_factory(**kwargs):', 'return', 'cls(func,', '**kwargs)', 'return', 'transformer_factory']
384,725
aws/sagemaker-python-sdk
session.py
Session.delete_endpoint
delete_endpoint
Delete an Amazon SageMaker ``Endpoint``.
[ "Delete", "an", "Amazon", "SageMaker", "``Endpoint``." ]
def delete_endpoint(self, endpoint_name): LOGGER.info('Deleting endpoint with name: %s', endpoint_name) self.sagemaker_client.delete_endpoint(EndpointName=endpoint_name)
['def', 'delete_endpoint(self,', 'endpoint_name):', "LOGGER.info('Deleting", 'endpoint', 'with', 'name:', "%s',", 'endpoint_name)', 'self.sagemaker_client.delete_endpoint(EndpointName=endpoint_name)']
829,633
LiDan456/MAD-GANs
plotting.py
save_mnist_plot_sample
save_mnist_plot_sample
Generates a grid showing mnist digits.
[ "Generates", "a", "grid", "showing", "mnist", "digits." ]
def save_mnist_plot_sample(samples, idx, identifier, n_samples, labels=None): assert n_samples <= samples.shape[0] if not labels is None: assert n_samples <= len(labels) if len(labels.shape) > 1 and (not labels.shape[1] == 1): label_titles = np.argmax(labels, axis=1) else: ...
['def', 'save_mnist_plot_sample(samples,', 'idx,', 'identifier,', 'n_samples,', 'labels=None):', 'assert', 'n_samples', '<=', 'samples.shape[0]', 'if', 'not', 'labels', 'is', 'None:', 'assert', 'n_samples', '<=', 'len(labels)', 'if', 'len(labels.shape)', '>', '1', 'and', '(not', 'labels.shape[1]', '==', '1):', 'label_t...
626,811
HighnessAtharva/VocabCLI
vocabCLI.py
unmaster
unmaster
Removes a word from the mastered list.
[ "Removes", "a", "word", "from", "the", "mastered", "list." ]
def unmaster(words: List[str]=typer.Argument(..., help='ðÂ\x9f¤Â\x94Word to remove from [bold blue]mastered[/bold blue]')): from modules.Utils import set_unmastered for word in words: set_unmastered(word)
['def', 'unmaster(words:', 'List[str]=typer.Argument(...,', "help='ðÂ\\x9f¤Â\\x94Word", 'to', 'remove', 'from', '[bold', 'blue]mastered[/bold', "blue]')):", 'from', 'modules.Utils', 'import', 'set_unmastered', 'for', 'word', 'in', 'words:', 'set_unmastered(word)']
946,219
NoGameNoLife00/mybolg
wrappers.py
DynamicCharsetRequestMixin.charset
charset
The charset from the content type.
[ "The", "charset", "from", "the", "content", "type." ]
def charset(self): header = self.environ.get('CONTENT_TYPE') if header: (ct, options) = parse_options_header(header) charset = options.get('charset') if charset: if is_known_charset(charset): return charset return self.unknown_charset(charset) ...
['def', 'charset(self):', 'header', '=', "self.environ.get('CONTENT_TYPE')", 'if', 'header:', '(ct,', 'options)', '=', 'parse_options_header(header)', 'charset', '=', "options.get('charset')", 'if', 'charset:', 'if', 'is_known_charset(charset):', 'return', 'charset', 'return', 'self.unknown_charset(charset)', 'return',...
290,083
ryu-ed/SpaceInvaders_Ros
math2html.py
BigBracket.getpiece4
getpiece4
Get the nth piece for a 4-piece bracket: curly bracket.
[ "Get", "the", "nth", "piece", "for", "a", "4-piece", "bracket:", "curly", "bracket." ]
def getpiece4(self, index): if index == 0: return self.pieces[0] if index == self.size - 1: return self.pieces[3] if index == (self.size - 1) / 2: return self.pieces[2] return self.pieces[1]
['def', 'getpiece4(self,', 'index):', 'if', 'index', '==', '0:', 'return', 'self.pieces[0]', 'if', 'index', '==', 'self.size', '-', '1:', 'return', 'self.pieces[3]', 'if', 'index', '==', '(self.size', '-', '1)', '/', '2:', 'return', 'self.pieces[2]', 'return', 'self.pieces[1]']
395,313
ZumoLabs/zpy
saver_video.py
VideoSaver.add_annotation
add_annotation
Add a new annotation to the Saver object.
[ "Add", "a", "new", "annotation", "to", "the", "Saver", "object." ]
def add_annotation(self, *args, video: str='default video', **kwargs) -> Dict: annotation = super().add_annotation(*args, **kwargs) video_id = self.video_name_to_id.get(video, None) assert video_id is not None, f'Could not find id for video {video}' annotation['video_id'] = video_id annotation.updat...
['def', 'add_annotation(self,', '*args,', 'video:', "str='default", "video',", '**kwargs)', '->', 'Dict:', 'annotation', '=', 'super().add_annotation(*args,', '**kwargs)', 'video_id', '=', 'self.video_name_to_id.get(video,', 'None)', 'assert', 'video_id', 'is', 'not', 'None,', "f'Could", 'not', 'find', 'id', 'for', 'vi...
972,122
QData/deepWordBug
states.py
Body.line_block_line
line_block_line
Return one line element of a line_block.
[ "Return", "one", "line", "element", "of", "a", "line_block." ]
def line_block_line(self, match, lineno): (indented, indent, line_offset, blank_finish) = self.state_machine.get_first_known_indented(match.end(), until_blank=True) text = '\n'.join(indented) (text_nodes, messages) = self.inline_text(text, lineno) line = nodes.line(text, '', *text_nodes) if match.st...
['def', 'line_block_line(self,', 'match,', 'lineno):', '(indented,', 'indent,', 'line_offset,', 'blank_finish)', '=', 'self.state_machine.get_first_known_indented(match.end(),', 'until_blank=True)', 'text', '=', "'\\n'.join(indented)", '(text_nodes,', 'messages)', '=', 'self.inline_text(text,', 'lineno)', 'line', '=', ...
542,169
johny-c/incremental-label-propagation
data_flow.py
gen_data_stream
gen_data_stream
Generates a sequence of all inputs and targets, optionally shuffled.
[ "Generates", "a", "sequence", "of", "all", "inputs", "and", "targets,", "optionally", "shuffled." ]
def gen_data_stream(inputs, targets, shuffle=False, seed=None): assert len(inputs) == len(targets) if shuffle: indices = np.arange(len(inputs)) random_state = check_random_state(seed) random_state.shuffle(indices) for i in indices: yield (inputs[i], targets[i]) el...
['def', 'gen_data_stream(inputs,', 'targets,', 'shuffle=False,', 'seed=None):', 'assert', 'len(inputs)', '==', 'len(targets)', 'if', 'shuffle:', 'indices', '=', 'np.arange(len(inputs))', 'random_state', '=', 'check_random_state(seed)', 'random_state.shuffle(indices)', 'for', 'i', 'in', 'indices:', 'yield', '(inputs[i],...
229,488
rifqind/Agent-Programs-3KS1
agents.py
GraphicEnvironment.get_world
get_world
Returns all the items in the world in a format understandable by the ipythonblocks BlockGrid.
[ "Returns", "all", "the", "items", "in", "the", "world", "in", "a", "format", "understandable", "by", "the", "ipythonblocks", "BlockGrid." ]
def get_world(self): result = [] (x_start, y_start) = (0, 0) (x_end, y_end) = (self.width, self.height) for x in range(x_start, x_end): row = [] for y in range(y_start, y_end): row.append(self.list_things_at([x, y])) result.append(row) return result
['def', 'get_world(self):', 'result', '=', '[]', '(x_start,', 'y_start)', '=', '(0,', '0)', '(x_end,', 'y_end)', '=', '(self.width,', 'self.height)', 'for', 'x', 'in', 'range(x_start,', 'x_end):', 'row', '=', '[]', 'for', 'y', 'in', 'range(y_start,', 'y_end):', 'row.append(self.list_things_at([x,', 'y]))', 'result.appe...
40,387
facebookresearch/CompilerGym
benchmark_test.py
test_benchmark_immutable
test_benchmark_immutable
Test that benchmark properties are immutable.
[ "Test", "that", "benchmark", "properties", "are", "immutable." ]
def test_benchmark_immutable(): benchmark = Benchmark(BenchmarkProto(uri='benchmark://example-compiler-v0/foobar')) with pytest.raises(AttributeError): benchmark.uri = 123 with pytest.raises(AttributeError): benchmark.proto = 123
['def', 'test_benchmark_immutable():', 'benchmark', '=', "Benchmark(BenchmarkProto(uri='benchmark://example-compiler-v0/foobar'))", 'with', 'pytest.raises(AttributeError):', 'benchmark.uri', '=', '123', 'with', 'pytest.raises(AttributeError):', 'benchmark.proto', '=', '123']
125,849
kubeflow/pipelines
metrics_utils.py
ConfusionMatrix.log_row
log_row
Logs a confusion matrix row.
[ "Logs", "a", "confusion", "matrix", "row." ]
def log_row(self, row_category: str, row: List[int]): if row_category not in self._categories: raise ValueError('Invalid category: {} passed. Expected one of: {}'.format(row_category, self._categories)) if len(row) != len(self._categories): raise ValueError('Invalid row. Expected size: {} got: {...
['def', 'log_row(self,', 'row_category:', 'str,', 'row:', 'List[int]):', 'if', 'row_category', 'not', 'in', 'self._categories:', 'raise', "ValueError('Invalid", 'category:', '{}', 'passed.', 'Expected', 'one', 'of:', "{}'.format(row_category,", 'self._categories))', 'if', 'len(row)', '!=', 'len(self._categories):', 'ra...
780,094
xuannianz/SAPD
efficientnet.py
round_filters
round_filters
Round number of filters based on width multiplier.
[ "Round", "number", "of", "filters", "based", "on", "width", "multiplier." ]
def round_filters(filters, width_coefficient, depth_divisor): filters *= width_coefficient new_filters = int(filters + depth_divisor / 2) // depth_divisor * depth_divisor new_filters = max(depth_divisor, new_filters) if new_filters < 0.9 * filters: new_filters += depth_divisor return int(new...
['def', 'round_filters(filters,', 'width_coefficient,', 'depth_divisor):', 'filters', '*=', 'width_coefficient', 'new_filters', '=', 'int(filters', '+', 'depth_divisor', '/', '2)', '//', 'depth_divisor', '*', 'depth_divisor', 'new_filters', '=', 'max(depth_divisor,', 'new_filters)', 'if', 'new_filters', '<', '0.9', '*'...
845,370
TonyLianLong/VAI-ReinforcementLearning
namescope.py
NameScope.remove
remove
Removes an identifier from this name scope.
[ "Removes", "an", "identifier", "from", "this", "name", "scope." ]
def remove(self, namespace, identifier): del self._namespaces[namespace][identifier] self.increment_revision()
['def', 'remove(self,', 'namespace,', 'identifier):', 'del', 'self._namespaces[namespace][identifier]', 'self.increment_revision()']
440,032
vturrisi/solo-learn
mae.py
MAE.forward
forward
Performs forward pass of the online backbone, projector and predictor.
[ "Performs", "forward", "pass", "of", "the", "online", "backbone,", "projector", "and", "predictor." ]
def forward(self, X: torch.Tensor) -> Dict[str, Any]: if not self.no_channel_last: X = X.to(memory_format=torch.channels_last) out = {} if self.training: (feats, patch_feats, mask, ids_restore) = self.backbone(X, self.mask_ratio) pred = self.decoder(patch_feats, ids_restore) ...
['def', 'forward(self,', 'X:', 'torch.Tensor)', '->', 'Dict[str,', 'Any]:', 'if', 'not', 'self.no_channel_last:', 'X', '=', 'X.to(memory_format=torch.channels_last)', 'out', '=', '{}', 'if', 'self.training:', '(feats,', 'patch_feats,', 'mask,', 'ids_restore)', '=', 'self.backbone(X,', 'self.mask_ratio)', 'pred', '=', '...
393,635
opendilab/DI-star
renderer_human.py
RendererHuman.run
run
Run loop that gets observations, renders them, and sends back actions.
[ "Run", "loop", "that", "gets", "observations,", "renders", "them,", "and", "sends", "back", "actions." ]
def run(self, run_config, controller, max_game_steps=0, max_episodes=0, game_steps_per_episode=0, save_replay=False): is_replay = controller.status == remote_controller.Status.in_replay total_game_steps = 0 start_time = time.time() num_episodes = 0 try: while True: self.init(cont...
['def', 'run(self,', 'run_config,', 'controller,', 'max_game_steps=0,', 'max_episodes=0,', 'game_steps_per_episode=0,', 'save_replay=False):', 'is_replay', '=', 'controller.status', '==', 'remote_controller.Status.in_replay', 'total_game_steps', '=', '0', 'start_time', '=', 'time.time()', 'num_episodes', '=', '0', 'try...
184,802
microsoft/nni
serializer.py
Traceable.trace_kwargs
trace_kwargs
Dict of keyword arguments.
[ "Dict", "of", "keyword", "arguments." ]
def trace_kwargs(self) -> Dict[str, Any]: raise NotImplementedError()
['def', 'trace_kwargs(self)', '->', 'Dict[str,', 'Any]:', 'raise', 'NotImplementedError()']
728,460
BigDataBiology/SemiBin
atomicwrite.py
AtomicWriter.commit
commit
Move the temporary file to the target location.
[ "Move", "the", "temporary", "file", "to", "the", "target", "location." ]
def commit(self, f): if self._overwrite: replace_atomic(f.name, self._path) else: move_atomic(f.name, self._path)
['def', 'commit(self,', 'f):', 'if', 'self._overwrite:', 'replace_atomic(f.name,', 'self._path)', 'else:', 'move_atomic(f.name,', 'self._path)']
343,536
Eric3911/OpenAGI
analyze_errors.py
ErrorCase.get_spans
get_spans
This method extracts the list of spans.
[ "This", "method", "extracts", "the", "list", "of", "spans." ]
def get_spans(self, tokens_hightlight): (spans, nb_tokens) = ([], len(tokens_hightlight)) (cur_start_idx, cur_bool_val) = (0, tokens_hightlight[0]) for idx in range(nb_tokens): if idx == nb_tokens - 1: if tokens_hightlight[idx] != cur_bool_val: spans.append((cur_start_idx...
['def', 'get_spans(self,', 'tokens_hightlight):', '(spans,', 'nb_tokens)', '=', '([],', 'len(tokens_hightlight))', '(cur_start_idx,', 'cur_bool_val)', '=', '(0,', 'tokens_hightlight[0])', 'for', 'idx', 'in', 'range(nb_tokens):', 'if', 'idx', '==', 'nb_tokens', '-', '1:', 'if', 'tokens_hightlight[idx]', '!=', 'cur_bool_...
272,142
aleju/self-driving-truck
batching.py
to_rgb
to_rgb
Convert an image from (h, w) to (h, w, 3).
[ "Convert", "an", "image", "from", "(h,", "w)", "to", "(h,", "w,", "3)." ]
def to_rgb(im): if im.ndim == 3: if im.shape[2] == 3: return im else: return np.tile(im, (1, 1, 3)) else: return np.tile(im[:, :, np.newaxis], (1, 1, 3))
['def', 'to_rgb(im):', 'if', 'im.ndim', '==', '3:', 'if', 'im.shape[2]', '==', '3:', 'return', 'im', 'else:', 'return', 'np.tile(im,', '(1,', '1,', '3))', 'else:', 'return', 'np.tile(im[:,', ':,', 'np.newaxis],', '(1,', '1,', '3))']
843,258
mrdvince/autoencoders
autoencoders.py
TFVariationalAutoencoder.reconstruct
reconstruct
Use VAE to reconstruct given data.
[ "Use", "VAE", "to", "reconstruct", "given", "data." ]
def reconstruct(self, X): return self.sess.run(self.x_reconstr_mean, feed_dict={self.x: X})
['def', 'reconstruct(self,', 'X):', 'return', 'self.sess.run(self.x_reconstr_mean,', 'feed_dict={self.x:', 'X})']
419,529
charlesCXK/TorchSemiSeg
parallel_apply.py
parallel_apply
parallel_apply
Applies each `module` in :attr:`modules` in parallel on arguments contained in :attr:`inputs` (positional) and :attr:`kwargs_tup` (keyword) on each of :attr:`devices`.
[ "Applies", "each", "`module`", "in", ":attr:`modules`", "in", "parallel", "on", "arguments", "contained", "in", ":attr:`inputs`", "(positional)", "and", ":attr:`kwargs_tup`", "(keyword)", "on", "each", "of", ":attr:`devices`." ]
def parallel_apply(modules, inputs, kwargs_tup=None, devices=None): assert len(modules) == len(inputs) if kwargs_tup is not None: assert len(modules) == len(kwargs_tup) else: kwargs_tup = ({},) * len(modules) if devices is not None: assert len(modules) == len(devices) else: ...
['def', 'parallel_apply(modules,', 'inputs,', 'kwargs_tup=None,', 'devices=None):', 'assert', 'len(modules)', '==', 'len(inputs)', 'if', 'kwargs_tup', 'is', 'not', 'None:', 'assert', 'len(modules)', '==', 'len(kwargs_tup)', 'else:', 'kwargs_tup', '=', '({},)', '*', 'len(modules)', 'if', 'devices', 'is', 'not', 'None:',...
903,438
tensorflow/quantum
serializable_gate_set_test.py
SerializableGateSetTest.test_serialize_deserialize_empty_circuit
test_serialize_deserialize_empty_circuit
Verify empty case serialize deserialize works.
[ "Verify", "empty", "case", "serialize", "deserialize", "works." ]
def test_serialize_deserialize_empty_circuit(self): circuit = cirq.Circuit() proto = program_pb2.Program(language=program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=program_pb2.Circuit(scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[])) self.assertEqual(proto,...
['def', 'test_serialize_deserialize_empty_circuit(self):', 'circuit', '=', 'cirq.Circuit()', 'proto', '=', "program_pb2.Program(language=program_pb2.Language(arg_function_language='',", "gate_set='my_gate_set'),", 'circuit=program_pb2.Circuit(scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT,', 'moments=[]))', '...
834,967
weimin17/Object-Detection_HelmetDetection
model_lib.py
filter_trainable_variables
filter_trainable_variables
Keep only trainable variables which are prefixed with given scopes.
[ "Keep", "only", "trainable", "variables", "which", "are", "prefixed", "with", "given", "scopes." ]
def filter_trainable_variables(trainable_scopes): if not trainable_scopes: return if isinstance(trainable_scopes, six.string_types): trainable_scopes = [scope.strip() for scope in trainable_scopes.split(',')] trainable_scopes = {scope for scope in trainable_scopes if scope} if not traina...
['def', 'filter_trainable_variables(trainable_scopes):', 'if', 'not', 'trainable_scopes:', 'return', 'if', 'isinstance(trainable_scopes,', 'six.string_types):', 'trainable_scopes', '=', '[scope.strip()', 'for', 'scope', 'in', "trainable_scopes.split(',')]", 'trainable_scopes', '=', '{scope', 'for', 'scope', 'in', 'trai...
761,405
AnuragAnalog/Code-for-learn-machinelearning
scaling.py
scaling.normalization
normalization
The values of the data are scaled to the interval [-1, 1] with a mean of zero.
[ "The", "values", "of", "the", "data", "are", "scaled", "to", "the", "interval", "[-1,", "1]", "with", "a", "mean", "of", "zero." ]
def normalization(self, data: [np.array, list]) -> np.array: data = np.array(data) self.checkna(data) shape = np.shape(data) if len(shape) == 1: data = (data - np.mean(data)) / (max(data) - min(data)) elif len(shape) == 2: for i in range(shape[-1]): mu = np.mean(data[:, i...
['def', 'normalization(self,', 'data:', '[np.array,', 'list])', '->', 'np.array:', 'data', '=', 'np.array(data)', 'self.checkna(data)', 'shape', '=', 'np.shape(data)', 'if', 'len(shape)', '==', '1:', 'data', '=', '(data', '-', 'np.mean(data))', '/', '(max(data)', '-', 'min(data))', 'elif', 'len(shape)', '==', '2:', 'fo...
493,579
MANGA-UOFA/NAUS
utils.py
get_data_parallel_world_size
get_data_parallel_world_size
Return world size for the data parallel group.
[ "Return", "world", "size", "for", "the", "data", "parallel", "group." ]
def get_data_parallel_world_size(): return get_world_size(get_data_parallel_group())
['def', 'get_data_parallel_world_size():', 'return', 'get_world_size(get_data_parallel_group())']
291,444
loicmarie/hands-detection
utils.py
save_image
save_image
Function that dumps the image to disk.
[ "Function", "that", "dumps", "the", "image", "to", "disk." ]
def save_image(inp_array, image_file): inp_array = np.clip(inp_array, 0, 255).astype(np.uint8) image = Image.fromarray(inp_array) buf = StringIO.StringIO() image.save(buf, format='JPEG') with open(image_file, 'w') as f: f.write(buf.getvalue()) return None
['def', 'save_image(inp_array,', 'image_file):', 'inp_array', '=', 'np.clip(inp_array,', '0,', '255).astype(np.uint8)', 'image', '=', 'Image.fromarray(inp_array)', 'buf', '=', 'StringIO.StringIO()', 'image.save(buf,', "format='JPEG')", 'with', 'open(image_file,', "'w')", 'as', 'f:', 'f.write(buf.getvalue())', 'return',...
575,156
PaddlePaddle/Paddle3D
bevdet4d.py
BEVDet4D.aug_test
aug_test
Test function without augmentation.
[ "Test", "function", "without", "augmentation." ]
def aug_test(self, points, img_metas, img=None, rescale=False): assert False
['def', 'aug_test(self,', 'points,', 'img_metas,', 'img=None,', 'rescale=False):', 'assert', 'False']
777,387
bnpy/bnpy
ProposalViz.py
plotELBOtermsForProposal
plotELBOtermsForProposal
Create trace plot of ELBO gain/loss relative to current model.
[ "Create", "trace", "plot", "of", "ELBO", "gain/loss", "relative", "to", "current", "model." ]
def plotELBOtermsForProposal(curLdict, propLdictList, xs=None, ymin=-0.5, ymax=0.5, savefilename=None, **kwargs): pylab.figure() L = len(propLdictList) if xs is None: xs = np.arange(0, L) legendKeys = [] for key in curLdict: if key.count('_') == 0: legendKeys.append(key) ...
['def', 'plotELBOtermsForProposal(curLdict,', 'propLdictList,', 'xs=None,', 'ymin=-0.5,', 'ymax=0.5,', 'savefilename=None,', '**kwargs):', 'pylab.figure()', 'L', '=', 'len(propLdictList)', 'if', 'xs', 'is', 'None:', 'xs', '=', 'np.arange(0,', 'L)', 'legendKeys', '=', '[]', 'for', 'key', 'in', 'curLdict:', 'if', "key.co...
465,284
rudranil723/mini-main
coordseq.py
GEOSCoordSeq.tuple
tuple
Return a tuple version of this coordinate sequence.
[ "Return", "a", "tuple", "version", "of", "this", "coordinate", "sequence." ]
def tuple(self): n = self.size get_point = self._point_getter if n == 1: return get_point(0) return tuple((get_point(i) for i in range(n)))
['def', 'tuple(self):', 'n', '=', 'self.size', 'get_point', '=', 'self._point_getter', 'if', 'n', '==', '1:', 'return', 'get_point(0)', 'return', 'tuple((get_point(i)', 'for', 'i', 'in', 'range(n)))']
315,273
wutong8023/CoLL
config.py
OnnxConfig.flatten_output_collection_property
flatten_output_collection_property
Flatten any potential nested structure expanding the name of the field with the index of the element within the structure.
[ "Flatten", "any", "potential", "nested", "structure", "expanding", "the", "name", "of", "the", "field", "with", "the", "index", "of", "the", "element", "within", "the", "structure." ]
def flatten_output_collection_property(name: str, field: Iterable[Any]) -> Dict[str, Any]: from itertools import chain return {f'{name}.{idx}': item for (idx, item) in enumerate(chain.from_iterable(field))}
['def', 'flatten_output_collection_property(name:', 'str,', 'field:', 'Iterable[Any])', '->', 'Dict[str,', 'Any]:', 'from', 'itertools', 'import', 'chain', 'return', "{f'{name}.{idx}':", 'item', 'for', '(idx,', 'item)', 'in', 'enumerate(chain.from_iterable(field))}']
466,997
tobegit3hub/deep_image_model
dataframe_test.py
setup_test_df
setup_test_df
Create a dataframe populated with some test columns.
[ "Create", "a", "dataframe", "populated", "with", "some", "test", "columns." ]
def setup_test_df(): df = learn.DataFrame() df['a'] = learn.TransformedSeries([mocks.MockSeries('foobar', mocks.MockTensor('Tensor a', tf.int32))], mocks.MockTwoOutputTransform('iue', 'eui', 'snt'), 'out1') df['b'] = learn.TransformedSeries([mocks.MockSeries('foobar', mocks.MockTensor('Tensor b', tf.int32))...
['def', 'setup_test_df():', 'df', '=', 'learn.DataFrame()', "df['a']", '=', "learn.TransformedSeries([mocks.MockSeries('foobar',", "mocks.MockTensor('Tensor", "a',", 'tf.int32))],', "mocks.MockTwoOutputTransform('iue',", "'eui',", "'snt'),", "'out1')", "df['b']", '=', "learn.TransformedSeries([mocks.MockSeries('foobar'...
181,868
open-mmlab/mmselfsup
utils.py
_DummyAxis.get_minpos
get_minpos
Return the minimum positive value for the axis.
[ "Return", "the", "minimum", "positive", "value", "for", "the", "axis." ]
def get_minpos(self) -> float: return self._minpos
['def', 'get_minpos(self)', '->', 'float:', 'return', 'self._minpos']
240,501
hamza-murad/AALU
discovery_v1.py
SourceStatus.from_dict
from_dict
Initialize a SourceStatus object from a json dictionary.
[ "Initialize", "a", "SourceStatus", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'SourceStatus': args = {} valid_keys = ['status', 'next_crawl'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for class SourceStatus: ' + ', '.join(bad_keys)) if 'status' in _dict: ...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'SourceStatus':", 'args', '=', '{}', 'valid_keys', '=', "['status',", "'next_crawl']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dictionary', 'for', 'class', 'Source...
5,680
Kvatsx/Artificial-Intelligence-Assignments
test_run.py
TestMagicRunSimple.test_unicode
test_unicode
Check that files in odd encodings are accepted.
[ "Check", "that", "files", "in", "odd", "encodings", "are", "accepted." ]
def test_unicode(self): mydir = os.path.dirname(__file__) na = os.path.join(mydir, 'nonascii.py') _ip.magic('run "%s"' % na) nt.assert_equal(_ip.user_ns['u'], u'Ã\x90Â\x8eÃ\x91Â\x82âÂ\x84Â\x96Ã\x90¤')
['def', 'test_unicode(self):', 'mydir', '=', 'os.path.dirname(__file__)', 'na', '=', 'os.path.join(mydir,', "'nonascii.py')", "_ip.magic('run", '"%s"\'', '%', 'na)', "nt.assert_equal(_ip.user_ns['u'],", "u'Ã\\x90Â\\x8eÃ\\x91Â\\x82âÂ\\x84Â\\x96Ã\\x90¤')"]
38,510
zihuitang/medical_AI_platform
__init__.py
Menu.add_command
add_command
Add command menu item.
[ "Add", "command", "menu", "item." ]
def add_command(self, cnf={}, **kw): self.add('command', cnf or kw)
['def', 'add_command(self,', 'cnf={},', '**kw):', "self.add('command',", 'cnf', 'or', 'kw)']
284,289
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.pair_margin
pair_margin
detect contact if dist<margin (npair x 1).
[ "detect", "contact", "if", "dist<margin", "(npair", "x", "1)." ]
def pair_margin(self): return util.buf_to_npy(self._ptr.contents.pair_margin, (self.npair,))
['def', 'pair_margin(self):', 'return', 'util.buf_to_npy(self._ptr.contents.pair_margin,', '(self.npair,))']
440,397
huawei-noah/xingtian
share_by_redis.py
ShareByRedis.send
send
Send data to redis server.
[ "Send", "data", "to", "redis", "server." ]
def send(self, data, name=None, block=True): data_buffer = pyarrow.serialize(data).to_buffer() self.redis.set(name, data_buffer)
['def', 'send(self,', 'data,', 'name=None,', 'block=True):', 'data_buffer', '=', 'pyarrow.serialize(data).to_buffer()', 'self.redis.set(name,', 'data_buffer)']
962,382
pokaxpoka/sunrise
fisher_factors.py
set_global_constants
set_global_constants
Sets various global constants used by the classes in this module.
[ "Sets", "various", "global", "constants", "used", "by", "the", "classes", "in", "this", "module." ]
def set_global_constants(init_covariances_at_zero=None, zero_debias=None, eigenvalue_decomposition_threshold=None, eigenvalue_clipping_threshold=None): global INIT_COVARIANCES_AT_ZERO global ZERO_DEBIAS global EIGENVALUE_DECOMPOSITION_THRESHOLD global EIGENVALUE_CLIPPING_THRESHOLD if init_covariance...
['def', 'set_global_constants(init_covariances_at_zero=None,', 'zero_debias=None,', 'eigenvalue_decomposition_threshold=None,', 'eigenvalue_clipping_threshold=None):', 'global', 'INIT_COVARIANCES_AT_ZERO', 'global', 'ZERO_DEBIAS', 'global', 'EIGENVALUE_DECOMPOSITION_THRESHOLD', 'global', 'EIGENVALUE_CLIPPING_THRESHOLD'...
911,809
Ruturaj123/Flowchart-Detection
metric_ops_test.py
StreamingAUCTest.np_auc
np_auc
Computes the AUC explicitly using Numpy.
[ "Computes", "the", "AUC", "explicitly", "using", "Numpy." ]
def np_auc(self, predictions, labels, weights): if weights is None: weights = np.ones(np.size(predictions)) is_positive = labels > 0 num_positives = np.sum(weights[is_positive]) num_negatives = np.sum(weights[~is_positive]) inds = np.argsort(-predictions) sorted_labels = labels[inds] ...
['def', 'np_auc(self,', 'predictions,', 'labels,', 'weights):', 'if', 'weights', 'is', 'None:', 'weights', '=', 'np.ones(np.size(predictions))', 'is_positive', '=', 'labels', '>', '0', 'num_positives', '=', 'np.sum(weights[is_positive])', 'num_negatives', '=', 'np.sum(weights[~is_positive])', 'inds', '=', 'np.argsort(-...
604,333
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
cifar_input.py
build_input
build_input
Build CIFAR image and labels.
[ "Build", "CIFAR", "image", "and", "labels." ]
def build_input(dataset, data_path, batch_size, mode): image_size = 32 if dataset == 'cifar10': label_bytes = 1 label_offset = 0 num_classes = 10 elif dataset == 'cifar100': label_bytes = 1 label_offset = 1 num_classes = 100 else: raise ValueError(...
['def', 'build_input(dataset,', 'data_path,', 'batch_size,', 'mode):', 'image_size', '=', '32', 'if', 'dataset', '==', "'cifar10':", 'label_bytes', '=', '1', 'label_offset', '=', '0', 'num_classes', '=', '10', 'elif', 'dataset', '==', "'cifar100':", 'label_bytes', '=', '1', 'label_offset', '=', '1', 'num_classes', '=',...
26,728
FedML-AI/FedML
envs.py
get_envs
get_envs
Get PyTorch needed environments from system envirionments.
[ "Get", "PyTorch", "needed", "environments", "from", "system", "envirionments." ]
def get_envs(): local_rank = int(os.getenv('LOCAL_RANK', -1)) rank = int(os.getenv('RANK', -1)) world_size = int(os.getenv('WORLD_SIZE', 1)) return (local_rank, rank, world_size)
['def', 'get_envs():', 'local_rank', '=', "int(os.getenv('LOCAL_RANK',", '-1))', 'rank', '=', "int(os.getenv('RANK',", '-1))', 'world_size', '=', "int(os.getenv('WORLD_SIZE',", '1))', 'return', '(local_rank,', 'rank,', 'world_size)']
545,085
triaquae/triaquae
operations.py
PostGISOperations.postgis_geos_version
postgis_geos_version
Returns the version of the GEOS library used with PostGIS.
[ "Returns", "the", "version", "of", "the", "GEOS", "library", "used", "with", "PostGIS." ]
def postgis_geos_version(self): return self._get_postgis_func('postgis_geos_version')
['def', 'postgis_geos_version(self):', 'return', "self._get_postgis_func('postgis_geos_version')"]
357,452
matsu0228/nlp-jp
image.py
_ImageBase.get_resample
get_resample
Return the image resample boolean.
[ "Return", "the", "image", "resample", "boolean." ]
def get_resample(self): return self._resample
['def', 'get_resample(self):', 'return', 'self._resample']
788,834
pedrojrv/nucml
plot.py
ml_results_plotly
ml_results_plotly
Plot the machine learning predictions from the dictionary generated by the.
[ "Plot", "the", "machine", "learning", "predictions", "from", "the", "dictionary", "generated", "by", "the." ]
def ml_results_plotly(results_dict, order_dict={}, save=False, render_browser=False, show=False): fig = go.Figure() if len(order_dict) == 0: order_dict = {'1': 'endf', '4': 'exfor_ml_original', '3': 'exfor_ml', '2': 'exfor_new'} exfor_original_trace = go.Scattergl(x=results_dict['exfor_ml_original']...
['def', 'ml_results_plotly(results_dict,', 'order_dict={},', 'save=False,', 'render_browser=False,', 'show=False):', 'fig', '=', 'go.Figure()', 'if', 'len(order_dict)', '==', '0:', 'order_dict', '=', "{'1':", "'endf',", "'4':", "'exfor_ml_original',", "'3':", "'exfor_ml',", "'2':", "'exfor_new'}", 'exfor_original_trace...
249,734
vals/SdA
utils.py
load_data
load_data
Loads the dataset :type dataset: string :param dataset: the path to the dataset.
[ "Loads", "the", "dataset", ":type", "dataset:", "string", ":param", "dataset:", "the", "path", "to", "the", "dataset." ]
def load_data(dataset): df = pd.read_table(dataset) data = df.ix[:, 1:].as_matrix() index = list(df.ix[:, 0]) def shared_dataset(data, borrow=True): data = data shared_data = theano.shared(numpy.asarray(data, dtype=theano.config.floatX), borrow=borrow) return shared_data dat...
['def', 'load_data(dataset):', 'df', '=', 'pd.read_table(dataset)', 'data', '=', 'df.ix[:,', '1:].as_matrix()', 'index', '=', 'list(df.ix[:,', '0])', 'def', 'shared_dataset(data,', 'borrow=True):', 'data', '=', 'data', 'shared_data', '=', 'theano.shared(numpy.asarray(data,', 'dtype=theano.config.floatX),', 'borrow=borr...
855,129
rudranil723/mini-main
options.py
ModelAdmin.save_formset
save_formset
Given an inline formset save it to the database.
[ "Given", "an", "inline", "formset", "save", "it", "to", "the", "database." ]
def save_formset(self, request, form, formset, change): formset.save()
['def', 'save_formset(self,', 'request,', 'form,', 'formset,', 'change):', 'formset.save()']
314,777
RasaHQ/rasa
trackers.py
DialogueStateTracker.reject_action
reject_action
Notify active loop that it was rejected.
[ "Notify", "active", "loop", "that", "it", "was", "rejected." ]
def reject_action(self, action_name: Text) -> None: if self.active_loop is not None and action_name == self.active_loop_name: self.active_loop.rejected = True
['def', 'reject_action(self,', 'action_name:', 'Text)', '->', 'None:', 'if', 'self.active_loop', 'is', 'not', 'None', 'and', 'action_name', '==', 'self.active_loop_name:', 'self.active_loop.rejected', '=', 'True']
837,529
google-research/batch_rl
fixed_replay_buffer.py
FixedReplayBuffer.load_single_buffer
load_single_buffer
Load a single replay buffer.
[ "Load", "a", "single", "replay", "buffer." ]
def load_single_buffer(self, suffix): replay_buffer = self._load_buffer(suffix) if replay_buffer is not None: self._replay_buffers = [replay_buffer] self.add_count = replay_buffer.add_count self._num_replay_buffers = 1 self._loaded_buffers = True
['def', 'load_single_buffer(self,', 'suffix):', 'replay_buffer', '=', 'self._load_buffer(suffix)', 'if', 'replay_buffer', 'is', 'not', 'None:', 'self._replay_buffers', '=', '[replay_buffer]', 'self.add_count', '=', 'replay_buffer.add_count', 'self._num_replay_buffers', '=', '1', 'self._loaded_buffers', '=', 'True']
105,912
gyh75520/Relational_DRL
dataset.py
ExpertDataset.log_info
log_info
Log the information of the dataset.
[ "Log", "the", "information", "of", "the", "dataset." ]
def log_info(self): logger.log('Total trajectories: {}'.format(self.num_traj)) logger.log('Total transitions: {}'.format(self.num_transition)) logger.log('Average returns: {}'.format(self.avg_ret)) logger.log('Std for returns: {}'.format(self.std_ret))
['def', 'log_info(self):', "logger.log('Total", 'trajectories:', "{}'.format(self.num_traj))", "logger.log('Total", 'transitions:', "{}'.format(self.num_transition))", "logger.log('Average", 'returns:', "{}'.format(self.avg_ret))", "logger.log('Std", 'for', 'returns:', "{}'.format(self.std_ret))"]
839,421
airbus/scikit-decide
scheduling_domains.py
SchedulingDomain.update_complete_dummy_tasks_simulation
update_complete_dummy_tasks_simulation
In a simulated scheduling environment, update the status of newly started tasks whose duration is 0 from ongoing to complete.
[ "In", "a", "simulated", "scheduling", "environment,", "update", "the", "status", "of", "newly", "started", "tasks", "whose", "duration", "is", "0", "from", "ongoing", "to", "complete." ]
def update_complete_dummy_tasks_simulation(self, state: State, action: SchedulingAction): return self.update_complete_dummy_tasks(state, action)
['def', 'update_complete_dummy_tasks_simulation(self,', 'state:', 'State,', 'action:', 'SchedulingAction):', 'return', 'self.update_complete_dummy_tasks(state,', 'action)']
847,865
google-research/scenic
dataset_utils.py
crop_and_resize_image_tong
crop_and_resize_image_tong
Crops and resizes the images in the given sequence of images.
[ "Crops", "and", "resizes", "the", "images", "in", "the", "given", "sequence", "of", "images." ]
def crop_and_resize_image_tong(frames: tf.Tensor, resized_size: tuple[int, int]=(224, 224), scales: tf.Tensor=tf.constant([1, 0.875, 0.75, 0.66])) -> tf.Tensor: shape = tf.shape(input=frames) timesteps = shape[0] image_h = shape[1] image_w = shape[2] channels = shape[3] (crop_h, crop_w, offset_h...
['def', 'crop_and_resize_image_tong(frames:', 'tf.Tensor,', 'resized_size:', 'tuple[int,', 'int]=(224,', '224),', 'scales:', 'tf.Tensor=tf.constant([1,', '0.875,', '0.75,', '0.66]))', '->', 'tf.Tensor:', 'shape', '=', 'tf.shape(input=frames)', 'timesteps', '=', 'shape[0]', 'image_h', '=', 'shape[1]', 'image_w', '=', 's...
847,118
rifqind/Agent-Programs-3KS1
document.py
Document.empty_line_count_at_the_end
empty_line_count_at_the_end
Return number of empty lines at the end of the document.
[ "Return", "number", "of", "empty", "lines", "at", "the", "end", "of", "the", "document." ]
def empty_line_count_at_the_end(self): count = 0 for line in self.lines[::-1]: if not line or line.isspace(): count += 1 else: break return count
['def', 'empty_line_count_at_the_end(self):', 'count', '=', '0', 'for', 'line', 'in', 'self.lines[::-1]:', 'if', 'not', 'line', 'or', 'line.isspace():', 'count', '+=', '1', 'else:', 'break', 'return', 'count']
44,989
ShuLiu1993/PANet
json_dataset.py
JsonDataset.valid_cached_keys
valid_cached_keys
Can load following key-ed values from the cached roidb file 'image'(image path) and 'flipped' values are already filled on _prep_roidb_entry, so we don't need to overwrite it again.
[ "Can", "load", "following", "key-ed", "values", "from", "the", "cached", "roidb", "file", "'image'(image", "path)", "and", "'flipped'", "values", "are", "already", "filled", "on", "_prep_roidb_entry,", "so", "we", "don't", "need", "to", "overwrite", "it", "again...
def valid_cached_keys(self): keys = ['boxes', 'segms', 'gt_classes', 'seg_areas', 'gt_overlaps', 'is_crowd', 'box_to_gt_ind_map'] if self.keypoints is not None: keys += ['gt_keypoints', 'has_visible_keypoints'] return keys
['def', 'valid_cached_keys(self):', 'keys', '=', "['boxes',", "'segms',", "'gt_classes',", "'seg_areas',", "'gt_overlaps',", "'is_crowd',", "'box_to_gt_ind_map']", 'if', 'self.keypoints', 'is', 'not', 'None:', 'keys', '+=', "['gt_keypoints',", "'has_visible_keypoints']", 'return', 'keys']
778,694
dongminlee94/deep_rl
a2c.py
Agent.select_action
select_action
Select an action from the set of available actions.
[ "Select", "an", "action", "from", "the", "set", "of", "available", "actions." ]
def select_action(self, obs): (action, _, log_pi) = self.policy(obs) v = self.vf(obs) self.transition.extend([log_pi, v]) return action.detach().cpu().numpy()
['def', 'select_action(self,', 'obs):', '(action,', '_,', 'log_pi)', '=', 'self.policy(obs)', 'v', '=', 'self.vf(obs)', 'self.transition.extend([log_pi,', 'v])', 'return', 'action.detach().cpu().numpy()']
183,588
Media-Smart/vedadet
colorspace.py
gray2rgb
gray2rgb
Convert a grayscale image to RGB image.
[ "Convert", "a", "grayscale", "image", "to", "RGB", "image." ]
def gray2rgb(img): img = img[..., None] if img.ndim == 2 else img out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) return out_img
['def', 'gray2rgb(img):', 'img', '=', 'img[...,', 'None]', 'if', 'img.ndim', '==', '2', 'else', 'img', 'out_img', '=', 'cv2.cvtColor(img,', 'cv2.COLOR_GRAY2RGB)', 'return', 'out_img']
931,073
facebookresearch/detectron2
rotated_fast_rcnn.py
fast_rcnn_inference_rotated
fast_rcnn_inference_rotated
Call `fast_rcnn_inference_single_image_rotated` for all images.
[ "Call", "`fast_rcnn_inference_single_image_rotated`", "for", "all", "images." ]
def fast_rcnn_inference_rotated(boxes, scores, image_shapes, score_thresh, nms_thresh, topk_per_image): result_per_image = [fast_rcnn_inference_single_image_rotated(boxes_per_image, scores_per_image, image_shape, score_thresh, nms_thresh, topk_per_image) for (scores_per_image, boxes_per_image, image_shape) in zip(s...
['def', 'fast_rcnn_inference_rotated(boxes,', 'scores,', 'image_shapes,', 'score_thresh,', 'nms_thresh,', 'topk_per_image):', 'result_per_image', '=', '[fast_rcnn_inference_single_image_rotated(boxes_per_image,', 'scores_per_image,', 'image_shape,', 'score_thresh,', 'nms_thresh,', 'topk_per_image)', 'for', '(scores_per...
549,286
atulkum/object_detection
loader.py
RoIDataLoader.enqueue_blobs
enqueue_blobs
Put a mini-batch on a BlobsQueue.
[ "Put", "a", "mini-batch", "on", "a", "BlobsQueue." ]
def enqueue_blobs(self, gpu_id, blob_names, blobs): assert len(blob_names) == len(blobs) t = time.time() dev = c2_utils.CudaDevice(gpu_id) queue_name = 'gpu_{}/{}'.format(gpu_id, self._blobs_queue_name) blob_names = ['gpu_{}/{}'.format(gpu_id, b) for b in blob_names] for (blob_name, blob) in zip...
['def', 'enqueue_blobs(self,', 'gpu_id,', 'blob_names,', 'blobs):', 'assert', 'len(blob_names)', '==', 'len(blobs)', 't', '=', 'time.time()', 'dev', '=', 'c2_utils.CudaDevice(gpu_id)', 'queue_name', '=', "'gpu_{}/{}'.format(gpu_id,", 'self._blobs_queue_name)', 'blob_names', '=', "['gpu_{}/{}'.format(gpu_id,", 'b)', 'fo...
772,988
suarez12138/AI-Reversi_IMP_TextDichotomy
texmanager.py
TexManager.get_custom_preamble
get_custom_preamble
Return a string containing user additions to the tex preamble.
[ "Return", "a", "string", "containing", "user", "additions", "to", "the", "tex", "preamble." ]
def get_custom_preamble(self): return rcParams['text.latex.preamble']
['def', 'get_custom_preamble(self):', 'return', "rcParams['text.latex.preamble']"]
96,769
Shuijing725/CrowdNav_DSRNN
srnn_model.py
EdgeAttention.forward
forward
Forward pass for the model params: h_temporal : Hidden state of the temporal edgeRNN h_spatials : Hidden states of all spatial edgeRNNs connected to the node.
[ "Forward", "pass", "for", "the", "model", "params:", "h_temporal", ":", "Hidden", "state", "of", "the", "temporal", "edgeRNN", "h_spatials", ":", "Hidden", "states", "of", "all", "spatial", "edgeRNNs", "connected", "to", "the", "node." ]
def forward(self, h_temporal, h_spatials): self.human_num = h_spatials.size()[2] // self.agent_num (weighted_value_list, attn_list) = ([], []) for i in range(self.num_attention_head): temporal_embed = self.temporal_edge_layer[i](h_temporal) spatial_embed = self.spatial_edge_layer[i](h_spatia...
['def', 'forward(self,', 'h_temporal,', 'h_spatials):', 'self.human_num', '=', 'h_spatials.size()[2]', '//', 'self.agent_num', '(weighted_value_list,', 'attn_list)', '=', '([],', '[])', 'for', 'i', 'in', 'range(self.num_attention_head):', 'temporal_embed', '=', 'self.temporal_edge_layer[i](h_temporal)', 'spatial_embed'...
506,309
apeterswu/RL4NMT
transformer_vae.py
nearest
nearest
Find the nearest means to elements in x.
[ "Find", "the", "nearest", "means", "to", "elements", "in", "x." ]
def nearest(x, means, hparams): (x, means) = (tf.stop_gradient(x), tf.stop_gradient(means)) means = tf.nn.l2_normalize(means, dim=1) x_flat = tf.reshape(x, [-1, hparams.hidden_size]) dist = -tf.matmul(x_flat, means, transpose_b=True) (_, nearest_idx) = tf.nn.top_k(-dist, k=1) nearest_hot = tf.on...
['def', 'nearest(x,', 'means,', 'hparams):', '(x,', 'means)', '=', '(tf.stop_gradient(x),', 'tf.stop_gradient(means))', 'means', '=', 'tf.nn.l2_normalize(means,', 'dim=1)', 'x_flat', '=', 'tf.reshape(x,', '[-1,', 'hparams.hidden_size])', 'dist', '=', '-tf.matmul(x_flat,', 'means,', 'transpose_b=True)', '(_,', 'nearest_...
331,699
openvinotoolkit/training_extensions
annotation.py
AnnotationSceneEntity.append_annotations
append_annotations
Adds a list of annotations to the annotation scene.
[ "Adds", "a", "list", "of", "annotations", "to", "the", "annotation", "scene." ]
def append_annotations(self, annotations: List[Annotation]) -> None: self.annotations.extend(annotations)
['def', 'append_annotations(self,', 'annotations:', 'List[Annotation])', '->', 'None:', 'self.annotations.extend(annotations)']
918,472
tobegit3hub/deep_image_model
event_multiplexer.py
EventMultiplexer.RunPaths
RunPaths
Returns a dict mapping run names to event file paths.
[ "Returns", "a", "dict", "mapping", "run", "names", "to", "event", "file", "paths." ]
def RunPaths(self): return self._paths
['def', 'RunPaths(self):', 'return', 'self._paths']
183,233
rudranil723/mini-main
fields.py
Field.widget_attrs
widget_attrs
Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field.
[ "Given", "a", "Widget", "instance", "(*not*", "a", "Widget", "class),", "return", "a", "dictionary", "of", "any", "HTML", "attributes", "that", "should", "be", "added", "to", "the", "Widget,", "based", "on", "this", "Field." ]
def widget_attrs(self, widget): return {}
['def', 'widget_attrs(self,', 'widget):', 'return', '{}']
316,217
bruinxiong/EG3D-pytorch
util.py
Logger.write
write
Write text to stdout (and a file) and optionally flush.
[ "Write", "text", "to", "stdout", "(and", "a", "file)", "and", "optionally", "flush." ]
def write(self, text: Union[str, bytes]) -> None: if isinstance(text, bytes): text = text.decode() if len(text) == 0: return if self.file is not None: self.file.write(text) self.stdout.write(text) if self.should_flush: self.flush()
['def', 'write(self,', 'text:', 'Union[str,', 'bytes])', '->', 'None:', 'if', 'isinstance(text,', 'bytes):', 'text', '=', 'text.decode()', 'if', 'len(text)', '==', '0:', 'return', 'if', 'self.file', 'is', 'not', 'None:', 'self.file.write(text)', 'self.stdout.write(text)', 'if', 'self.should_flush:', 'self.flush()']
561,208
ilya16/MultINN
encoder.py
Encoder.num_layers
num_layers
int: The number of layers in the Encoder.
[ "int:", "The", "number", "of", "layers", "in", "the", "Encoder." ]
def num_layers(self): return len(self._num_hidden)
['def', 'num_layers(self):', 'return', 'len(self._num_hidden)']
644,225