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
deepmind/dm_control
renderer.py
SceneCamera.is_initialized
is_initialized
Returns True if camera is properly initialized.
[ "Returns", "True", "if", "camera", "is", "properly", "initialized." ]
def is_initialized(self): if not self._scene: return False frustum_near = self._scene.camera[0].frustum_near frustum_far = self._scene.camera[0].frustum_far return frustum_near > 0 and frustum_near < frustum_far
['def', 'is_initialized(self):', 'if', 'not', 'self._scene:', 'return', 'False', 'frustum_near', '=', 'self._scene.camera[0].frustum_near', 'frustum_far', '=', 'self._scene.camera[0].frustum_far', 'return', 'frustum_near', '>', '0', 'and', 'frustum_near', '<', 'frustum_far']
166,582
rifqind/Agent-Programs-3KS1
test_application.py
test_unicode_cwd
test_unicode_cwd
Check that IPython starts with non-ascii characters in the path.
[ "Check", "that", "IPython", "starts", "with", "non-ascii", "characters", "in", "the", "path." ]
def test_unicode_cwd(): wd = tempfile.mkdtemp(suffix=u'âÂ\x82¬') old_wd = os.getcwd() os.chdir(wd) try: app = BaseIPythonApplication() app.init_profile_dir() app.init_config_files() app.load_config_file(suppress_errors=False) finally: os.chdir(old_wd)
['def', 'test_unicode_cwd():', 'wd', '=', "tempfile.mkdtemp(suffix=u'âÂ\\x82¬')", 'old_wd', '=', 'os.getcwd()', 'os.chdir(wd)', 'try:', 'app', '=', 'BaseIPythonApplication()', 'app.init_profile_dir()', 'app.init_config_files()', 'app.load_config_file(suppress_errors=False)', 'finally:', 'os.chdir(old_wd)']
41,358
cbaziotis/seq3
helpers.py
sequence_mask
sequence_mask
Creates a boolean mask from sequence lengths.
[ "Creates", "a", "boolean", "mask", "from", "sequence", "lengths." ]
def sequence_mask(lengths, max_len=None): batch_size = lengths.numel() max_len = max_len or lengths.max() return torch.arange(0, max_len, device=lengths.device).type_as(lengths).unsqueeze(0).expand(batch_size, max_len).lt(lengths.unsqueeze(1))
['def', 'sequence_mask(lengths,', 'max_len=None):', 'batch_size', '=', 'lengths.numel()', 'max_len', '=', 'max_len', 'or', 'lengths.max()', 'return', 'torch.arange(0,', 'max_len,', 'device=lengths.device).type_as(lengths).unsqueeze(0).expand(batch_size,', 'max_len).lt(lengths.unsqueeze(1))']
876,498
matsu0228/nlp-jp
routing.py
Matcher.reverse
reverse
Reconstructs full url from matcher instance and additional arguments.
[ "Reconstructs", "full", "url", "from", "matcher", "instance", "and", "additional", "arguments." ]
def reverse(self, *args): return None
['def', 'reverse(self,', '*args):', 'return', 'None']
807,347
weimin17/Object-Detection_HelmetDetection
bulk_component.py
extract_fixed_feature_ids
extract_fixed_feature_ids
Extracts fixed feature IDs.
[ "Extracts", "fixed", "feature", "IDs." ]
def extract_fixed_feature_ids(comp, state, stride): num_channels = len(comp.spec.fixed_feature) if not num_channels: return (state.handle, []) for feature_spec in comp.spec.fixed_feature: check.Eq(feature_spec.size, 1, 'All features must have size=1') check.Lt(feature_spec.embedding_...
['def', 'extract_fixed_feature_ids(comp,', 'state,', 'stride):', 'num_channels', '=', 'len(comp.spec.fixed_feature)', 'if', 'not', 'num_channels:', 'return', '(state.handle,', '[])', 'for', 'feature_spec', 'in', 'comp.spec.fixed_feature:', 'check.Eq(feature_spec.size,', '1,', "'All", 'features', 'must', 'have', "size=1...
760,055
lvwerra/trl
test_ppo_trainer.py
PPOTrainerTester.test_ppo_step_rewards_shape
test_ppo_step_rewards_shape
Test if the rewards shape is correct by asserting that if a wrong reward shape is passed, we get a value error.
[ "Test", "if", "the", "rewards", "shape", "is", "correct", "by", "asserting", "that", "if", "a", "wrong", "reward", "shape", "is", "passed,", "we", "get", "a", "value", "error." ]
def test_ppo_step_rewards_shape(self): dummy_dataset = self._init_dummy_dataset() ppo_trainer = PPOTrainer(config=self.ppo_config, model=self.gpt2_model, ref_model=None, tokenizer=self.gpt2_tokenizer, dataset=dummy_dataset) dummy_dataloader = ppo_trainer.dataloader for (query_tensor, response_tensor) in...
['def', 'test_ppo_step_rewards_shape(self):', 'dummy_dataset', '=', 'self._init_dummy_dataset()', 'ppo_trainer', '=', 'PPOTrainer(config=self.ppo_config,', 'model=self.gpt2_model,', 'ref_model=None,', 'tokenizer=self.gpt2_tokenizer,', 'dataset=dummy_dataset)', 'dummy_dataloader', '=', 'ppo_trainer.dataloader', 'for', '...
425,842
jimtin/Stock_Comparison
demo.py
ClearMixin.marquee
marquee
Blank marquee that returns '' no matter what the input.
[ "Blank", "marquee", "that", "returns", "''", "no", "matter", "what", "the", "input." ]
def marquee(self, txt='', width=78, mark='*'): return ''
['def', 'marquee(self,', "txt='',", 'width=78,', "mark='*'):", 'return', "''"]
385,227
QData/deepWordBug
math2html.py
Label.process
process
Process a label container.
[ "Process", "a", "label", "container." ]
def process(self): key = self.getparameter('name') self.create(' ', key) self.lastnumbered = Label.lastlayout
['def', 'process(self):', 'key', '=', "self.getparameter('name')", "self.create('", "',", 'key)', 'self.lastnumbered', '=', 'Label.lastlayout']
542,560
cheng052/BRNet
builder.py
build_middle_encoder
build_middle_encoder
Build middle level encoder.
[ "Build", "middle", "level", "encoder." ]
def build_middle_encoder(cfg): return build(cfg, MIDDLE_ENCODERS)
['def', 'build_middle_encoder(cfg):', 'return', 'build(cfg,', 'MIDDLE_ENCODERS)']
409,855
open-mmlab/mmtracking
flow.py
flow_warp_feats
flow_warp_feats
Use flow to warp feature map.
[ "Use", "flow", "to", "warp", "feature", "map." ]
def flow_warp_feats(x, flow): assert len(x.shape) == 4 assert len(flow.shape) == 4 and flow.shape[1] == 2 scale_factor = float(x.shape[-1]) / flow.shape[-1] flow = torch.nn.functional.interpolate(flow, scale_factor=scale_factor, mode='bilinear', align_corners=False) flow = flow * scale_factor (H...
['def', 'flow_warp_feats(x,', 'flow):', 'assert', 'len(x.shape)', '==', '4', 'assert', 'len(flow.shape)', '==', '4', 'and', 'flow.shape[1]', '==', '2', 'scale_factor', '=', 'float(x.shape[-1])', '/', 'flow.shape[-1]', 'flow', '=', 'torch.nn.functional.interpolate(flow,', 'scale_factor=scale_factor,', "mode='bilinear',"...
625,695
sktime/sktime
test_window_summarizer.py
test_wrong_column
test_wrong_column
Test mismatch between X column names and target_cols.
[ "Test", "mismatch", "between", "X", "column", "names", "and", "target_cols." ]
def test_wrong_column(): transformer = WindowSummarizer(target_cols=['dummy']) Xt = transformer.fit_transform(X_ll_train) return Xt
['def', 'test_wrong_column():', 'transformer', '=', "WindowSummarizer(target_cols=['dummy'])", 'Xt', '=', 'transformer.fit_transform(X_ll_train)', 'return', 'Xt']
877,928
arshpreetsingh/quantopian-machinelearning
test_iplib.py
test_reset
test_reset
reset must clear most namespaces.
[ "reset", "must", "clear", "most", "namespaces." ]
def test_reset(): ip.reset() nvars_user_ns = len(ip.user_ns) nvars_hidden = len(ip.user_ns_hidden) ip.user_ns['x'] = 1 ip.user_ns['y'] = 1 ip.reset() nt.assert_equal(len(ip.user_ns), nvars_user_ns) nt.assert_equal(len(ip.user_ns_hidden), nvars_hidden)
['def', 'test_reset():', 'ip.reset()', 'nvars_user_ns', '=', 'len(ip.user_ns)', 'nvars_hidden', '=', 'len(ip.user_ns_hidden)', "ip.user_ns['x']", '=', '1', "ip.user_ns['y']", '=', '1', 'ip.reset()', 'nt.assert_equal(len(ip.user_ns),', 'nvars_user_ns)', 'nt.assert_equal(len(ip.user_ns_hidden),', 'nvars_hidden)']
886,658
devashish-patel/webcam-motion-detector
test_process.py
test_arg_split
test_arg_split
Ensure that argument lines are correctly split like in a shell.
[ "Ensure", "that", "argument", "lines", "are", "correctly", "split", "like", "in", "a", "shell." ]
def test_arg_split(): tests = [['hi', ['hi']], [u'hi', [u'hi']], ['hello there', ['hello', 'there']], [u'hǎllo', [u'hǎllo']], ['something "with quotes"', ['something', '"with quotes"']]] for (argstr, argv) in tests: nt.assert_equal(arg_split(argstr), argv)
['def', 'test_arg_split():', 'tests', '=', "[['hi',", "['hi']],", "[u'hi',", "[u'hi']],", "['hello", "there',", "['hello',", "'there']],", "[u'hǎllo',", "[u'hǎllo']],", "['something", '"with', 'quotes"\',', "['something',", '\'"with', 'quotes"\']]]', 'for', '(argstr,', 'argv)', 'in', 'tests:', 'nt.assert_equal(arg_spli...
979,544
ago109/predictive-forward-forward
sim_train.py
plot_img_grid
plot_img_grid
Visualizes a matrix of vector patterns in the form of an image grid plot.
[ "Visualizes", "a", "matrix", "of", "vector", "patterns", "in", "the", "form", "of", "an", "image", "grid", "plot." ]
def plot_img_grid(samples, fname, nx, ny, px, py, plt, rotNeg90=False): px_dim = px py_dim = py canvas = np.empty((px_dim * nx, py_dim * ny)) ptr = 0 for i in range(0, nx, 1): for j in range(0, ny, 1): xs = np.expand_dims(samples[ptr, :], axis=0) xs = xs[0].reshape(px...
['def', 'plot_img_grid(samples,', 'fname,', 'nx,', 'ny,', 'px,', 'py,', 'plt,', 'rotNeg90=False):', 'px_dim', '=', 'px', 'py_dim', '=', 'py', 'canvas', '=', 'np.empty((px_dim', '*', 'nx,', 'py_dim', '*', 'ny))', 'ptr', '=', '0', 'for', 'i', 'in', 'range(0,', 'nx,', '1):', 'for', 'j', 'in', 'range(0,', 'ny,', '1):', 'xs...
305,930
intel/neural-compressor
transform.py
read_squad_examples
read_squad_examples
Read a SQuAD json file into a list of SquadExample.
[ "Read", "a", "SQuAD", "json", "file", "into", "a", "list", "of", "SquadExample." ]
def read_squad_examples(input_file): import json with tf.io.gfile.GFile(input_file, 'r') as reader: input_data = json.load(reader)['data'] def is_whitespace(c): if c == ' ' or c == '\t' or c == '\r' or (c == '\n') or (ord(c) == 8239): return True return False example...
['def', 'read_squad_examples(input_file):', 'import', 'json', 'with', 'tf.io.gfile.GFile(input_file,', "'r')", 'as', 'reader:', 'input_data', '=', "json.load(reader)['data']", 'def', 'is_whitespace(c):', 'if', 'c', '==', "'", "'", 'or', 'c', '==', "'\\t'", 'or', 'c', '==', "'\\r'", 'or', '(c', '==', "'\\n')", 'or', '(o...
738,496
ludwig-ai/ludwig
strings_utils.py
values_are_pandas_numbers
values_are_pandas_numbers
Returns True if values would be read by pandas as dtype float or int.
[ "Returns", "True", "if", "values", "would", "be", "read", "by", "pandas", "as", "dtype", "float", "or", "int." ]
def values_are_pandas_numbers(values: List[str]): for v in values: try: float(v) except ValueError: return False return True
['def', 'values_are_pandas_numbers(values:', 'List[str]):', 'for', 'v', 'in', 'values:', 'try:', 'float(v)', 'except', 'ValueError:', 'return', 'False', 'return', 'True']
617,150
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
build_src.py
subst_vars
subst_vars
Substitute any occurrence of @foo@ by d['foo'] from source file into target.
[ "Substitute", "any", "occurrence", "of", "@foo@", "by", "d['foo']", "from", "source", "file", "into", "target." ]
def subst_vars(target, source, d): var = re.compile('@([a-zA-Z_]+)@') fs = open(source, 'r') try: ft = open(target, 'w') try: for l in fs: m = var.search(l) if m: ft.write(l.replace('@%s@' % m.group(1), d[m.group(1)])) ...
['def', 'subst_vars(target,', 'source,', 'd):', 'var', '=', "re.compile('@([a-zA-Z_]+)@')", 'fs', '=', 'open(source,', "'r')", 'try:', 'ft', '=', 'open(target,', "'w')", 'try:', 'for', 'l', 'in', 'fs:', 'm', '=', 'var.search(l)', 'if', 'm:', "ft.write(l.replace('@%s@'", '%', 'm.group(1),', 'd[m.group(1)]))', 'else:', '...
966,639
Levantespot/UDA_for_RS
uda_decorator.py
UDADecorator.simple_test
simple_test
Simple test with single image.
[ "Simple", "test", "with", "single", "image." ]
def simple_test(self, img, img_meta, rescale=True): return self.get_model().simple_test(img, img_meta, rescale)
['def', 'simple_test(self,', 'img,', 'img_meta,', 'rescale=True):', 'return', 'self.get_model().simple_test(img,', 'img_meta,', 'rescale)']
947,413
bhateharsh/computer_vision
model_lib_test.py
ModelLibTest.test_model_fn_in_predict_mode
test_model_fn_in_predict_mode
Tests the model function in PREDICT mode.
[ "Tests", "the", "model", "function", "in", "PREDICT", "mode." ]
def test_model_fn_in_predict_mode(self): configs = _get_configs_for_model(MODEL_NAME_FOR_TEST) self._assert_model_fn_for_predict(configs)
['def', 'test_model_fn_in_predict_mode(self):', 'configs', '=', '_get_configs_for_model(MODEL_NAME_FOR_TEST)', 'self._assert_model_fn_for_predict(configs)']
503,717
danamyu/hedgehog_detector
pg_train.py
AsyncTrainer.maybe_save_best_model
maybe_save_best_model
Check if this model got the highest reward and save to disk if so.
[ "Check", "if", "this", "model", "got", "the", "highest", "reward", "and", "save", "to", "disk", "if", "so." ]
def maybe_save_best_model(self, session, saver, checkpoint_file): if self.is_chief and session.run(self.is_best_model): logging.info('Saving best model to "%s"', checkpoint_file) saver.save(session, checkpoint_file) session.run(self.reset_is_best_model)
['def', 'maybe_save_best_model(self,', 'session,', 'saver,', 'checkpoint_file):', 'if', 'self.is_chief', 'and', 'session.run(self.is_best_model):', "logging.info('Saving", 'best', 'model', 'to', '"%s"\',', 'checkpoint_file)', 'saver.save(session,', 'checkpoint_file)', 'session.run(self.reset_is_best_model)']
589,379
caiiiac/Machine-Learning-with-Python
dviread.py
Dvi.close
close
Close the underlying file if it is open.
[ "Close", "the", "underlying", "file", "if", "it", "is", "open." ]
def close(self): if not self.file.closed: self.file.close()
['def', 'close(self):', 'if', 'not', 'self.file.closed:', 'self.file.close()']
715,442
KleinYuan/tf-object-detection
coco_evaluation_test.py
CocoDetectionEvaluationTest.testRejectionOnDuplicateGroundtruth
testRejectionOnDuplicateGroundtruth
Tests that groundtruth cannot be added more than once for an image.
[ "Tests", "that", "groundtruth", "cannot", "be", "added", "more", "than", "once", "for", "an", "image." ]
def testRejectionOnDuplicateGroundtruth(self): categories = [{'id': 1, 'name': 'cat'}, {'id': 2, 'name': 'dog'}, {'id': 3, 'name': 'elephant'}] coco_evaluator = coco_evaluation.CocoDetectionEvaluator(categories) image_key1 = 'img1' groundtruth_boxes1 = np.array([[0, 0, 1, 1], [0, 0, 2, 2], [0, 0, 3, 3]]...
['def', 'testRejectionOnDuplicateGroundtruth(self):', 'categories', '=', "[{'id':", '1,', "'name':", "'cat'},", "{'id':", '2,', "'name':", "'dog'},", "{'id':", '3,', "'name':", "'elephant'}]", 'coco_evaluator', '=', 'coco_evaluation.CocoDetectionEvaluator(categories)', 'image_key1', '=', "'img1'", 'groundtruth_boxes1',...
914,874
sanujkul/Artificial-Intelligence
search.py
Graph.connect1
connect1
Add a link from A to B of given distance, in one direction only.
[ "Add", "a", "link", "from", "A", "to", "B", "of", "given", "distance,", "in", "one", "direction", "only." ]
def connect1(self, A, B, distance): self.graph_dict.setdefault(A, {})[B] = distance
['def', 'connect1(self,', 'A,', 'B,', 'distance):', 'self.graph_dict.setdefault(A,', '{})[B]', '=', 'distance']
118,317
calico/basenji
seqnn.py
SeqNN.build_slice
build_slice
Slice and/or sum across tasks, in graph.
[ "Slice", "and/or", "sum", "across", "tasks,", "in", "graph." ]
def build_slice(self, target_slice=None, target_sum=False): if target_slice is not None or target_sum: sequence = tf.keras.Input(shape=(self.seq_length, 4), name='sequence') predictions = self.model(sequence) if target_slice is None: predictions_slice = predictions else: ...
['def', 'build_slice(self,', 'target_slice=None,', 'target_sum=False):', 'if', 'target_slice', 'is', 'not', 'None', 'or', 'target_sum:', 'sequence', '=', 'tf.keras.Input(shape=(self.seq_length,', '4),', "name='sequence')", 'predictions', '=', 'self.model(sequence)', 'if', 'target_slice', 'is', 'None:', 'predictions_sli...
94,597
vishalprabha/Image-Classification-Transfer-Learning-with-Inception-v3
retrain.py
should_distort_images
should_distort_images
Whether any distortions are enabled, from the input flags.
[ "Whether", "any", "distortions", "are", "enabled,", "from", "the", "input", "flags." ]
def should_distort_images(flip_left_right, random_crop, random_scale, random_brightness): return flip_left_right or random_crop != 0 or random_scale != 0 or (random_brightness != 0)
['def', 'should_distort_images(flip_left_right,', 'random_crop,', 'random_scale,', 'random_brightness):', 'return', 'flip_left_right', 'or', 'random_crop', '!=', '0', 'or', 'random_scale', '!=', '0', 'or', '(random_brightness', '!=', '0)']
599,092
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_102a.py
create_grid
create_grid
Create a grid of a given `size`.
[ "Create", "a", "grid", "of", "a", "given", "`size`." ]
def create_grid(size): (H, W) = size if is_tuple(size) else (size, size) grid = FloatTensor(H, W, 2) linear_points = torch.linspace(-1 + 1 / W, 1 - 1 / W, W) if W > 1 else tensor([0.0]) grid[:, :, 1] = torch.ger(torch.ones(H), linear_points).expand_as(grid[:, :, 0]) linear_points = torch.linspace(-1...
['def', 'create_grid(size):', '(H,', 'W)', '=', 'size', 'if', 'is_tuple(size)', 'else', '(size,', 'size)', 'grid', '=', 'FloatTensor(H,', 'W,', '2)', 'linear_points', '=', 'torch.linspace(-1', '+', '1', '/', 'W,', '1', '-', '1', '/', 'W,', 'W)', 'if', 'W', '>', '1', 'else', 'tensor([0.0])', 'grid[:,', ':,', '1]', '=', ...
81,895
AdroitAnandAI/Computer-Vision-Math-Magic-vs-AI
searchImgObject.py
match
match
Here we are using correlation diff because we are searching objects.
[ "Here", "we", "are", "using", "correlation", "diff", "because", "we", "are", "searching", "objects." ]
def match(base, current): res = cdist(base, current, metric='correlation') return np.nansum(res)
['def', 'match(base,', 'current):', 'res', '=', 'cdist(base,', 'current,', "metric='correlation')", 'return', 'np.nansum(res)']
470,302
rlpy/rlpy
IndependentDiscretizationCompactBinary.py
IndependentDiscretizationCompactBinary.getDimNumber
getDimNumber
Returns the dimension number corresponding to feature ``f``.
[ "Returns", "the", "dimension", "number", "corresponding", "to", "feature", "``f``." ]
def getDimNumber(self, f): dim = np.searchsorted(self.maxFeatureIDperDimension, f) return dim
['def', 'getDimNumber(self,', 'f):', 'dim', '=', 'np.searchsorted(self.maxFeatureIDperDimension,', 'f)', 'return', 'dim']
333,878
sek788432/Waymo-2D-Object-Detection
image_classification.py
image_classification_imagenet_resnetrs
image_classification_imagenet_resnetrs
Image classification on imagenet with resnet-rs.
[ "Image", "classification", "on", "imagenet", "with", "resnet-rs." ]
def image_classification_imagenet_resnetrs() -> cfg.ExperimentConfig: train_batch_size = 4096 eval_batch_size = 4096 steps_per_epoch = IMAGENET_TRAIN_EXAMPLES // train_batch_size config = cfg.ExperimentConfig(task=ImageClassificationTask(model=ImageClassificationModel(num_classes=1001, input_size=[160, ...
['def', 'image_classification_imagenet_resnetrs()', '->', 'cfg.ExperimentConfig:', 'train_batch_size', '=', '4096', 'eval_batch_size', '=', '4096', 'steps_per_epoch', '=', 'IMAGENET_TRAIN_EXAMPLES', '//', 'train_batch_size', 'config', '=', 'cfg.ExperimentConfig(task=ImageClassificationTask(model=ImageClassificationMode...
973,018
ArdaGunay99/Key_Detection_Unsupervised_Learning
scale.py
ScaleBase.set_default_locators_and_formatters
set_default_locators_and_formatters
Set the locators and formatters of *axis* to instances suitable for this scale.
[ "Set", "the", "locators", "and", "formatters", "of", "*axis*", "to", "instances", "suitable", "for", "this", "scale." ]
def set_default_locators_and_formatters(self, axis): raise NotImplementedError()
['def', 'set_default_locators_and_formatters(self,', 'axis):', 'raise', 'NotImplementedError()']
257,255
open-mmlab/mmdetection3d
kitti_metric.py
KittiMetric.bbox2result_kitti
bbox2result_kitti
Convert 3D detection results to kitti format for evaluation and test submission.
[ "Convert", "3D", "detection", "results", "to", "kitti", "format", "for", "evaluation", "and", "test", "submission." ]
def bbox2result_kitti(self, net_outputs: List[dict], sample_idx_list: List[int], class_names: List[str], pklfile_prefix: Optional[str]=None, submission_prefix: Optional[str]=None) -> List[dict]: assert len(net_outputs) == len(self.data_infos), 'invalid list length of network outputs' if submission_prefix is not...
['def', 'bbox2result_kitti(self,', 'net_outputs:', 'List[dict],', 'sample_idx_list:', 'List[int],', 'class_names:', 'List[str],', 'pklfile_prefix:', 'Optional[str]=None,', 'submission_prefix:', 'Optional[str]=None)', '->', 'List[dict]:', 'assert', 'len(net_outputs)', '==', 'len(self.data_infos),', "'invalid", 'list', '...
631,802
nicknochnack/RealTimeSignLanguageTFJS
anchor_generator.py
maybe_map_structure_for_anchor
maybe_map_structure_for_anchor
broadcast the params to match anchor_sizes.
[ "broadcast", "the", "params", "to", "match", "anchor_sizes." ]
def maybe_map_structure_for_anchor(params, anchor_sizes): if all((isinstance(param, (int, float)) for param in params)): if isinstance(anchor_sizes, (tuple, list)): return [params] * len(anchor_sizes) elif isinstance(anchor_sizes, dict): return tf.nest.map_structure(lambda _:...
['def', 'maybe_map_structure_for_anchor(params,', 'anchor_sizes):', 'if', 'all((isinstance(param,', '(int,', 'float))', 'for', 'param', 'in', 'params)):', 'if', 'isinstance(anchor_sizes,', '(tuple,', 'list)):', 'return', '[params]', '*', 'len(anchor_sizes)', 'elif', 'isinstance(anchor_sizes,', 'dict):', 'return', 'tf.n...
851,244
SapienzaNLP/xl-amr
predictor.py
Predictor.dump_line
dump_line
If you don't want your outputs in JSON-lines format you can override this function to output them differently.
[ "If", "you", "don't", "want", "your", "outputs", "in", "JSON-lines", "format", "you", "can", "override", "this", "function", "to", "output", "them", "differently." ]
def dump_line(self, outputs: JsonDict) -> str: return json.dumps(outputs) + '\n'
['def', 'dump_line(self,', 'outputs:', 'JsonDict)', '->', 'str:', 'return', 'json.dumps(outputs)', '+', "'\\n'"]
968,623
ITZ-ZAID/AI
cnf_transformation.py
move_not_inward
move_not_inward
Moves the '¬' operator inward and returns the given formula transformed.
[ "Moves", "the", "'¬'", "operator", "inward", "and", "returns", "the", "given", "formula", "transformed." ]
def move_not_inward(f): inside = f.child if isinstance(inside, Atom) or isinstance(inside, Not): return ~inside inside.lchild = ~inside.lchild inside.rchild = ~inside.rchild if inside.op == 'âÂ\x88§': inside.op = 'âÂ\x88¨' elif inside.op == 'âÂ\x88¨': inside.op = 'Ã...
['def', 'move_not_inward(f):', 'inside', '=', 'f.child', 'if', 'isinstance(inside,', 'Atom)', 'or', 'isinstance(inside,', 'Not):', 'return', '~inside', 'inside.lchild', '=', '~inside.lchild', 'inside.rchild', '=', '~inside.rchild', 'if', 'inside.op', '==', "'âÂ\\x88§':", 'inside.op', '=', "'âÂ\\x88¨'", 'elif', 'ins...
69,414
fcjian/TOOD
cascade_rcnn.py
CascadeRCNN.show_result
show_result
Show prediction results of the detector.
[ "Show", "prediction", "results", "of", "the", "detector." ]
def show_result(self, data, result, **kwargs): if self.with_mask: (ms_bbox_result, ms_segm_result) = result if isinstance(ms_bbox_result, dict): result = (ms_bbox_result['ensemble'], ms_segm_result['ensemble']) elif isinstance(result, dict): result = result['ensemble'] re...
['def', 'show_result(self,', 'data,', 'result,', '**kwargs):', 'if', 'self.with_mask:', '(ms_bbox_result,', 'ms_segm_result)', '=', 'result', 'if', 'isinstance(ms_bbox_result,', 'dict):', 'result', '=', "(ms_bbox_result['ensemble'],", "ms_segm_result['ensemble'])", 'elif', 'isinstance(result,', 'dict):', 'result', '=',...
902,150
ldkong1205/LaserMix
vis_utils.py
to_depth_mode
to_depth_mode
Convert points and bboxes to Depth Coord and Depth Box mode.
[ "Convert", "points", "and", "bboxes", "to", "Depth", "Coord", "and", "Depth", "Box", "mode." ]
def to_depth_mode(points: np.ndarray, bboxes: BaseInstance3DBoxes) -> Tuple[np.ndarray, BaseInstance3DBoxes]: if points is not None: points = Coord3DMode.convert_point(points.copy(), Coord3DMode.LIDAR, Coord3DMode.DEPTH) if bboxes is not None: bboxes = Box3DMode.convert(bboxes.clone(), Box3DMode...
['def', 'to_depth_mode(points:', 'np.ndarray,', 'bboxes:', 'BaseInstance3DBoxes)', '->', 'Tuple[np.ndarray,', 'BaseInstance3DBoxes]:', 'if', 'points', 'is', 'not', 'None:', 'points', '=', 'Coord3DMode.convert_point(points.copy(),', 'Coord3DMode.LIDAR,', 'Coord3DMode.DEPTH)', 'if', 'bboxes', 'is', 'not', 'None:', 'bboxe...
624,478
thaines/helit
multiclass.py
MultiModel.getLabels
getLabels
Returns a list of the labels supported.
[ "Returns", "a", "list", "of", "the", "labels", "supported." ]
def getLabels(self): return self.labels
['def', 'getLabels(self):', 'return', 'self.labels']
592,501
enuguru/artificial_intelligence_and_machine_
mcore.py
Matcher.children
children
Returns an (possibly empty) list of the submatchers of this matcher.
[ "Returns", "an", "(possibly", "empty)", "list", "of", "the", "submatchers", "of", "this", "matcher." ]
def children(self): return []
['def', 'children(self):', 'return', '[]']
133,482
guanyuelee/midrae
utils.py
to_png
to_png
Convert a 3D tensor to png.
[ "Convert", "a", "3D", "tensor", "to", "png." ]
def to_png(x): with tf.Graph().as_default(): with tf.Session() as sess_temp: x = tf.constant(x) y = tf.image.encode_png(tf.cast(tf.clip_by_value(tf.round(127.5 + 127.5 * x), 0, 255), tf.uint8), compression=9) return sess_temp.run(y)
['def', 'to_png(x):', 'with', 'tf.Graph().as_default():', 'with', 'tf.Session()', 'as', 'sess_temp:', 'x', '=', 'tf.constant(x)', 'y', '=', 'tf.image.encode_png(tf.cast(tf.clip_by_value(tf.round(127.5', '+', '127.5', '*', 'x),', '0,', '255),', 'tf.uint8),', 'compression=9)', 'return', 'sess_temp.run(y)']
670,318
enuguru/artificial_intelligence_and_machine_learning
lexer.py
Lexer.tokenize
tokenize
Calls tokeniter + tokenize and wraps it in a token stream.
[ "Calls", "tokeniter", "+", "tokenize", "and", "wraps", "it", "in", "a", "token", "stream." ]
def tokenize(self, source, name=None, filename=None, state=None): stream = self.tokeniter(source, name, filename, state) return TokenStream(self.wrap(stream, name, filename), name, filename)
['def', 'tokenize(self,', 'source,', 'name=None,', 'filename=None,', 'state=None):', 'stream', '=', 'self.tokeniter(source,', 'name,', 'filename,', 'state)', 'return', 'TokenStream(self.wrap(stream,', 'name,', 'filename),', 'name,', 'filename)']
129,303
santhoshkolloju/Abstractive-Summarization-With-Transfer-
agent_utils.py
Space.dtype
dtype
Data type of the element.
[ "Data", "type", "of", "the", "element." ]
def dtype(self): return self._dtype
['def', 'dtype(self):', 'return', 'self._dtype']
405,953
rainer85ah/ComputerVision
camera.py
Camera.center
center
Compute and return the camera center.
[ "Compute", "and", "return", "the", "camera", "center." ]
def center(self): if self.c is not None: return self.c else: self.factor() self.c = -dot(self.R.T, self.t) return self.c
['def', 'center(self):', 'if', 'self.c', 'is', 'not', 'None:', 'return', 'self.c', 'else:', 'self.factor()', 'self.c', '=', '-dot(self.R.T,', 'self.t)', 'return', 'self.c']
471,476
NoaCahan/WavenetAutoEncoder
generate.py
decode
decode
Synthesize audio from an array of embeddings.
[ "Synthesize", "audio", "from", "an", "array", "of", "embeddings." ]
def decode(model_path, model_name, encoding, decoder_path, decoder_name, sr=16000, duration=10): if os.path.exists(decoder_path) is False: os.makedirs(decoder_path) with open('./params/model_params.json') as f: model_params = json.load(f) f.close() net = WavenetAutoencoder(**model_params...
['def', 'decode(model_path,', 'model_name,', 'encoding,', 'decoder_path,', 'decoder_name,', 'sr=16000,', 'duration=10):', 'if', 'os.path.exists(decoder_path)', 'is', 'False:', 'os.makedirs(decoder_path)', 'with', "open('./params/model_params.json')", 'as', 'f:', 'model_params', '=', 'json.load(f)', 'f.close()', 'net', ...
972,268
akash-agni/Real-Time-Object-Detection
object_detection_evaluation.py
ObjectDetectionEvaluation.add_single_detected_image_info
add_single_detected_image_info
Add detected result of a single image into the evaluation database.
[ "Add", "detected", "result", "of", "a", "single", "image", "into", "the", "evaluation", "database." ]
def add_single_detected_image_info(self, image_key, detected_boxes, detected_scores, detected_class_labels): if len(detected_boxes) != len(detected_scores) or len(detected_boxes) != len(detected_class_labels): raise ValueError('detected_boxes, detected_scores and detected_class_labels should all have same l...
['def', 'add_single_detected_image_info(self,', 'image_key,', 'detected_boxes,', 'detected_scores,', 'detected_class_labels):', 'if', 'len(detected_boxes)', '!=', 'len(detected_scores)', 'or', 'len(detected_boxes)', '!=', 'len(detected_class_labels):', 'raise', "ValueError('detected_boxes,", 'detected_scores', 'and', '...
850,007
openvinotoolkit/training_extensions
random_augment.py
auto_contrast
auto_contrast
Applies auto contrast to an image.
[ "Applies", "auto", "contrast", "to", "an", "image." ]
def auto_contrast(img, **kwargs): return (PIL.ImageOps.autocontrast(img), None)
['def', 'auto_contrast(img,', '**kwargs):', 'return', '(PIL.ImageOps.autocontrast(img),', 'None)']
903,986
Kvatsx/Artificial-Intelligence-Assignments
image_test.py
ImageModuleTest.testLoadIcon
testLoadIcon
see if we can load the pygame icon.
[ "see", "if", "we", "can", "load", "the", "pygame", "icon." ]
def testLoadIcon(self): f = pygame.pkgdata.getResource('pygame_icon.bmp') self.assertEqual(f.mode, 'rb') surf = pygame.image.load_basic(f) self.assertEqual(surf.get_at((0, 0)), (5, 4, 5, 255)) self.assertEqual(surf.get_height(), 32) self.assertEqual(surf.get_width(), 32)
['def', 'testLoadIcon(self):', 'f', '=', "pygame.pkgdata.getResource('pygame_icon.bmp')", 'self.assertEqual(f.mode,', "'rb')", 'surf', '=', 'pygame.image.load_basic(f)', 'self.assertEqual(surf.get_at((0,', '0)),', '(5,', '4,', '5,', '255))', 'self.assertEqual(surf.get_height(),', '32)', 'self.assertEqual(surf.get_width...
76,411
MinRegret/deluca
_gpc.py
GPC.update
update
Description: update agent internal state.
[ "Description:", "update", "agent", "internal", "state." ]
def update(self, state: jnp.ndarray, u: jnp.ndarray) -> None: noise = state - self.A @ self.state - self.B @ u self.noise_history = jax.ops.index_update(self.noise_history, 0, noise) self.noise_history = jnp.roll(self.noise_history, -1, axis=0) (delta_M, delta_bias) = self.grad(self.M, self.noise_histor...
['def', 'update(self,', 'state:', 'jnp.ndarray,', 'u:', 'jnp.ndarray)', '->', 'None:', 'noise', '=', 'state', '-', 'self.A', '@', 'self.state', '-', 'self.B', '@', 'u', 'self.noise_history', '=', 'jax.ops.index_update(self.noise_history,', '0,', 'noise)', 'self.noise_history', '=', 'jnp.roll(self.noise_history,', '-1,'...
537,851
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
lfads.py
LFADS.train_epoch
train_epoch
Train the model through the entire dataset once.
[ "Train", "the", "model", "through", "the", "entire", "dataset", "once." ]
def train_epoch(self, datasets, batch_size=None, do_save_ckpt=True): ops_to_eval = [self.cost, self.recon_cost, self.kl_cost, self.kl_weight, self.l2_cost, self.l2_weight, self.train_op] collected_op_values = self.run_epoch(datasets, ops_to_eval, kind='train') total_cost = total_recon_cost = total_kl_cost =...
['def', 'train_epoch(self,', 'datasets,', 'batch_size=None,', 'do_save_ckpt=True):', 'ops_to_eval', '=', '[self.cost,', 'self.recon_cost,', 'self.kl_cost,', 'self.kl_weight,', 'self.l2_cost,', 'self.l2_weight,', 'self.train_op]', 'collected_op_values', '=', 'self.run_epoch(datasets,', 'ops_to_eval,', "kind='train')", '...
49,701
tonysy/Deep-Feature-Flow-Segmentation
module.py
Module.output_names
output_names
A list of names for the outputs of this module.
[ "A", "list", "of", "names", "for", "the", "outputs", "of", "this", "module." ]
def output_names(self): return self._output_names
['def', 'output_names(self):', 'return', 'self._output_names']
517,109
fpaupier/tensorflow-serving_sidecar
oid_od_challenge_evaluation_utils.py
build_groundtruth_boxes_dictionary
build_groundtruth_boxes_dictionary
Builds a groundtruth dictionary from groundtruth data in CSV file.
[ "Builds", "a", "groundtruth", "dictionary", "from", "groundtruth", "data", "in", "CSV", "file." ]
def build_groundtruth_boxes_dictionary(data, class_label_map): data_boxes = data[data.ConfidenceImageLabel.isnull()] data_labels = data[data.XMin.isnull()] return {standard_fields.InputDataFields.groundtruth_boxes: data_boxes[['YMin', 'XMin', 'YMax', 'XMax']].as_matrix(), standard_fields.InputDataFields.gro...
['def', 'build_groundtruth_boxes_dictionary(data,', 'class_label_map):', 'data_boxes', '=', 'data[data.ConfidenceImageLabel.isnull()]', 'data_labels', '=', 'data[data.XMin.isnull()]', 'return', '{standard_fields.InputDataFields.groundtruth_boxes:', "data_boxes[['YMin',", "'XMin',", "'YMax',", "'XMax']].as_matrix(),", '...
922,083
ivanmontero/autobot
utils_summarization.py
encode_for_summarization
encode_for_summarization
Encode the story and summary lines, and join them as specified in [1] by using `[SEP] [CLS]` tokens to separate sentences.
[ "Encode", "the", "story", "and", "summary", "lines,", "and", "join", "them", "as", "specified", "in", "[1]", "by", "using", "`[SEP]", "[CLS]`", "tokens", "to", "separate", "sentences." ]
def encode_for_summarization(story_lines, summary_lines, tokenizer): story_lines_token_ids = [tokenizer.encode(line) for line in story_lines] story_token_ids = [token for sentence in story_lines_token_ids for token in sentence] summary_lines_token_ids = [tokenizer.encode(line) for line in summary_lines] ...
['def', 'encode_for_summarization(story_lines,', 'summary_lines,', 'tokenizer):', 'story_lines_token_ids', '=', '[tokenizer.encode(line)', 'for', 'line', 'in', 'story_lines]', 'story_token_ids', '=', '[token', 'for', 'sentence', 'in', 'story_lines_token_ids', 'for', 'token', 'in', 'sentence]', 'summary_lines_token_ids'...
417,774
wanyao1992/code_summarization_public
Dict.py
Dict.prune
prune
Return a new dictionary with the `size` most frequent entries.
[ "Return", "a", "new", "dictionary", "with", "the", "`size`", "most", "frequent", "entries." ]
def prune(self, size): if size >= self.size(): return self freq = torch.Tensor([self.frequencies[i] for i in range(len(self.frequencies))]) (_, idx) = torch.sort(freq, 0, True) newDict = Dict() newDict.lower = self.lower for i in self.special: newDict.addSpecial(self.idxToLabel[i...
['def', 'prune(self,', 'size):', 'if', 'size', '>=', 'self.size():', 'return', 'self', 'freq', '=', 'torch.Tensor([self.frequencies[i]', 'for', 'i', 'in', 'range(len(self.frequencies))])', '(_,', 'idx)', '=', 'torch.sort(freq,', '0,', 'True)', 'newDict', '=', 'Dict()', 'newDict.lower', '=', 'self.lower', 'for', 'i', 'i...
495,844
violet-zct/fairseq-detect-hallucination
trainer.py
Trainer.set_num_updates
set_num_updates
Set the number of parameters updates.
[ "Set", "the", "number", "of", "parameters", "updates." ]
def set_num_updates(self, num_updates): self._num_updates = num_updates self.lr_step_update() if self.quantizer: self.quantizer.step_update(self._num_updates) metrics.log_scalar('num_updates', self._num_updates, weight=0, priority=200)
['def', 'set_num_updates(self,', 'num_updates):', 'self._num_updates', '=', 'num_updates', 'self.lr_step_update()', 'if', 'self.quantizer:', 'self.quantizer.step_update(self._num_updates)', "metrics.log_scalar('num_updates',", 'self._num_updates,', 'weight=0,', 'priority=200)']
558,632
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.nuser_geom
nuser_geom
number of mjtNums in geom_user.
[ "number", "of", "mjtNums", "in", "geom_user." ]
def nuser_geom(self): return self._ptr.contents.nuser_geom
['def', 'nuser_geom(self):', 'return', 'self._ptr.contents.nuser_geom']
440,216
kemaloksuz/RankSortLoss
guided_anchor_head.py
GuidedAnchorHead.get_sampled_approxs
get_sampled_approxs
Get sampled approxs and inside flags according to feature map sizes.
[ "Get", "sampled", "approxs", "and", "inside", "flags", "according", "to", "feature", "map", "sizes." ]
def get_sampled_approxs(self, featmap_sizes, img_metas, device='cuda'): num_imgs = len(img_metas) multi_level_approxs = self.approx_anchor_generator.grid_anchors(featmap_sizes, device=device) approxs_list = [multi_level_approxs for _ in range(num_imgs)] inside_flag_list = [] for (img_id, img_meta) i...
['def', 'get_sampled_approxs(self,', 'featmap_sizes,', 'img_metas,', "device='cuda'):", 'num_imgs', '=', 'len(img_metas)', 'multi_level_approxs', '=', 'self.approx_anchor_generator.grid_anchors(featmap_sizes,', 'device=device)', 'approxs_list', '=', '[multi_level_approxs', 'for', '_', 'in', 'range(num_imgs)]', 'inside_...
836,135
tensorly/quantum
noisy_expectation_op_test.py
NoisyExpectationCalculationTest.test_single_channel
test_single_channel
Individually test adding just a single channel type to circuits.
[ "Individually", "test", "adding", "just", "a", "single", "channel", "type", "to", "circuits." ]
def test_single_channel(self, channel): symbol_names = [] batch_size = 5 n_qubits = 6 qubits = cirq.LineQubit.range(n_qubits) (circuit_batch, resolver_batch) = util.random_circuit_resolver_batch(qubits, batch_size, include_channels=False) for i in range(batch_size): circuit_batch[i] = ci...
['def', 'test_single_channel(self,', 'channel):', 'symbol_names', '=', '[]', 'batch_size', '=', '5', 'n_qubits', '=', '6', 'qubits', '=', 'cirq.LineQubit.range(n_qubits)', '(circuit_batch,', 'resolver_batch)', '=', 'util.random_circuit_resolver_batch(qubits,', 'batch_size,', 'include_channels=False)', 'for', 'i', 'in',...
834,846
fudan-zvg/SeaFormer
hub.py
get_cache_dir
get_cache_dir
Returns the location of the directory where models are cached (and creates it if necessary).
[ "Returns", "the", "location", "of", "the", "directory", "where", "models", "are", "cached", "(and", "creates", "it", "if", "necessary)." ]
def get_cache_dir(child_dir=''): if os.getenv('TORCH_MODEL_ZOO'): _logger.warning('TORCH_MODEL_ZOO is deprecated, please use env TORCH_HOME instead') hub_dir = get_dir() child_dir = () if not child_dir else (child_dir,) model_dir = os.path.join(hub_dir, 'checkpoints', *child_dir) os.makedirs...
['def', "get_cache_dir(child_dir=''):", 'if', "os.getenv('TORCH_MODEL_ZOO'):", "_logger.warning('TORCH_MODEL_ZOO", 'is', 'deprecated,', 'please', 'use', 'env', 'TORCH_HOME', "instead')", 'hub_dir', '=', 'get_dir()', 'child_dir', '=', '()', 'if', 'not', 'child_dir', 'else', '(child_dir,)', 'model_dir', '=', 'os.path.joi...
855,487
deepmind/dm_control
rodent.py
Rat.ground_contact_geoms
ground_contact_geoms
Return ground contact geoms.
[ "Return", "ground", "contact", "geoms." ]
def ground_contact_geoms(self): return tuple(self._mjcf_root.find('body', 'foot_L').find_all('geom') + self._mjcf_root.find('body', 'foot_R').find_all('geom') + self._mjcf_root.find('body', 'hand_L').find_all('geom') + self._mjcf_root.find('body', 'hand_R').find_all('geom') + self._mjcf_root.find('body', 'vertebra_...
['def', 'ground_contact_geoms(self):', 'return', "tuple(self._mjcf_root.find('body',", "'foot_L').find_all('geom')", '+', "self._mjcf_root.find('body',", "'foot_R').find_all('geom')", '+', "self._mjcf_root.find('body',", "'hand_L').find_all('geom')", '+', "self._mjcf_root.find('body',", "'hand_R').find_all('geom')", '+...
165,145
Levantespot/UDA_for_RS
ohem_pixel_sampler.py
OHEMPixelSampler.sample
sample
Sample pixels that have high loss or with low prediction confidence.
[ "Sample", "pixels", "that", "have", "high", "loss", "or", "with", "low", "prediction", "confidence." ]
def sample(self, seg_logit, seg_label): with torch.no_grad(): assert seg_logit.shape[2:] == seg_label.shape[2:] assert seg_label.shape[1] == 1 seg_label = seg_label.squeeze(1).long() batch_kept = self.min_kept * seg_label.size(0) valid_mask = seg_label != self.context.ignore_...
['def', 'sample(self,', 'seg_logit,', 'seg_label):', 'with', 'torch.no_grad():', 'assert', 'seg_logit.shape[2:]', '==', 'seg_label.shape[2:]', 'assert', 'seg_label.shape[1]', '==', '1', 'seg_label', '=', 'seg_label.squeeze(1).long()', 'batch_kept', '=', 'self.min_kept', '*', 'seg_label.size(0)', 'valid_mask', '=', 'seg...
947,333
ldamewood/renormalization
polyfit.py
polyfit
polyfit
Fit a polynomial using LinearRegression model.
[ "Fit", "a", "polynomial", "using", "LinearRegression", "model." ]
def polyfit(xdata, ydata, deg=2, linearMethod=NormalSVD()): if deg < 1: raise ValueError('Polynomial degree must be > 1') return linearMethod.getWeights(_xpoly(xdata, deg), ydata)
['def', 'polyfit(xdata,', 'ydata,', 'deg=2,', 'linearMethod=NormalSVD()):', 'if', 'deg', '<', '1:', 'raise', "ValueError('Polynomial", 'degree', 'must', 'be', '>', "1')", 'return', 'linearMethod.getWeights(_xpoly(xdata,', 'deg),', 'ydata)']
840,220
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data_utils.py
Vocabulary.encode
encode
Convert a sentence to a list of ids, with special tokens added.
[ "Convert", "a", "sentence", "to", "a", "list", "of", "ids,", "with", "special", "tokens", "added." ]
def encode(self, sentence): word_ids = [self.word_to_id(cur_word) for cur_word in sentence.split()] return np.array([self.bos] + word_ids + [self.eos], dtype=np.int32)
['def', 'encode(self,', 'sentence):', 'word_ids', '=', '[self.word_to_id(cur_word)', 'for', 'cur_word', 'in', 'sentence.split()]', 'return', 'np.array([self.bos]', '+', 'word_ids', '+', '[self.eos],', 'dtype=np.int32)']
49,972
megvii-research/TreeEnergyLoss
video_helper.py
VideoReader.width
width
int: Width of video frames.
[ "int:", "Width", "of", "video", "frames." ]
def width(self): return self._width
['def', 'width(self):', 'return', 'self._width']
951,447
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
req_uninstall.py
StashedUninstallPathSet.commit
commit
Commits the uninstall by removing stashed files.
[ "Commits", "the", "uninstall", "by", "removing", "stashed", "files." ]
def commit(self): for (_, save_dir) in self._save_dirs.items(): save_dir.cleanup() self._moves = [] self._save_dirs = {}
['def', 'commit(self):', 'for', '(_,', 'save_dir)', 'in', 'self._save_dirs.items():', 'save_dir.cleanup()', 'self._moves', '=', '[]', 'self._save_dirs', '=', '{}']
950,100
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
_pydecimal.py
Decimal.exp
exp
Returns e ** self.
[ "Returns", "e", "**", "self." ]
def exp(self, context=None): if context is None: context = getcontext() ans = self._check_nans(context=context) if ans: return ans if self._isinfinity() == -1: return _Zero if not self: return _One if self._isinfinity() == 1: return Decimal(self) p = c...
['def', 'exp(self,', 'context=None):', 'if', 'context', 'is', 'None:', 'context', '=', 'getcontext()', 'ans', '=', 'self._check_nans(context=context)', 'if', 'ans:', 'return', 'ans', 'if', 'self._isinfinity()', '==', '-1:', 'return', '_Zero', 'if', 'not', 'self:', 'return', '_One', 'if', 'self._isinfinity()', '==', '1:...
429,980
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pydoc.py
stripid
stripid
Remove the hexadecimal id from a Python object representation.
[ "Remove", "the", "hexadecimal", "id", "from", "a", "Python", "object", "representation." ]
def stripid(text): return _re_stripid.sub('\\1', text)
['def', 'stripid(text):', 'return', "_re_stripid.sub('\\\\1',", 'text)']
429,281
43Carrig/recurrent_neural_networks_practice
ops.py
get_all_collection_keys
get_all_collection_keys
Returns a list of collections used in the default graph.
[ "Returns", "a", "list", "of", "collections", "used", "in", "the", "default", "graph." ]
def get_all_collection_keys(): return get_default_graph().get_all_collection_keys()
['def', 'get_all_collection_keys():', 'return', 'get_default_graph().get_all_collection_keys()']
336,362
GregorKobsik/Octree-Transformer
kd_tree_test.py
TestQuadtree.test_token_sequence_retrival_short
test_token_sequence_retrival_short
Inserts a sequence representing a diagonal line and tries to retrive the same token sequence.
[ "Inserts", "a", "sequence", "representing", "a", "diagonal", "line", "and", "tries", "to", "retrive", "the", "same", "token", "sequence." ]
def test_token_sequence_retrival_short(self): input = '1221' + '12211221' qtree = kdTree(spatial_dim=2).insert_token_sequence(input, resolution=32) output = qtree.get_token_sequence()[0] self.assertEqual(len(input), len(output)) self.assertSequenceEqual(input, ''.join((str(x) for x in output)))
['def', 'test_token_sequence_retrival_short(self):', 'input', '=', "'1221'", '+', "'12211221'", 'qtree', '=', 'kdTree(spatial_dim=2).insert_token_sequence(input,', 'resolution=32)', 'output', '=', 'qtree.get_token_sequence()[0]', 'self.assertEqual(len(input),', 'len(output))', 'self.assertSequenceEqual(input,', "''.joi...
755,113
weimin17/Object-Detection_HelmetDetection
evaluation_utils.py
print_formatted
print_formatted
Print and log metrics.
[ "Print", "and", "log", "metrics." ]
def print_formatted(present, id_to_word, log, batch_of_tuples): num_cols = len(batch_of_tuples[0][0]) repeat_float_format = '{:<12.3f} ' repeat_str_format = '{:<13}' format_str = ''.join(['[{:<1}] {:<20}', str(repeat_float_format * (num_cols - 1))]) header_format_str = ''.join(['[{:<1}] {:<20}', s...
['def', 'print_formatted(present,', 'id_to_word,', 'log,', 'batch_of_tuples):', 'num_cols', '=', 'len(batch_of_tuples[0][0])', 'repeat_float_format', '=', "'{:<12.3f}", "'", 'repeat_str_format', '=', "'{:<13}'", 'format_str', '=', "''.join(['[{:<1}]", "{:<20}',", 'str(repeat_float_format', '*', '(num_cols', '-', '1))])...
763,657
tueimage/essential-skills
scrollview.py
ScrollView.slice_index
slice_index
The index of the slice that is currently shown in the plot.
[ "The", "index", "of", "the", "slice", "that", "is", "currently", "shown", "in", "the", "plot." ]
def slice_index(self): return self._slice_index
['def', 'slice_index(self):', 'return', 'self._slice_index']
563,381
43Carrig/recurrent_neural_networks_practice
plugin_event_multiplexer.py
EventMultiplexer.SummaryMetadata
SummaryMetadata
Return the summary metadata for the given tag on the given run.
[ "Return", "the", "summary", "metadata", "for", "the", "given", "tag", "on", "the", "given", "run." ]
def SummaryMetadata(self, run, tag): accumulator = self.GetAccumulator(run) return accumulator.SummaryMetadata(tag)
['def', 'SummaryMetadata(self,', 'run,', 'tag):', 'accumulator', '=', 'self.GetAccumulator(run)', 'return', 'accumulator.SummaryMetadata(tag)']
312,115
rudranil723/mini-main
dependencygraph.py
DependencyGraph.right_children
right_children
Returns the number of right children under the node specified by the given address.
[ "Returns", "the", "number", "of", "right", "children", "under", "the", "node", "specified", "by", "the", "given", "address." ]
def right_children(self, node_index): children = chain.from_iterable(self.nodes[node_index]['deps'].values()) index = self.nodes[node_index]['address'] return sum((1 for c in children if c > index))
['def', 'right_children(self,', 'node_index):', 'children', '=', "chain.from_iterable(self.nodes[node_index]['deps'].values())", 'index', '=', "self.nodes[node_index]['address']", 'return', 'sum((1', 'for', 'c', 'in', 'children', 'if', 'c', '>', 'index))']
321,455
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
encoder_manager.py
EncoderManager.load_model
load_model
Loads a skip-thoughts model.
[ "Loads", "a", "skip-thoughts", "model." ]
def load_model(self, model_config, vocabulary_file, embedding_matrix_file, checkpoint_path): tf.logging.info('Reading vocabulary from %s', vocabulary_file) with tf.gfile.GFile(vocabulary_file, mode='r') as f: lines = list(f.readlines()) reverse_vocab = [line.decode('utf-8').strip() for line in lines...
['def', 'load_model(self,', 'model_config,', 'vocabulary_file,', 'embedding_matrix_file,', 'checkpoint_path):', "tf.logging.info('Reading", 'vocabulary', 'from', "%s',", 'vocabulary_file)', 'with', 'tf.gfile.GFile(vocabulary_file,', "mode='r')", 'as', 'f:', 'lines', '=', 'list(f.readlines())', 'reverse_vocab', '=', "[l...
109,596
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
multi.py
MultiIndex.levshape
levshape
A tuple with the length of each level.
[ "A", "tuple", "with", "the", "length", "of", "each", "level." ]
def levshape(self): return tuple((len(x) for x in self.levels))
['def', 'levshape(self):', 'return', 'tuple((len(x)', 'for', 'x', 'in', 'self.levels))']
82,953
zedom1/nlp
inferer.py
Inferer.start
start
Runs the whole inferring process.
[ "Runs", "the", "whole", "inferring", "process." ]
def start(self): self.logger.info('start inferring...') (is_exist, infer_file) = self.get_infer_file() if is_exist: self.logger.info('file {} exists, skipping.'.format(infer_file)) self.model.evaluate(infer_file, from_file=True) return None all_res = [] for (i, batch) in enum...
['def', 'start(self):', "self.logger.info('start", "inferring...')", '(is_exist,', 'infer_file)', '=', 'self.get_infer_file()', 'if', 'is_exist:', "self.logger.info('file", '{}', 'exists,', "skipping.'.format(infer_file))", 'self.model.evaluate(infer_file,', 'from_file=True)', 'return', 'None', 'all_res', '=', '[]', 'f...
808,448
sunishsheth2009/ChatterBot
mcore.py
Matcher.term_matchers
term_matchers
Returns an iterator of term matchers in this tree.
[ "Returns", "an", "iterator", "of", "term", "matchers", "in", "this", "tree." ]
def term_matchers(self): if self.term() is not None: yield self else: for cm in self.children(): for m in cm.term_matchers(): yield m
['def', 'term_matchers(self):', 'if', 'self.term()', 'is', 'not', 'None:', 'yield', 'self', 'else:', 'for', 'cm', 'in', 'self.children():', 'for', 'm', 'in', 'cm.term_matchers():', 'yield', 'm']
484,550
43Carrig/recurrent_neural_networks_practice
control_flow_ops.py
CondContext.BuildCondBranch
BuildCondBranch
Add the subgraph defined by fn() to the graph.
[ "Add", "the", "subgraph", "defined", "by", "fn()", "to", "the", "graph." ]
def BuildCondBranch(self, fn): pre_summaries = ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) original_result = fn() post_summaries = ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION) if len(post_summaries) > len(pre_summaries): new_summaries = post_summaries[len(pre_summaries):] ...
['def', 'BuildCondBranch(self,', 'fn):', 'pre_summaries', '=', 'ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION)', 'original_result', '=', 'fn()', 'post_summaries', '=', 'ops.get_collection(ops.GraphKeys._SUMMARY_COLLECTION)', 'if', 'len(post_summaries)', '>', 'len(pre_summaries):', 'new_summaries', '=', 'post_sum...
337,171
thaines/helit
dataset.py
Dataset.getLabels
getLabels
Returns a list of all the labels in the data set.
[ "Returns", "a", "list", "of", "all", "the", "labels", "in", "the", "data", "set." ]
def getLabels(self): return self.numToLabel
['def', 'getLabels(self):', 'return', 'self.numToLabel']
592,466
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_102a.py
activ_to_bbox
activ_to_bbox
Extrapolate bounding boxes on anchors from the model activations.
[ "Extrapolate", "bounding", "boxes", "on", "anchors", "from", "the", "model", "activations." ]
def activ_to_bbox(acts, anchors, flatten=True): if flatten: acts.mul_(acts.new_tensor([[0.1, 0.1, 0.2, 0.2]])) centers = anchors[..., 2:] * acts[..., :2] + anchors[..., :2] sizes = anchors[..., 2:] * torch.exp(acts[..., :2]) return torch.cat([centers, sizes], -1) else: re...
['def', 'activ_to_bbox(acts,', 'anchors,', 'flatten=True):', 'if', 'flatten:', 'acts.mul_(acts.new_tensor([[0.1,', '0.1,', '0.2,', '0.2]]))', 'centers', '=', 'anchors[...,', '2:]', '*', 'acts[...,', ':2]', '+', 'anchors[...,', ':2]', 'sizes', '=', 'anchors[...,', '2:]', '*', 'torch.exp(acts[...,', ':2])', 'return', 'to...
32,608
Oneflow-Inc/vision
vision_helpers.py
make_grid
make_grid
Make a grid of images.
[ "Make", "a", "grid", "of", "images." ]
def make_grid(tensor: Union[flow.Tensor, List[flow.Tensor]], nrow: int=8, padding: int=2, normalize: bool=False, range: Optional[Tuple[int, int]]=None, scale_each: bool=False, pad_value: int=0) -> flow.Tensor: if not (isinstance(tensor, flow.Tensor) or (isinstance(tensor, list) and all((isinstance(t, flow.Tensor) f...
['def', 'make_grid(tensor:', 'Union[flow.Tensor,', 'List[flow.Tensor]],', 'nrow:', 'int=8,', 'padding:', 'int=2,', 'normalize:', 'bool=False,', 'range:', 'Optional[Tuple[int,', 'int]]=None,', 'scale_each:', 'bool=False,', 'pad_value:', 'int=0)', '->', 'flow.Tensor:', 'if', 'not', '(isinstance(tensor,', 'flow.Tensor)', ...
957,637
researchmm/WSOD2
lvis.py
LVISV05Dataset.evaluate
evaluate
Evaluation in LVIS protocol.
[ "Evaluation", "in", "LVIS", "protocol." ]
def evaluate(self, results, metric='bbox', logger=None, jsonfile_prefix=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=np.arange(0.5, 0.96, 0.05)): try: import lvis assert lvis.__version__ >= '10.5.3' from lvis import LVISResults, LVISEval except AssertionError: ...
['def', 'evaluate(self,', 'results,', "metric='bbox',", 'logger=None,', 'jsonfile_prefix=None,', 'classwise=False,', 'proposal_nums=(100,', '300,', '1000),', 'iou_thrs=np.arange(0.5,', '0.96,', '0.05)):', 'try:', 'import', 'lvis', 'assert', 'lvis.__version__', '>=', "'10.5.3'", 'from', 'lvis', 'import', 'LVISResults,',...
374,104
43Carrig/recurrent_neural_networks_practice
bijector_impl.py
Bijector.validate_args
validate_args
Returns True if Tensor arguments will be validated.
[ "Returns", "True", "if", "Tensor", "arguments", "will", "be", "validated." ]
def validate_args(self): return self._validate_args
['def', 'validate_args(self):', 'return', 'self._validate_args']
339,160
tensorflow/agents
array_spec.py
BoundedArraySpec.minimum
minimum
Returns a NumPy array specifying the minimum bounds (inclusive).
[ "Returns", "a", "NumPy", "array", "specifying", "the", "minimum", "bounds", "(inclusive)." ]
def minimum(self): return self._minimum
['def', 'minimum(self):', 'return', 'self._minimum']
23,680
43Carrig/recurrent_neural_networks_practice
categorical_split_handler.py
EqualitySplitHandler.update_stats
update_stats
Updates the state for equality split handler.
[ "Updates", "the", "state", "for", "equality", "split", "handler." ]
def update_stats(self, stamp_token, example_partition_ids, gradients, hessians, empty_gradients, empty_hessians, weights, is_active, scheduled_reads): del scheduled_reads def not_active_inputs(): return (constant_op.constant([], dtype=dtypes.int32), constant_op.constant([], dtype=dtypes.int64, shape=[1...
['def', 'update_stats(self,', 'stamp_token,', 'example_partition_ids,', 'gradients,', 'hessians,', 'empty_gradients,', 'empty_hessians,', 'weights,', 'is_active,', 'scheduled_reads):', 'del', 'scheduled_reads', 'def', 'not_active_inputs():', 'return', '(constant_op.constant([],', 'dtype=dtypes.int32),', 'constant_op.co...
312,479
clips/pattern
__init__.py
Graph.edge
edge
Returns the edge between the nodes with given id1 and id2.
[ "Returns", "the", "edge", "between", "the", "nodes", "with", "given", "id1", "and", "id2." ]
def edge(self, id1, id2): if isinstance(id1, Node) and id1.graph == self: id1 = id1.id if isinstance(id2, Node) and id2.graph == self: id2 = id2.id return id1 in self and id2 in self and self[id1].links.edge(id2) or None
['def', 'edge(self,', 'id1,', 'id2):', 'if', 'isinstance(id1,', 'Node)', 'and', 'id1.graph', '==', 'self:', 'id1', '=', 'id1.id', 'if', 'isinstance(id2,', 'Node)', 'and', 'id2.graph', '==', 'self:', 'id2', '=', 'id2.id', 'return', 'id1', 'in', 'self', 'and', 'id2', 'in', 'self', 'and', 'self[id1].links.edge(id2)', 'or'...
764,660
QData/deepWordBug
tty.py
Terminal.israw
israw
Returns True if the TTY should operate in raw mode.
[ "Returns", "True", "if", "the", "TTY", "should", "operate", "in", "raw", "mode." ]
def israw(self): return self.raw
['def', 'israw(self):', 'return', 'self.raw']
541,986
masterkapilkumar/Unsupervised-Learning
utils.py
generate_images_helper
generate_images_helper
Helper function to visualize generated images from randomly sampled values from the latent space.
[ "Helper", "function", "to", "visualize", "generated", "images", "from", "randomly", "sampled", "values", "from", "the", "latent", "space." ]
def generate_images_helper(net, epoch, label='After_'): net.eval() with torch.no_grad(): z = torch.randn(config.TEST_SAMPLES, config.LATENT_DIM).to(config.device) (_, test_images) = net(z, encode=False, decode=True) test_images = test_images.cpu().detach().numpy() net.train() ...
['def', 'generate_images_helper(net,', 'epoch,', "label='After_'):", 'net.eval()', 'with', 'torch.no_grad():', 'z', '=', 'torch.randn(config.TEST_SAMPLES,', 'config.LATENT_DIM).to(config.device)', '(_,', 'test_images)', '=', 'net(z,', 'encode=False,', 'decode=True)', 'test_images', '=', 'test_images.cpu().detach().nump...
353,427
ganyeshprasanna/AI
heuristic_search.py
Grid.get_coin_locations
get_coin_locations
Returns a list of the coordinates of all coins.
[ "Returns", "a", "list", "of", "the", "coordinates", "of", "all", "coins." ]
def get_coin_locations(self): coins = [] for x in range(self.width): for y in range(self.height): if self.is_coin(x, y): coins.append((x, y)) return coins
['def', 'get_coin_locations(self):', 'coins', '=', '[]', 'for', 'x', 'in', 'range(self.width):', 'for', 'y', 'in', 'range(self.height):', 'if', 'self.is_coin(x,', 'y):', 'coins.append((x,', 'y))', 'return', 'coins']
69,582
myothida/Supervised-Machine-Learning
arrayTools.py
vectorLength
vectorLength
Calculate the length of the given vector.
[ "Calculate", "the", "length", "of", "the", "given", "vector." ]
def vectorLength(vector): (x, y) = vector return math.sqrt(x ** 2 + y ** 2)
['def', 'vectorLength(vector):', '(x,', 'y)', '=', 'vector', 'return', 'math.sqrt(x', '**', '2', '+', 'y', '**', '2)']
360,907
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
nb_007b.py
PoolingLinearClassifier.pool
pool
Pools the tensor along the seq_len dimension.
[ "Pools", "the", "tensor", "along", "the", "seq_len", "dimension." ]
def pool(self, x: Tensor, bs: int, is_max: bool): f = F.adaptive_max_pool1d if is_max else F.adaptive_avg_pool1d return f(x.permute(1, 2, 0), (1,)).view(bs, -1)
['def', 'pool(self,', 'x:', 'Tensor,', 'bs:', 'int,', 'is_max:', 'bool):', 'f', '=', 'F.adaptive_max_pool1d', 'if', 'is_max', 'else', 'F.adaptive_avg_pool1d', 'return', 'f(x.permute(1,', '2,', '0),', '(1,)).view(bs,', '-1)']
81,801
hideyukiinada/transfer-learning
util_functions.py
gen_preds
gen_preds
Generates predictions on a novel data array using a fit classifier clf is a classifier that has already been fit arr is a data array identical in dimension to the array clf was trained on Returns the array of predictions.
[ "Generates", "predictions", "on", "a", "novel", "data", "array", "using", "a", "fit", "classifier", "clf", "is", "a", "classifier", "that", "has", "already", "been", "fit", "arr", "is", "a", "data", "array", "identical", "in", "dimension", "to", "the", "ar...
def gen_preds(clf, arr): if hasattr(clf, 'predict_proba'): ret = clf.predict(arr) else: ret = clf.predict(arr) return ret
['def', 'gen_preds(clf,', 'arr):', 'if', 'hasattr(clf,', "'predict_proba'):", 'ret', '=', 'clf.predict(arr)', 'else:', 'ret', '=', 'clf.predict(arr)', 'return', 'ret']
929,443
google-research/batch-ppo
batch_env.py
BatchEnv.reset
reset
Reset the environment and convert the resulting observation.
[ "Reset", "the", "environment", "and", "convert", "the", "resulting", "observation." ]
def reset(self, indices=None): if indices is None: indices = np.arange(len(self._envs)) if self._blocking: observs = [self._envs[index].reset() for index in indices] else: observs = [self._envs[index].reset(blocking=False) for index in indices] observs = [observ() for observ ...
['def', 'reset(self,', 'indices=None):', 'if', 'indices', 'is', 'None:', 'indices', '=', 'np.arange(len(self._envs))', 'if', 'self._blocking:', 'observs', '=', '[self._envs[index].reset()', 'for', 'index', 'in', 'indices]', 'else:', 'observs', '=', '[self._envs[index].reset(blocking=False)', 'for', 'index', 'in', 'indi...
95,032
kornia/kornia
tiny_vit.py
TinyViT.from_config
from_config
Create a TinyViT model from pre-defined variants.
[ "Create", "a", "TinyViT", "model", "from", "pre-defined", "variants." ]
def from_config(variant: str, pretrained: bool | str=False, **kwargs: Any) -> TinyViT: KORNIA_CHECK(variant in ('5m', '11m', '21m'), 'Only variant 5m, 11m, and 21m are supported') return {'5m': _tiny_vit_5m, '11m': _tiny_vit_11m, '21m': _tiny_vit_21m}[variant](pretrained, **kwargs)
['def', 'from_config(variant:', 'str,', 'pretrained:', 'bool', '|', 'str=False,', '**kwargs:', 'Any)', '->', 'TinyViT:', 'KORNIA_CHECK(variant', 'in', "('5m',", "'11m',", "'21m'),", "'Only", 'variant', '5m,', '11m,', 'and', '21m', 'are', "supported')", 'return', "{'5m':", '_tiny_vit_5m,', "'11m':", '_tiny_vit_11m,', "'...
621,625
Kvatsx/Artificial-Intelligence-Assignments
_deprecated.py
ZMQIOLoop.current
current
Returns the current thread’s IOLoop.
[ "Returns", "the", "current", "thread’s", "IOLoop." ]
def current(cls, *args, **kwargs): if tornado_version >= (3,): PollIOLoop.configure(cls) loop = PollIOLoop.current(*args, **kwargs) if not isinstance(loop, cls): warnings.warn('IOLoop.current expected instance of %r, got %r' % (cls, loop), RuntimeWarning, stacklevel=2) return loop
['def', 'current(cls,', '*args,', '**kwargs):', 'if', 'tornado_version', '>=', '(3,):', 'PollIOLoop.configure(cls)', 'loop', '=', 'PollIOLoop.current(*args,', '**kwargs)', 'if', 'not', 'isinstance(loop,', 'cls):', "warnings.warn('IOLoop.current", 'expected', 'instance', 'of', '%r,', 'got', "%r'", '%', '(cls,', 'loop),'...
79,211
vivekchoksi/taxi-pickups
plot.py
Plotter.plotNumPickupsByZone
plotNumPickupsByZone
Plot a histogram showing the distribution of true number of pickups by zone.
[ "Plot", "a", "histogram", "showing", "the", "distribution", "of", "true", "number", "of", "pickups", "by", "zone." ]
def plotNumPickupsByZone(self): num_pickups_by_zone = {} num_pickups_list = [] for row in self.data: zone_id = str(row['zone_id']) num_pickups_by_zone[zone_id] = num_pickups_by_zone.get(zone_id, 0) + row['num_pickups'] for num_pickups in num_pickups_by_zone.values(): num_pickups_...
['def', 'plotNumPickupsByZone(self):', 'num_pickups_by_zone', '=', '{}', 'num_pickups_list', '=', '[]', 'for', 'row', 'in', 'self.data:', 'zone_id', '=', "str(row['zone_id'])", 'num_pickups_by_zone[zone_id]', '=', 'num_pickups_by_zone.get(zone_id,', '0)', '+', "row['num_pickups']", 'for', 'num_pickups', 'in', 'num_pick...
365,496
danamyu/hedgehog_detector
model.py
Model.sample_step
sample_step
Sample batch of steps from policy.
[ "Sample", "batch", "of", "steps", "from", "policy." ]
def sample_step(self, sess, single_observation, internal_state, single_action, greedy=False): if greedy: outputs = [self.greedy_next_internal_state, self.greedy_sampled_actions] else: outputs = [self.next_internal_state, self.sampled_actions] feed_dict = {self.internal_state: internal_state}...
['def', 'sample_step(self,', 'sess,', 'single_observation,', 'internal_state,', 'single_action,', 'greedy=False):', 'if', 'greedy:', 'outputs', '=', '[self.greedy_next_internal_state,', 'self.greedy_sampled_actions]', 'else:', 'outputs', '=', '[self.next_internal_state,', 'self.sampled_actions]', 'feed_dict', '=', '{se...
590,242
tobegit3hub/deep_image_model
dnn_linear_combined_test.py
DNNLinearCombinedClassifierTest.testLossWithWeights
testLossWithWeights
Tests loss calculation with weights.
[ "Tests", "loss", "calculation", "with", "weights." ]
def testLossWithWeights(self): def _input_fn_train(): features = {'x': tf.ones(shape=[4, 1], dtype=tf.float32), 'w': tf.constant([[1.0], [1.0], [1.0], [1.0]])} labels = tf.constant([[1.0], [0.0], [0.0], [0.0]]) return (features, labels) def _input_fn_eval(): features = {'x': tf...
['def', 'testLossWithWeights(self):', 'def', '_input_fn_train():', 'features', '=', "{'x':", 'tf.ones(shape=[4,', '1],', 'dtype=tf.float32),', "'w':", 'tf.constant([[1.0],', '[1.0],', '[1.0],', '[1.0]])}', 'labels', '=', 'tf.constant([[1.0],', '[0.0],', '[0.0],', '[0.0]])', 'return', '(features,', 'labels)', 'def', '_i...
181,664
choasup/SIN
config.py
cfg_from_file
cfg_from_file
Load a config file and merge it into the default options.
[ "Load", "a", "config", "file", "and", "merge", "it", "into", "the", "default", "options." ]
def cfg_from_file(filename): import yaml with open(filename, 'r') as f: yaml_cfg = edict(yaml.load(f)) _merge_a_into_b(yaml_cfg, __C)
['def', 'cfg_from_file(filename):', 'import', 'yaml', 'with', 'open(filename,', "'r')", 'as', 'f:', 'yaml_cfg', '=', 'edict(yaml.load(f))', '_merge_a_into_b(yaml_cfg,', '__C)']
884,330
triaquae/triaquae
archive.py
extract
extract
Unpack the tar or zip file at the specified path to the directory specified by to_path.
[ "Unpack", "the", "tar", "or", "zip", "file", "at", "the", "specified", "path", "to", "the", "directory", "specified", "by", "to_path." ]
def extract(path, to_path=''): with Archive(path) as archive: archive.extract(to_path)
['def', 'extract(path,', "to_path=''):", 'with', 'Archive(path)', 'as', 'archive:', 'archive.extract(to_path)']
423,998
zihuitang/medical_AI_platform
__init__.py
Listbox.selection_set
selection_set
Set the selection from FIRST to LAST (included) without changing the currently selected elements.
[ "Set", "the", "selection", "from", "FIRST", "to", "LAST", "(included)", "without", "changing", "the", "currently", "selected", "elements." ]
def selection_set(self, first, last=None): self.tk.call(self._w, 'selection', 'set', first, last)
['def', 'selection_set(self,', 'first,', 'last=None):', 'self.tk.call(self._w,', "'selection',", "'set',", 'first,', 'last)']
284,281
sunishsheth2009/ChatterBot
test_example.py
ViewTestCase.test_get_main_page
test_get_main_page
Test that the main page can be loaded.
[ "Test", "that", "the", "main", "page", "can", "be", "loaded." ]
def test_get_main_page(self): response = self.client.get(self.url) self.assertEqual(response.status_code, 200)
['def', 'test_get_main_page(self):', 'response', '=', 'self.client.get(self.url)', 'self.assertEqual(response.status_code,', '200)']
478,201