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 |
|---|---|---|---|---|---|---|---|---|
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_layers.py | tpu_conv1d | tpu_conv1d | Version of conv1d that works on TPU (as of 11/2017). | [
"Version",
"of",
"conv1d",
"that",
"works",
"on",
"TPU",
"(as",
"of",
"11/2017)."
] | def tpu_conv1d(inputs, filters, kernel_size, padding='SAME', name='tpu_conv1d'):
if kernel_size == 1:
return dense(inputs, filters, name=name, use_bias=True)
if padding == 'SAME':
assert kernel_size % 2 == 1
first_offset = -((kernel_size - 1) // 2)
else:
assert padding == 'LE... | ['def', 'tpu_conv1d(inputs,', 'filters,', 'kernel_size,', "padding='SAME',", "name='tpu_conv1d'):", 'if', 'kernel_size', '==', '1:', 'return', 'dense(inputs,', 'filters,', 'name=name,', 'use_bias=True)', 'if', 'padding', '==', "'SAME':", 'assert', 'kernel_size', '%', '2', '==', '1', 'first_offset', '=', '-((kernel_size... | 965,253 |
zcablii/LSKNet | oriented_reppoints_head.py | OrientedRepPointsHead.dynamic_pointset_samples_selection | dynamic_pointset_samples_selection | The dynamic top k selection of point set samples based on the quality assessment values. | [
"The",
"dynamic",
"top",
"k",
"selection",
"of",
"point",
"set",
"samples",
"based",
"on",
"the",
"quality",
"assessment",
"values."
] | def dynamic_pointset_samples_selection(self, quality, label, label_weight, bbox_weight, pos_inds, pos_gt_inds, num_proposals_each_level=None, num_level=None):
if len(pos_inds) == 0:
return (label, label_weight, bbox_weight, 0, torch.tensor([]).type_as(bbox_weight))
num_gt = pos_gt_inds.max()
num_pro... | ['def', 'dynamic_pointset_samples_selection(self,', 'quality,', 'label,', 'label_weight,', 'bbox_weight,', 'pos_inds,', 'pos_gt_inds,', 'num_proposals_each_level=None,', 'num_level=None):', 'if', 'len(pos_inds)', '==', '0:', 'return', '(label,', 'label_weight,', 'bbox_weight,', '0,', 'torch.tensor([]).type_as(bbox_weig... | 616,132 |
KleinYuan/tf-object-detection | inception_v4.py | block_inception_a | block_inception_a | Builds Inception-A block for Inception v4 network. | [
"Builds",
"Inception-A",
"block",
"for",
"Inception",
"v4",
"network."
] | def block_inception_a(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockInceptionA', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv... | ['def', 'block_inception_a(inputs,', 'scope=None,', 'reuse=None):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.avg_pool2d,', 'slim.max_pool2d],', 'stride=1,', "padding='SAME'):", 'with', 'tf.variable_scope(scope,', "'BlockInceptionA',", '[inputs],', 'reuse=reuse):', 'with', "tf.variable_scope('Branch_0'):", 'branch_... | 915,399 |
matsu0228/nlp-jp | named_commands.py | register | register | Store handler in the `_readline_commands` dictionary. | [
"Store",
"handler",
"in",
"the",
"`_readline_commands`",
"dictionary."
] | def register(name):
assert isinstance(name, six.text_type)
def decorator(handler):
assert callable(handler)
_readline_commands[name] = handler
return handler
return decorator | ['def', 'register(name):', 'assert', 'isinstance(name,', 'six.text_type)', 'def', 'decorator(handler):', 'assert', 'callable(handler)', '_readline_commands[name]', '=', 'handler', 'return', 'handler', 'return', 'decorator'] | 804,445 |
deepmind/dm_control | lqr.py | LQRLevel.get_termination | get_termination | Terminates when the state norm is smaller than epsilon. | [
"Terminates",
"when",
"the",
"state",
"norm",
"is",
"smaller",
"than",
"epsilon."
] | def get_termination(self, physics):
if physics.state_norm() < self._TERMINAL_TOL:
return 0.0 | ['def', 'get_termination(self,', 'physics):', 'if', 'physics.state_norm()', '<', 'self._TERMINAL_TOL:', 'return', '0.0'] | 165,510 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model.py | Seq2SeqAttentionSharedEmbedding.decode | decode | Return probability distribution over words. | [
"Return",
"probability",
"distribution",
"over",
"words."
] | def decode(self, logits):
logits_reshape = logits.view(-1, self.vocab_size)
word_probs = F.softmax(logits_reshape)
word_probs = word_probs.view(logits.size()[0], logits.size()[1], logits.size()[2])
return word_probs | ['def', 'decode(self,', 'logits):', 'logits_reshape', '=', 'logits.view(-1,', 'self.vocab_size)', 'word_probs', '=', 'F.softmax(logits_reshape)', 'word_probs', '=', 'word_probs.view(logits.size()[0],', 'logits.size()[1],', 'logits.size()[2])', 'return', 'word_probs'] | 15,044 |
arshpreetsingh/quantopian-machinelearning | sessionmanager.py | SessionManager.start_kernel_for_session | start_kernel_for_session | Start a new kernel for a given session. | [
"Start",
"a",
"new",
"kernel",
"for",
"a",
"given",
"session."
] | def start_kernel_for_session(self, session_id, path, name, type, kernel_name):
kernel_path = self.contents_manager.get_kernel_path(path=path)
kernel_id = (yield maybe_future(self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)))
raise gen.Return(kernel_id) | ['def', 'start_kernel_for_session(self,', 'session_id,', 'path,', 'name,', 'type,', 'kernel_name):', 'kernel_path', '=', 'self.contents_manager.get_kernel_path(path=path)', 'kernel_id', '=', '(yield', 'maybe_future(self.kernel_manager.start_kernel(path=kernel_path,', 'kernel_name=kernel_name)))', 'raise', 'gen.Return(k... | 888,667 |
google/deepvariant | dv_utils.py | get_one_example_from_examples_path | get_one_example_from_examples_path | Get the first record from `source`. | [
"Get",
"the",
"first",
"record",
"from",
"`source`."
] | def get_one_example_from_examples_path(source, proto=None):
files = sharded_file_utils.glob_list_sharded_file_patterns(source)
if not files:
raise ValueError('Cannot find matching files with the pattern "{}"'.format(source))
for f in files:
try:
return next(tfrecord.read_tfrecord... | ['def', 'get_one_example_from_examples_path(source,', 'proto=None):', 'files', '=', 'sharded_file_utils.glob_list_sharded_file_patterns(source)', 'if', 'not', 'files:', 'raise', "ValueError('Cannot", 'find', 'matching', 'files', 'with', 'the', 'pattern', '"{}"\'.format(source))', 'for', 'f', 'in', 'files:', 'try:', 're... | 540,274 |
triaquae/triaquae | errcheck.py | check_geom | check_geom | Error checking on routines that return Geometries. | [
"Error",
"checking",
"on",
"routines",
"that",
"return",
"Geometries."
] | def check_geom(result, func, cargs):
if not result:
raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__)
return result | ['def', 'check_geom(result,', 'func,', 'cargs):', 'if', 'not', 'result:', 'raise', "GEOSException('Error", 'encountered', 'checking', 'Geometry', 'returned', 'from', 'GEOS', 'C', 'function', '"%s".\'', '%', 'func.__name__)', 'return', 'result'] | 357,854 |
boostcampaitech2/semantic-segmentation-level2-cv-07 | mask_point_head.py | MaskPointHead.forward | forward | Classify each point base on fine grained and coarse feats. | [
"Classify",
"each",
"point",
"base",
"on",
"fine",
"grained",
"and",
"coarse",
"feats."
] | def forward(self, fine_grained_feats, coarse_feats):
x = torch.cat([fine_grained_feats, coarse_feats], dim=1)
for fc in self.fcs:
x = fc(x)
if self.coarse_pred_each_layer:
x = torch.cat((x, coarse_feats), dim=1)
return self.fc_logits(x) | ['def', 'forward(self,', 'fine_grained_feats,', 'coarse_feats):', 'x', '=', 'torch.cat([fine_grained_feats,', 'coarse_feats],', 'dim=1)', 'for', 'fc', 'in', 'self.fcs:', 'x', '=', 'fc(x)', 'if', 'self.coarse_pred_each_layer:', 'x', '=', 'torch.cat((x,', 'coarse_feats),', 'dim=1)', 'return', 'self.fc_logits(x)'] | 857,294 |
wbsth/cs50ai | minesweeper.py | Sentence.mark_mine | mark_mine | Updates internal knowledge representation given the fact that a cell is known to be a mine. | [
"Updates",
"internal",
"knowledge",
"representation",
"given",
"the",
"fact",
"that",
"a",
"cell",
"is",
"known",
"to",
"be",
"a",
"mine."
] | def mark_mine(self, cell):
if cell in self.cells:
self.cells.remove(cell)
subtract = self.count - 1
self.count = 0 if subtract < 0 else subtract | ['def', 'mark_mine(self,', 'cell):', 'if', 'cell', 'in', 'self.cells:', 'self.cells.remove(cell)', 'subtract', '=', 'self.count', '-', '1', 'self.count', '=', '0', 'if', 'subtract', '<', '0', 'else', 'subtract'] | 192,454 |
thaines/helit | chunk_db.py | ChunkDB.empty | empty | Returns True if there is nothing in the db. | [
"Returns",
"True",
"if",
"there",
"is",
"nothing",
"in",
"the",
"db."
] | def empty(self):
return len(self.chunks) == 0 | ['def', 'empty(self):', 'return', 'len(self.chunks)', '==', '0'] | 591,843 |
enuguru/artificial_intelligence_and_machine_learning | datastructures.py | WWWAuthenticate.set_basic | set_basic | Clear the auth info and enable basic auth. | [
"Clear",
"the",
"auth",
"info",
"and",
"enable",
"basic",
"auth."
] | def set_basic(self, realm='authentication required'):
dict.clear(self)
dict.update(self, {'__auth_type__': 'basic', 'realm': realm})
if self.on_update:
self.on_update(self) | ['def', 'set_basic(self,', "realm='authentication", "required'):", 'dict.clear(self)', 'dict.update(self,', "{'__auth_type__':", "'basic',", "'realm':", 'realm})', 'if', 'self.on_update:', 'self.on_update(self)'] | 161,166 |
vturrisi/solo-learn | classification_dataloader.py | prepare_datasets | prepare_datasets | Prepares train and val datasets. | [
"Prepares",
"train",
"and",
"val",
"datasets."
] | def prepare_datasets(dataset: str, T_train: Callable, T_val: Callable, train_data_path: Optional[Union[str, Path]]=None, val_data_path: Optional[Union[str, Path]]=None, data_format: Optional[str]='image_folder', download: bool=True, data_fraction: float=-1.0) -> Tuple[Dataset, Dataset]:
if train_data_path is None:
... | ['def', 'prepare_datasets(dataset:', 'str,', 'T_train:', 'Callable,', 'T_val:', 'Callable,', 'train_data_path:', 'Optional[Union[str,', 'Path]]=None,', 'val_data_path:', 'Optional[Union[str,', 'Path]]=None,', 'data_format:', "Optional[str]='image_folder',", 'download:', 'bool=True,', 'data_fraction:', 'float=-1.0)', '-... | 393,543 |
intel/neural-compressor | test_domain.py | TestDomain.test_domain_with_flavour | test_domain_with_flavour | Test that domain serializes as expected. | [
"Test",
"that",
"domain",
"serializes",
"as",
"expected."
] | def test_domain_with_flavour(self) -> None:
domain = Domain(domain='foo', domain_flavour='bar')
expected = {'domain': 'foo', 'domain_flavour': 'bar'}
self.assertEqual(expected, domain.serialize()) | ['def', 'test_domain_with_flavour(self)', '->', 'None:', 'domain', '=', "Domain(domain='foo',", "domain_flavour='bar')", 'expected', '=', "{'domain':", "'foo',", "'domain_flavour':", "'bar'}", 'self.assertEqual(expected,', 'domain.serialize())'] | 721,632 |
Yorko/mlcourse.ai | apriori.py | TransactionManager.items | items | Returns the item list that the transaction is consisted of. | [
"Returns",
"the",
"item",
"list",
"that",
"the",
"transaction",
"is",
"consisted",
"of."
] | def items(self):
return sorted(self.__items) | ['def', 'items(self):', 'return', 'sorted(self.__items)'] | 630,100 |
liuslevis/weiquncrawler | oauth.py | OAuthServer.authorize_token | authorize_token | Authorize a request token. | [
"Authorize",
"a",
"request",
"token."
] | def authorize_token(self, token, user):
return self.data_store.authorize_request_token(token, user) | ['def', 'authorize_token(self,', 'token,', 'user):', 'return', 'self.data_store.authorize_request_token(token,', 'user)'] | 373,579 |
jshilong/DDQ | io.py | frames2video | frames2video | Read the frame images from a directory and join them as a video. | [
"Read",
"the",
"frame",
"images",
"from",
"a",
"directory",
"and",
"join",
"them",
"as",
"a",
"video."
] | def frames2video(frame_dir, video_file, fps=30, fourcc='XVID', filename_tmpl='{:06d}.jpg', start=0, end=0, show_progress=True):
if end == 0:
ext = filename_tmpl.split('.')[-1]
end = len([name for name in scandir(frame_dir, ext)])
first_file = osp.join(frame_dir, filename_tmpl.format(start))
... | ['def', 'frames2video(frame_dir,', 'video_file,', 'fps=30,', "fourcc='XVID',", "filename_tmpl='{:06d}.jpg',", 'start=0,', 'end=0,', 'show_progress=True):', 'if', 'end', '==', '0:', 'ext', '=', "filename_tmpl.split('.')[-1]", 'end', '=', 'len([name', 'for', 'name', 'in', 'scandir(frame_dir,', 'ext)])', 'first_file', '='... | 515,561 |
david-abel/simple_rl | BanditMDPClass.py | BanditMDP.get_parameters | get_parameters | Returns: (dict) key=param_name (str) --> val=param_val (object). | [
"Returns:",
"(dict)",
"key=param_name",
"(str)",
"-->",
"val=param_val",
"(object)."
] | def get_parameters(self):
param_dict = defaultdict(int)
param_dict['num_arms'] = self.num_arms
param_dict['distr_family'] = self.distr_family
param_dict['distr_params'] = self.distr_params
return param_dict | ['def', 'get_parameters(self):', 'param_dict', '=', 'defaultdict(int)', "param_dict['num_arms']", '=', 'self.num_arms', "param_dict['distr_family']", '=', 'self.distr_family', "param_dict['distr_params']", '=', 'self.distr_params', 'return', 'param_dict'] | 350,812 |
sunoonlee/cs224n | q2_parser_transitions.py | minibatch_parse | minibatch_parse | Parses a list of sentences in minibatches using a model. | [
"Parses",
"a",
"list",
"of",
"sentences",
"in",
"minibatches",
"using",
"a",
"model."
] | def minibatch_parse(sentences, model, batch_size):
(start_idx, end_idx) = (0, 0)
PartialParses = [PartialParse(sentence) for sentence in sentences]
dependencies = []
while end_idx < len(sentences):
end_idx = min(start_idx + batch_size, len(sentences))
batch_PartialParses = PartialParses[... | ['def', 'minibatch_parse(sentences,', 'model,', 'batch_size):', '(start_idx,', 'end_idx)', '=', '(0,', '0)', 'PartialParses', '=', '[PartialParse(sentence)', 'for', 'sentence', 'in', 'sentences]', 'dependencies', '=', '[]', 'while', 'end_idx', '<', 'len(sentences):', 'end_idx', '=', 'min(start_idx', '+', 'batch_size,',... | 507,277 |
denisyarats/exorl | quadruped.py | Physics.imu | imu | Returns IMU-like sensor readings. | [
"Returns",
"IMU-like",
"sensor",
"readings."
] | def imu(self):
imu_sensors = self._get_sensor_names(enums.mjtSensor.mjSENS_GYRO, enums.mjtSensor.mjSENS_ACCELEROMETER)
return self.named.data.sensordata[imu_sensors] | ['def', 'imu(self):', 'imu_sensors', '=', 'self._get_sensor_names(enums.mjtSensor.mjSENS_GYRO,', 'enums.mjtSensor.mjSENS_ACCELEROMETER)', 'return', 'self.named.data.sensordata[imu_sensors]'] | 563,593 |
AlibabaResearch/efficientteacher | autoaugment_utils.py | solarize_only_bboxes | solarize_only_bboxes | Apply solarize to each bbox in the image with probability prob. | [
"Apply",
"solarize",
"to",
"each",
"bbox",
"in",
"the",
"image",
"with",
"probability",
"prob."
] | def solarize_only_bboxes(image, bboxes, prob, threshold):
func_changes_bbox = False
prob = _scale_bbox_only_op_probability(prob)
return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, solarize, func_changes_bbox, threshold) | ['def', 'solarize_only_bboxes(image,', 'bboxes,', 'prob,', 'threshold):', 'func_changes_bbox', '=', 'False', 'prob', '=', '_scale_bbox_only_op_probability(prob)', 'return', '_apply_multi_bbox_augmentation_wrapper(image,', 'bboxes,', 'prob,', 'solarize,', 'func_changes_bbox,', 'threshold)'] | 561,094 |
sarnsdev/social-alignment-data-mining | test_parallel.py | test_dispatch_one_job | test_dispatch_one_job | Test that with only one job, Parallel does act as a iterator. | [
"Test",
"that",
"with",
"only",
"one",
"job,",
"Parallel",
"does",
"act",
"as",
"a",
"iterator."
] | def test_dispatch_one_job(backend, batch_size, expected_queue):
queue = list()
def producer():
for i in range(6):
queue.append('Produced %i' % i)
yield i
Parallel(n_jobs=1, batch_size=batch_size, backend=backend)((delayed(consumer)(queue, x) for x in producer()))
assert ... | ['def', 'test_dispatch_one_job(backend,', 'batch_size,', 'expected_queue):', 'queue', '=', 'list()', 'def', 'producer():', 'for', 'i', 'in', 'range(6):', "queue.append('Produced", "%i'", '%', 'i)', 'yield', 'i', 'Parallel(n_jobs=1,', 'batch_size=batch_size,', 'backend=backend)((delayed(consumer)(queue,', 'x)', 'for', '... | 352,579 |
berlius/artificial-intelligence | timer_comparison.py | ModuleTester.test_4 | test_4 | Test of take, transpose, inner, outer products. | [
"Test",
"of",
"take,",
"transpose,",
"inner,",
"outer",
"products."
] | def test_4(self):
x = self.arange(24)
y = np.arange(24)
x[5:6] = self.masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert self.allequal(np.transpose(y, (2, 0, 1)), self.transpose(x, (2, 0, 1)))
assert self.allequal(np.take(y, (2, 0, 1), 1), self.take(x, (2, 0, 1), 1))
assert self... | ['def', 'test_4(self):', 'x', '=', 'self.arange(24)', 'y', '=', 'np.arange(24)', 'x[5:6]', '=', 'self.masked', 'x', '=', 'x.reshape(2,', '3,', '4)', 'y', '=', 'y.reshape(2,', '3,', '4)', 'assert', 'self.allequal(np.transpose(y,', '(2,', '0,', '1)),', 'self.transpose(x,', '(2,', '0,', '1)))', 'assert', 'self.allequal(np... | 172,533 |
intel/neural-compressor | quantize_graph_matmul.py | FuseNodeStartWithMatmul.apply_matmul_biasadd_relu_fusion | apply_matmul_biasadd_relu_fusion | Apply the MatMul BiasAdd Relu fusion. | [
"Apply",
"the",
"MatMul",
"BiasAdd",
"Relu",
"fusion."
] | def apply_matmul_biasadd_relu_fusion(self, match_node_name):
matched_node = self.node_name_mapping[match_node_name[0]]
(control_inputs, normal_inputs) = self._get_node_input(matched_node.node.name)
weight_name = normal_inputs[1]
weight_node = self.node_name_mapping[helper.node_name_from_input(weight_nam... | ['def', 'apply_matmul_biasadd_relu_fusion(self,', 'match_node_name):', 'matched_node', '=', 'self.node_name_mapping[match_node_name[0]]', '(control_inputs,', 'normal_inputs)', '=', 'self._get_node_input(matched_node.node.name)', 'weight_name', '=', 'normal_inputs[1]', 'weight_node', '=', 'self.node_name_mapping[helper.... | 737,780 |
AEProgrammer/object_detection | model.py | DetectionModel.groundtruth_has_field | groundtruth_has_field | Determines whether the groundtruth includes the given field. | [
"Determines",
"whether",
"the",
"groundtruth",
"includes",
"the",
"given",
"field."
] | def groundtruth_has_field(self, field):
return field in self._groundtruth_lists | ['def', 'groundtruth_has_field(self,', 'field):', 'return', 'field', 'in', 'self._groundtruth_lists'] | 775,871 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | webcam.py | display_webcams | display_webcams | Builds an WebcamViewer to animate incoming images, runs it. | [
"Builds",
"an",
"WebcamViewer",
"to",
"animate",
"incoming",
"images,",
"runs",
"it."
] | def display_webcams(display_queues):
viewer = WebcamViewer(display_queues)
viewer.run() | ['def', 'display_webcams(display_queues):', 'viewer', '=', 'WebcamViewer(display_queues)', 'viewer.run()'] | 112,502 |
intelligent-environments-lab/CityLearn | citylearn.py | CityLearnEnv.power_outage | power_outage | Time series of number of buildings experiencing power outage. | [
"Time",
"series",
"of",
"number",
"of",
"buildings",
"experiencing",
"power",
"outage."
] | def power_outage(self) -> np.ndarray:
return pd.DataFrame([b.power_outage_signal for b in self.buildings]).sum(axis=0, min_count=1).to_numpy()[:self.time_step + 1] | ['def', 'power_outage(self)', '->', 'np.ndarray:', 'return', 'pd.DataFrame([b.power_outage_signal', 'for', 'b', 'in', 'self.buildings]).sum(axis=0,', 'min_count=1).to_numpy()[:self.time_step', '+', '1]'] | 105,702 |
rifqind/Agent-Programs-3KS1 | testing_test.py | AsyncTestCaseTest.test_subsequent_wait_calls | test_subsequent_wait_calls | This test makes sure that a second call to wait() clears the first timeout. | [
"This",
"test",
"makes",
"sure",
"that",
"a",
"second",
"call",
"to",
"wait()",
"clears",
"the",
"first",
"timeout."
] | def test_subsequent_wait_calls(self):
self.io_loop.add_timeout(self.io_loop.time() + 0.0, self.stop)
self.wait(timeout=0.02)
self.io_loop.add_timeout(self.io_loop.time() + 0.03, self.stop)
self.wait(timeout=0.15) | ['def', 'test_subsequent_wait_calls(self):', 'self.io_loop.add_timeout(self.io_loop.time()', '+', '0.0,', 'self.stop)', 'self.wait(timeout=0.02)', 'self.io_loop.add_timeout(self.io_loop.time()', '+', '0.03,', 'self.stop)', 'self.wait(timeout=0.15)'] | 21,554 |
fudan-zvg/DeepInteraction | depth_map_utils.py | fill_in_multiscale | fill_in_multiscale | Slower, multi-scale dilation version with additional noise removal that provides better qualitative results. | [
"Slower,",
"multi-scale",
"dilation",
"version",
"with",
"additional",
"noise",
"removal",
"that",
"provides",
"better",
"qualitative",
"results."
] | def fill_in_multiscale(depth_map, max_depth=100.0, dilation_kernel_far=CROSS_KERNEL_3, dilation_kernel_med=CROSS_KERNEL_5, dilation_kernel_near=CROSS_KERNEL_7, extrapolate=False, blur_type='bilateral', show_process=False):
depths_in = np.float32(depth_map)
valid_pixels_near = (depths_in > 0.1) & (depths_in <= 1... | ['def', 'fill_in_multiscale(depth_map,', 'max_depth=100.0,', 'dilation_kernel_far=CROSS_KERNEL_3,', 'dilation_kernel_med=CROSS_KERNEL_5,', 'dilation_kernel_near=CROSS_KERNEL_7,', 'extrapolate=False,', "blur_type='bilateral',", 'show_process=False):', 'depths_in', '=', 'np.float32(depth_map)', 'valid_pixels_near', '=', ... | 521,180 |
instadeepai/jumanji | env_not_smoke.py | make_random_select_action_fn | make_random_select_action_fn | Create select action function that chooses random actions. | [
"Create",
"select",
"action",
"function",
"that",
"chooses",
"random",
"actions."
] | def make_random_select_action_fn(action_spec: Union[specs.BoundedArray, specs.DiscreteArray, specs.MultiDiscreteArray]) -> SelectActionFn:
def select_action(key: chex.PRNGKey, state: chex.ArrayTree) -> chex.ArrayTree:
del state
if isinstance(action_spec, specs.DiscreteArray) or isinstance(action_sp... | ['def', 'make_random_select_action_fn(action_spec:', 'Union[specs.BoundedArray,', 'specs.DiscreteArray,', 'specs.MultiDiscreteArray])', '->', 'SelectActionFn:', 'def', 'select_action(key:', 'chex.PRNGKey,', 'state:', 'chex.ArrayTree)', '->', 'chex.ArrayTree:', 'del', 'state', 'if', 'isinstance(action_spec,', 'specs.Dis... | 594,553 |
dreasysnail/deconv_paragraph_represention | rougescore.py | rouge_n | rouge_n | Compute the ROUGE-N score of a peer with respect to one or more models, for a given value of `n`. | [
"Compute",
"the",
"ROUGE-N",
"score",
"of",
"a",
"peer",
"with",
"respect",
"to",
"one",
"or",
"more",
"models,",
"for",
"a",
"given",
"value",
"of",
"`n`."
] | def rouge_n(peer, models, n, alpha):
matches = 0
recall_total = 0
peer_counter = _ngram_counts(peer, n)
for model in models:
model_counter = _ngram_counts(model, n)
matches += _counter_overlap(peer_counter, model_counter)
recall_total += _ngram_count(model, n)
precision_total... | ['def', 'rouge_n(peer,', 'models,', 'n,', 'alpha):', 'matches', '=', '0', 'recall_total', '=', '0', 'peer_counter', '=', '_ngram_counts(peer,', 'n)', 'for', 'model', 'in', 'models:', 'model_counter', '=', '_ngram_counts(model,', 'n)', 'matches', '+=', '_counter_overlap(peer_counter,', 'model_counter)', 'recall_total', ... | 127,156 |
ldkong1205/LaserMix | base_box3d.py | BaseInstance3DBoxes.bottom_height | bottom_height | Tensor: A vector with bottom height of each box in shape (N, ). | [
"Tensor:",
"A",
"vector",
"with",
"bottom",
"height",
"of",
"each",
"box",
"in",
"shape",
"(N,",
")."
] | def bottom_height(self) -> Tensor:
return self.tensor[:, 2] | ['def', 'bottom_height(self)', '->', 'Tensor:', 'return', 'self.tensor[:,', '2]'] | 624,330 |
thaines/helit | mask_stats.py | MaskStats.getFMeasureAvg | getFMeasureAvg | Given an inclusive frame range returns the average of the f-measure for that range. | [
"Given",
"an",
"inclusive",
"frame",
"range",
"returns",
"the",
"average",
"of",
"the",
"f-measure",
"for",
"that",
"range."
] | def getFMeasureAvg(self, start, end):
ret = 0.0
for i in xrange(start, end + 1):
val = self.getFMeasure(i)
ret += (val - ret) / float(i + 1 - start)
return ret | ['def', 'getFMeasureAvg(self,', 'start,', 'end):', 'ret', '=', '0.0', 'for', 'i', 'in', 'xrange(start,', 'end', '+', '1):', 'val', '=', 'self.getFMeasure(i)', 'ret', '+=', '(val', '-', 'ret)', '/', 'float(i', '+', '1', '-', 'start)', 'return', 'ret'] | 592,790 |
astooke/accel_rl | ext.py | compact | compact | For a dictionary this removes all None values, and for a list this removes all None elements; otherwise it returns the input itself. | [
"For",
"a",
"dictionary",
"this",
"removes",
"all",
"None",
"values,",
"and",
"for",
"a",
"list",
"this",
"removes",
"all",
"None",
"elements;",
"otherwise",
"it",
"returns",
"the",
"input",
"itself."
] | def compact(x):
if isinstance(x, dict):
return dict(((k, v) for (k, v) in x.items() if v is not None))
elif isinstance(x, list):
return [elem for elem in x if elem is not None]
return x | ['def', 'compact(x):', 'if', 'isinstance(x,', 'dict):', 'return', 'dict(((k,', 'v)', 'for', '(k,', 'v)', 'in', 'x.items()', 'if', 'v', 'is', 'not', 'None))', 'elif', 'isinstance(x,', 'list):', 'return', '[elem', 'for', 'elem', 'in', 'x', 'if', 'elem', 'is', 'not', 'None]', 'return', 'x'] | 406,913 |
devashish-patel/webcam-motion-detector | console_widget.py | ConsoleWidget.prompt_to_top | prompt_to_top | Moves the prompt to the top of the viewport. | [
"Moves",
"the",
"prompt",
"to",
"the",
"top",
"of",
"the",
"viewport."
] | def prompt_to_top(self):
if not self._executing:
prompt_cursor = self._get_prompt_cursor()
if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():
self._set_cursor(prompt_cursor)
self._set_top_cursor(prompt_cursor) | ['def', 'prompt_to_top(self):', 'if', 'not', 'self._executing:', 'prompt_cursor', '=', 'self._get_prompt_cursor()', 'if', 'self._get_cursor().blockNumber()', '<', 'prompt_cursor.blockNumber():', 'self._set_cursor(prompt_cursor)', 'self._set_top_cursor(prompt_cursor)'] | 984,411 |
jialeli1/lidarseg3d | fastai_optim.py | OptimWrapper.read_val | read_val | Read a hyperparameter `key` in the optimizer dictionary. | [
"Read",
"a",
"hyperparameter",
"`key`",
"in",
"the",
"optimizer",
"dictionary."
] | def read_val(self, key: str):
val = [pg[key] for pg in self.opt.param_groups[::2]]
if is_tuple(val[0]):
val = ([o[0] for o in val], [o[1] for o in val])
return val | ['def', 'read_val(self,', 'key:', 'str):', 'val', '=', '[pg[key]', 'for', 'pg', 'in', 'self.opt.param_groups[::2]]', 'if', 'is_tuple(val[0]):', 'val', '=', '([o[0]', 'for', 'o', 'in', 'val],', '[o[1]', 'for', 'o', 'in', 'val])', 'return', 'val'] | 601,555 |
arshpreetsingh/quantopian-machinelearning | testing.py | HTMLTreeBuilderSmokeTest.test_head_tag_between_head_and_body | test_head_tag_between_head_and_body | Prevent recurrence of a bug in the html5lib treebuilder. | [
"Prevent",
"recurrence",
"of",
"a",
"bug",
"in",
"the",
"html5lib",
"treebuilder."
] | def test_head_tag_between_head_and_body(self):
content = '<html><head></head>\n <link></link>\n <body>foo</body>\n</html>\n'
soup = self.soup(content)
self.assertNotEqual(None, soup.html.body)
self.assertConnectedness(soup) | ['def', 'test_head_tag_between_head_and_body(self):', 'content', '=', "'<html><head></head>\\n", '<link></link>\\n', "<body>foo</body>\\n</html>\\n'", 'soup', '=', 'self.soup(content)', 'self.assertNotEqual(None,', 'soup.html.body)', 'self.assertConnectedness(soup)'] | 816,534 |
Eric3911/OpenAGI | text_classification_model.py | TextClassificationModel.validation_step | validation_step | Lightning calls this inside the validation loop with the data from the validation dataloader passed in as `batch`. | [
"Lightning",
"calls",
"this",
"inside",
"the",
"validation",
"loop",
"with",
"the",
"data",
"from",
"the",
"validation",
"dataloader",
"passed",
"in",
"as",
"`batch`."
] | def validation_step(self, batch, batch_idx):
(input_ids, input_type_ids, input_mask, labels) = batch
logits = self.forward(input_ids=input_ids, token_type_ids=input_type_ids, attention_mask=input_mask)
val_loss = self.loss(logits=logits, labels=labels)
preds = torch.argmax(logits, axis=-1)
(tp, fn, ... | ['def', 'validation_step(self,', 'batch,', 'batch_idx):', '(input_ids,', 'input_type_ids,', 'input_mask,', 'labels)', '=', 'batch', 'logits', '=', 'self.forward(input_ids=input_ids,', 'token_type_ids=input_type_ids,', 'attention_mask=input_mask)', 'val_loss', '=', 'self.loss(logits=logits,', 'labels=labels)', 'preds', ... | 273,656 |
nicknochnack/RealTimeSignLanguageTFJS | factory_3d.py | build_model | build_model | Builds backbone from a config. | [
"Builds",
"backbone",
"from",
"a",
"config."
] | def build_model(model_type: str, input_specs: tf.keras.layers.InputSpec, model_config: video_classification_cfg.hyperparams.Config, num_classes: int, l2_regularizer: tf.keras.regularizers.Regularizer=None):
model_builder = registry.lookup(_REGISTERED_MODEL_CLS, model_type)
return model_builder(input_specs, mode... | ['def', 'build_model(model_type:', 'str,', 'input_specs:', 'tf.keras.layers.InputSpec,', 'model_config:', 'video_classification_cfg.hyperparams.Config,', 'num_classes:', 'int,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None):', 'model_builder', '=', 'registry.lookup(_REGISTERED_MODEL_CLS,', 'model_type)', ... | 850,780 |
befelix/safe_learning | configuration.py | Configuration.np_dtype | np_dtype | Return the numpy dtype. | [
"Return",
"the",
"numpy",
"dtype."
] | def np_dtype(self):
return self.dtype.as_numpy_dtype | ['def', 'np_dtype(self):', 'return', 'self.dtype.as_numpy_dtype'] | 328,291 |
FahadTComsats/Natural-Language-Processing | Datum.py | levenshtein | levenshtein | Calculate the Damerau-Levenshtein distance between sequences. | [
"Calculate",
"the",
"Damerau-Levenshtein",
"distance",
"between",
"sequences."
] | def levenshtein(seq1, seq2):
oneago = None
thisrow = range(1, len(seq2) + 1) + [0]
for x in xrange(len(seq1)):
(twoago, oneago, thisrow) = (oneago, thisrow, [0] * len(seq2) + [x + 1])
for y in xrange(len(seq2)):
delcost = oneago[y] + 1
addcost = thisrow[y - 1] + 1
... | ['def', 'levenshtein(seq1,', 'seq2):', 'oneago', '=', 'None', 'thisrow', '=', 'range(1,', 'len(seq2)', '+', '1)', '+', '[0]', 'for', 'x', 'in', 'xrange(len(seq1)):', '(twoago,', 'oneago,', 'thisrow)', '=', '(oneago,', 'thisrow,', '[0]', '*', 'len(seq2)', '+', '[x', '+', '1])', 'for', 'y', 'in', 'xrange(len(seq2)):', 'd... | 683,365 |
sfailsthy/char-rnn-tensorflow | dataset.py | IteratorInitializerHook.after_create_session | after_create_session | Initialise the iterator after the session has been created. | [
"Initialise",
"the",
"iterator",
"after",
"the",
"session",
"has",
"been",
"created."
] | def after_create_session(self, session, coord):
self.iterator_initializer_func(session) | ['def', 'after_create_session(self,', 'session,', 'coord):', 'self.iterator_initializer_func(session)'] | 104,658 |
sek788432/Waymo-2D-Object-Detection | model.py | Model.inference | inference | Runs depth or egomotion inference from placeholders. | [
"Runs",
"depth",
"or",
"egomotion",
"inference",
"from",
"placeholders."
] | def inference(self, inputs, sess, mode):
fetches = {}
if mode == 'depth':
fetches['depth'] = self.est_depth
inputs_ph = self.inputs_depth
if mode == 'egomotion':
fetches['egomotion'] = self.est_egomotion
inputs_ph = self.inputs_egomotion
results = sess.run(fetches, feed_d... | ['def', 'inference(self,', 'inputs,', 'sess,', 'mode):', 'fetches', '=', '{}', 'if', 'mode', '==', "'depth':", "fetches['depth']", '=', 'self.est_depth', 'inputs_ph', '=', 'self.inputs_depth', 'if', 'mode', '==', "'egomotion':", "fetches['egomotion']", '=', 'self.est_egomotion', 'inputs_ph', '=', 'self.inputs_egomotion... | 975,887 |
43Carrig/recurrent_neural_networks_practice | util.py | get_regularization_losses | get_regularization_losses | Gets the list of regularization losses. | [
"Gets",
"the",
"list",
"of",
"regularization",
"losses."
] | def get_regularization_losses(scope=None):
return ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES, scope) | ['def', 'get_regularization_losses(scope=None):', 'return', 'ops.get_collection(ops.GraphKeys.REGULARIZATION_LOSSES,', 'scope)'] | 339,319 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | pytorch_train_spectrograms.py | create_weights | create_weights | Create the weights ('grayzones') for a given label. | [
"Create",
"the",
"weights",
"('grayzones')",
"for",
"a",
"given",
"label."
] | def create_weights(label, start_size=40, end_size=3):
a = np.logical_xor(label, np.roll(label, 1))
b = np.cumsum(a) % 2
if start_size == 0:
c = np.zeros(label.shape)
else:
c = np.convolve(a * b, np.hstack((np.zeros(start_size - 1), np.ones(start_size))), mode='same')
if end_size == 0... | ['def', 'create_weights(label,', 'start_size=40,', 'end_size=3):', 'a', '=', 'np.logical_xor(label,', 'np.roll(label,', '1))', 'b', '=', 'np.cumsum(a)', '%', '2', 'if', 'start_size', '==', '0:', 'c', '=', 'np.zeros(label.shape)', 'else:', 'c', '=', 'np.convolve(a', '*', 'b,', 'np.hstack((np.zeros(start_size', '-', '1),... | 12,434 |
tensorflow/agents | episodic_replay_buffer.py | EpisodicReplayBuffer.add_batch | add_batch | Adds a batch of single steps for the corresponding episodes IDs. | [
"Adds",
"a",
"batch",
"of",
"single",
"steps",
"for",
"the",
"corresponding",
"episodes",
"IDs."
] | def add_batch(self, items, episode_ids):
episode_ids.shape.assert_has_rank(1)
with tf.device(self._device):
with tf.name_scope('add_batch'):
begin_episode = self._begin_episode_fn(items)
end_episode = self._end_episode_fn(items)
batch_episode_ids = self._get_batch_epi... | ['def', 'add_batch(self,', 'items,', 'episode_ids):', 'episode_ids.shape.assert_has_rank(1)', 'with', 'tf.device(self._device):', 'with', "tf.name_scope('add_batch'):", 'begin_episode', '=', 'self._begin_episode_fn(items)', 'end_episode', '=', 'self._end_episode_fn(items)', 'batch_episode_ids', '=', 'self._get_batch_ep... | 23,618 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | util.py | vectorize | vectorize | Vectorize input features wrt a label column. | [
"Vectorize",
"input",
"features",
"wrt",
"a",
"label",
"column."
] | def vectorize(df, label_column):
feature_names = []
for feature_name in df.columns.values:
if feature_name != label_column:
if label_column not in feature_names:
feature_names.append(label_column)
inputs = df[feature_names].index
return inputs | ['def', 'vectorize(df,', 'label_column):', 'feature_names', '=', '[]', 'for', 'feature_name', 'in', 'df.columns.values:', 'if', 'feature_name', '!=', 'label_column:', 'if', 'label_column', 'not', 'in', 'feature_names:', 'feature_names.append(label_column)', 'inputs', '=', 'df[feature_names].index', 'return', 'inputs'] | 15,818 |
jeromewang-github/computer_vision | setup.py | UploadCommand.status | status | Prints things in bold. | [
"Prints",
"things",
"in",
"bold."
] | def status(s):
print('\x1b[1m{0}\x1b[0m'.format(s)) | ['def', 'status(s):', "print('\\x1b[1m{0}\\x1b[0m'.format(s))"] | 474,601 |
omarmhaimdat/twitter_nlp_native_swift | lexer.py | compile_rules | compile_rules | Compiles all the rules from the environment into a list of rules. | [
"Compiles",
"all",
"the",
"rules",
"from",
"the",
"environment",
"into",
"a",
"list",
"of",
"rules."
] | def compile_rules(environment):
e = re.escape
rules = [(len(environment.comment_start_string), 'comment', e(environment.comment_start_string)), (len(environment.block_start_string), 'block', e(environment.block_start_string)), (len(environment.variable_start_string), 'variable', e(environment.variable_start_str... | ['def', 'compile_rules(environment):', 'e', '=', 're.escape', 'rules', '=', '[(len(environment.comment_start_string),', "'comment',", 'e(environment.comment_start_string)),', '(len(environment.block_start_string),', "'block',", 'e(environment.block_start_string)),', '(len(environment.variable_start_string),', "'variabl... | 953,956 |
43Carrig/recurrent_neural_networks_practice | op_util.py | get_op_symbol | get_op_symbol | Given an AST node object, returns a string containing the symbol. | [
"Given",
"an",
"AST",
"node",
"object,",
"returns",
"a",
"string",
"containing",
"the",
"symbol."
] | def get_op_symbol(obj, fmt='%s', symbol_data=symbol_data, type=type):
return fmt % symbol_data[type(obj)] | ['def', 'get_op_symbol(obj,', "fmt='%s',", 'symbol_data=symbol_data,', 'type=type):', 'return', 'fmt', '%', 'symbol_data[type(obj)]'] | 309,777 |
matsu0228/nlp-jp | test_doc2vec.py | TestDoc2VecModel.test_dbow_hs | test_dbow_hs | Test DBOW doc2vec training. | [
"Test",
"DBOW",
"doc2vec",
"training."
] | def test_dbow_hs(self):
model = doc2vec.Doc2Vec(list_corpus, dm=0, hs=1, negative=0, min_count=2, iter=20)
self.model_sanity(model) | ['def', 'test_dbow_hs(self):', 'model', '=', 'doc2vec.Doc2Vec(list_corpus,', 'dm=0,', 'hs=1,', 'negative=0,', 'min_count=2,', 'iter=20)', 'self.model_sanity(model)'] | 786,079 |
pytorch/vision | ps_roi_align.py | ps_roi_align | ps_roi_align | Performs Position-Sensitive Region of Interest (RoI) Align operator mentioned in Light-Head R-CNN. | [
"Performs",
"Position-Sensitive",
"Region",
"of",
"Interest",
"(RoI)",
"Align",
"operator",
"mentioned",
"in",
"Light-Head",
"R-CNN."
] | def ps_roi_align(input: Tensor, boxes: Tensor, output_size: int, spatial_scale: float=1.0, sampling_ratio: int=-1) -> Tensor:
if not torch.jit.is_scripting() and (not torch.jit.is_tracing()):
_log_api_usage_once(ps_roi_align)
_assert_has_ops()
check_roi_boxes_shape(boxes)
rois = boxes
output... | ['def', 'ps_roi_align(input:', 'Tensor,', 'boxes:', 'Tensor,', 'output_size:', 'int,', 'spatial_scale:', 'float=1.0,', 'sampling_ratio:', 'int=-1)', '->', 'Tensor:', 'if', 'not', 'torch.jit.is_scripting()', 'and', '(not', 'torch.jit.is_tracing()):', '_log_api_usage_once(ps_roi_align)', '_assert_has_ops()', 'check_roi_b... | 959,206 |
openvinotoolkit/training_extensions | detcon_loss.py | DetConLoss.get_distributed_tensors | get_distributed_tensors | Grab tensors across replicas during distributed training. | [
"Grab",
"tensors",
"across",
"replicas",
"during",
"distributed",
"training."
] | def get_distributed_tensors(self, target1, target2, batch_size, num_samples, num_features, device):
if dist.is_initialized() and self.use_replicator_loss:
world_size = dist.get_world_size()
target1_large = [torch.zeros_like(target1) for _ in range(world_size)]
target2_large = [torch.zeros_li... | ['def', 'get_distributed_tensors(self,', 'target1,', 'target2,', 'batch_size,', 'num_samples,', 'num_features,', 'device):', 'if', 'dist.is_initialized()', 'and', 'self.use_replicator_loss:', 'world_size', '=', 'dist.get_world_size()', 'target1_large', '=', '[torch.zeros_like(target1)', 'for', '_', 'in', 'range(world_s... | 918,277 |
rll/rllab | box2d_env.py | Box2DEnv.step | step | Note: override this method with great care, as it post-processes the observations, etc. | [
"Note:",
"override",
"this",
"method",
"with",
"great",
"care,",
"as",
"it",
"post-processes",
"the",
"observations,",
"etc."
] | def step(self, action):
reward_computer = self.compute_reward(action)
action = self._inject_action_noise(action)
for _ in range(self.frame_skip):
self.forward_dynamics(action)
next(reward_computer)
reward = next(reward_computer)
self._invalidate_state_caches()
done = self.is_current_... | ['def', 'step(self,', 'action):', 'reward_computer', '=', 'self.compute_reward(action)', 'action', '=', 'self._inject_action_noise(action)', 'for', '_', 'in', 'range(self.frame_skip):', 'self.forward_dynamics(action)', 'next(reward_computer)', 'reward', '=', 'next(reward_computer)', 'self._invalidate_state_caches()', '... | 333,031 |
Kvatsx/Artificial-Intelligence-Assignments | checkpoints.py | GenericCheckpointsMixin.create_file_checkpoint | create_file_checkpoint | Create a checkpoint of the current state of a file Returns a checkpoint model for the new checkpoint. | [
"Create",
"a",
"checkpoint",
"of",
"the",
"current",
"state",
"of",
"a",
"file",
"Returns",
"a",
"checkpoint",
"model",
"for",
"the",
"new",
"checkpoint."
] | def create_file_checkpoint(self, content, format, path):
raise NotImplementedError('must be implemented in a subclass') | ['def', 'create_file_checkpoint(self,', 'content,', 'format,', 'path):', 'raise', "NotImplementedError('must", 'be', 'implemented', 'in', 'a', "subclass')"] | 2,219 |
srai-lab/srai | conftest.py | joint_multiindex | joint_multiindex | Get MultiIndex for joint GeoDataFrame. | [
"Get",
"MultiIndex",
"for",
"joint",
"GeoDataFrame."
] | def joint_multiindex() -> pd.MultiIndex:
return pd.MultiIndex.from_tuples([(0, 2), (0, 3), (1, 2), (0, 0), (3, 0), (2, 1)], names=[REGIONS_INDEX, FEATURES_INDEX]) | ['def', 'joint_multiindex()', '->', 'pd.MultiIndex:', 'return', 'pd.MultiIndex.from_tuples([(0,', '2),', '(0,', '3),', '(1,', '2),', '(0,', '0),', '(3,', '0),', '(2,', '1)],', 'names=[REGIONS_INDEX,', 'FEATURES_INDEX])'] | 372,000 |
zihuitang/medical_AI_platform | test_unparse.py | read_pyfile | read_pyfile | Read and return the contents of a Python source file (as a string), taking into account the file encoding. | [
"Read",
"and",
"return",
"the",
"contents",
"of",
"a",
"Python",
"source",
"file",
"(as",
"a",
"string),",
"taking",
"into",
"account",
"the",
"file",
"encoding."
] | def read_pyfile(filename):
with open(filename, 'rb') as pyfile:
encoding = tokenize.detect_encoding(pyfile.readline)[0]
with open(filename, 'r', encoding=encoding) as pyfile:
source = pyfile.read()
return source | ['def', 'read_pyfile(filename):', 'with', 'open(filename,', "'rb')", 'as', 'pyfile:', 'encoding', '=', 'tokenize.detect_encoding(pyfile.readline)[0]', 'with', 'open(filename,', "'r',", 'encoding=encoding)', 'as', 'pyfile:', 'source', '=', 'pyfile.read()', 'return', 'source'] | 283,869 |
myothida/Supervised-Machine-Learning | protocol.py | rich_cast | rich_cast | Cast an object to a renderable by calling __rich__ if present. | [
"Cast",
"an",
"object",
"to",
"a",
"renderable",
"by",
"calling",
"__rich__",
"if",
"present."
] | def rich_cast(renderable: object) -> 'RenderableType':
from pip._vendor.rich.console import RenderableType
rich_visited_set: Set[type] = set()
while hasattr(renderable, '__rich__') and (not isclass(renderable)):
if hasattr(renderable, _GIBBERISH):
return repr(renderable)
cast_met... | ['def', 'rich_cast(renderable:', 'object)', '->', "'RenderableType':", 'from', 'pip._vendor.rich.console', 'import', 'RenderableType', 'rich_visited_set:', 'Set[type]', '=', 'set()', 'while', 'hasattr(renderable,', "'__rich__')", 'and', '(not', 'isclass(renderable)):', 'if', 'hasattr(renderable,', '_GIBBERISH):', 'retu... | 445,059 |
thu-ml/tianshou | mapolicy.py | MultiAgentPolicyManager.replace_policy | replace_policy | Replace the "agent_id"th policy in this manager. | [
"Replace",
"the",
"\"agent_id\"th",
"policy",
"in",
"this",
"manager."
] | def replace_policy(self, policy: BasePolicy, agent_id: int) -> None:
policy.set_agent_id(agent_id)
self.policies[agent_id] = policy | ['def', 'replace_policy(self,', 'policy:', 'BasePolicy,', 'agent_id:', 'int)', '->', 'None:', 'policy.set_agent_id(agent_id)', 'self.policies[agent_id]', '=', 'policy'] | 355,283 |
googleapis/python-aiplatform | async_client.py | IndexEndpointServiceAsyncClient.from_service_account_file | from_service_account_file | Creates an instance of this client using the provided credentials file. | [
"Creates",
"an",
"instance",
"of",
"this",
"client",
"using",
"the",
"provided",
"credentials",
"file."
] | def from_service_account_file(cls, filename: str, *args, **kwargs):
return IndexEndpointServiceClient.from_service_account_file.__func__(IndexEndpointServiceAsyncClient, filename, *args, **kwargs) | ['def', 'from_service_account_file(cls,', 'filename:', 'str,', '*args,', '**kwargs):', 'return', 'IndexEndpointServiceClient.from_service_account_file.__func__(IndexEndpointServiceAsyncClient,', 'filename,', '*args,', '**kwargs)'] | 810,711 |
intel/neural-compressor | tf_criteria.py | register_criterion | register_criterion | Register a criterion to the registry. | [
"Register",
"a",
"criterion",
"to",
"the",
"registry."
] | def register_criterion(name):
def register(criterion):
CRITERIA[name] = criterion
return criterion
return register | ['def', 'register_criterion(name):', 'def', 'register(criterion):', 'CRITERIA[name]', '=', 'criterion', 'return', 'criterion', 'return', 'register'] | 738,063 |
neokarn/computer_vision | image_iter.py | FaceImageIter.augmentation_transform | augmentation_transform | Transforms input data with specified augmentation. | [
"Transforms",
"input",
"data",
"with",
"specified",
"augmentation."
] | def augmentation_transform(self, data):
for aug in self.auglist:
data = [ret for src in data for ret in aug(src)]
return data | ['def', 'augmentation_transform(self,', 'data):', 'for', 'aug', 'in', 'self.auglist:', 'data', '=', '[ret', 'for', 'src', 'in', 'data', 'for', 'ret', 'in', 'aug(src)]', 'return', 'data'] | 500,283 |
michaelhush/M-LOOP | utilities.py | dict_to_txt_file | dict_to_txt_file | Method for writing a dict to a file with syntax similar to how files are input. | [
"Method",
"for",
"writing",
"a",
"dict",
"to",
"a",
"file",
"with",
"syntax",
"similar",
"to",
"how",
"files",
"are",
"input."
] | def dict_to_txt_file(tdict, filename):
with open(filename, 'w') as out_file:
for key in tdict:
out_file.write(str(key) + '=' + repr(tdict[key]).replace('\n', '').replace('\r', '') + '\n') | ['def', 'dict_to_txt_file(tdict,', 'filename):', 'with', 'open(filename,', "'w')", 'as', 'out_file:', 'for', 'key', 'in', 'tdict:', 'out_file.write(str(key)', '+', "'='", '+', "repr(tdict[key]).replace('\\n',", "'').replace('\\r',", "'')", '+', "'\\n')"] | 619,935 |
deepmind/dm_control | renderer.py | RenderSettings.apply_settings | apply_settings | Applies settings to the specified scene. | [
"Applies",
"settings",
"to",
"the",
"specified",
"scene."
] | def apply_settings(self, scene):
scene.stereo = self._stereo_mode
scene.flags[:] = self._render_flags[:] | ['def', 'apply_settings(self,', 'scene):', 'scene.stereo', '=', 'self._stereo_mode', 'scene.flags[:]', '=', 'self._render_flags[:]'] | 165,661 |
rifqind/Agent-Programs-3KS1 | inputtransformer.py | CoroutineInputTransformer.reset | reset | Return, transformed any lines that the transformer has accumulated, and reset its internal state. | [
"Return,",
"transformed",
"any",
"lines",
"that",
"the",
"transformer",
"has",
"accumulated,",
"and",
"reset",
"its",
"internal",
"state."
] | def reset(self):
return self.coro.send(None) | ['def', 'reset(self):', 'return', 'self.coro.send(None)'] | 41,065 |
omni-us/squeezedet-keras | utils.py | safe_exp_np | safe_exp_np | Safe exponential function for numpy tensors. | [
"Safe",
"exponential",
"function",
"for",
"numpy",
"tensors."
] | def safe_exp_np(w, thresh):
slope = np.exp(thresh)
lin_bool = w > thresh
lin_region = lin_bool.astype(float)
lin_out = slope * (w - thresh + 1.0)
exp_out = np.exp(np.where(lin_bool, np.zeros_like(w), w))
out = lin_region * lin_out + (1.0 - lin_region) * exp_out
return out | ['def', 'safe_exp_np(w,', 'thresh):', 'slope', '=', 'np.exp(thresh)', 'lin_bool', '=', 'w', '>', 'thresh', 'lin_region', '=', 'lin_bool.astype(float)', 'lin_out', '=', 'slope', '*', '(w', '-', 'thresh', '+', '1.0)', 'exp_out', '=', 'np.exp(np.where(lin_bool,', 'np.zeros_like(w),', 'w))', 'out', '=', 'lin_region', '*', ... | 897,257 |
microsoft/nni | model_speedup.py | ModelSpeedup.placeholder | placeholder | Override the execution for 'placeholder' ops. | [
"Override",
"the",
"execution",
"for",
"'placeholder'",
"ops."
] | def placeholder(self, target: Target, args, kwargs) -> Any:
return self.arg_dict[target] | ['def', 'placeholder(self,', 'target:', 'Target,', 'args,', 'kwargs)', '->', 'Any:', 'return', 'self.arg_dict[target]'] | 728,537 |
Xianpeng919/MonoCon | nuscenes_mono_dataset.py | output_to_nusc_box | output_to_nusc_box | Convert the output to the box class in the nuScenes. | [
"Convert",
"the",
"output",
"to",
"the",
"box",
"class",
"in",
"the",
"nuScenes."
] | def output_to_nusc_box(detection):
box3d = detection['boxes_3d']
scores = detection['scores_3d'].numpy()
labels = detection['labels_3d'].numpy()
attrs = None
if 'attrs_3d' in detection:
attrs = detection['attrs_3d'].numpy()
box_gravity_center = box3d.gravity_center.numpy()
box_dims =... | ['def', 'output_to_nusc_box(detection):', 'box3d', '=', "detection['boxes_3d']", 'scores', '=', "detection['scores_3d'].numpy()", 'labels', '=', "detection['labels_3d'].numpy()", 'attrs', '=', 'None', 'if', "'attrs_3d'", 'in', 'detection:', 'attrs', '=', "detection['attrs_3d'].numpy()", 'box_gravity_center', '=', 'box3... | 654,469 |
chribsen/simple-machine-learning-examples | test_basic.py | test_pick_best | test_pick_best | Test the wheel ranking algorithm. | [
"Test",
"the",
"wheel",
"ranking",
"algorithm."
] | def test_pick_best():
def get_tags(res):
info = res[-1].parsed_filename.groupdict()
return (info['pyver'], info['abi'], info['plat'])
cand_tags = [('py27', 'noabi', 'noarch'), ('py26', 'noabi', 'noarch'), ('cp27', 'noabi', 'linux_i686'), ('cp26', 'noabi', 'linux_i686'), ('cp27', 'noabi', 'linux... | ['def', 'test_pick_best():', 'def', 'get_tags(res):', 'info', '=', 'res[-1].parsed_filename.groupdict()', 'return', "(info['pyver'],", "info['abi'],", "info['plat'])", 'cand_tags', '=', "[('py27',", "'noabi',", "'noarch'),", "('py26',", "'noabi',", "'noarch'),", "('cp27',", "'noabi',", "'linux_i686'),", "('cp26',", "'n... | 883,092 |
thaines/helit | params_sets.py | ParamsRange.getKernelList | getKernelList | Returns the list of kernels. | [
"Returns",
"the",
"list",
"of",
"kernels."
] | def getKernelList(self):
return self.kernel | ['def', 'getKernelList(self):', 'return', 'self.kernel'] | 592,561 |
haruiz/CvStudio | imageViewer.py | ImageViewer.zoomFactor | zoomFactor | Zoom scale value (*float*). | [
"Zoom",
"scale",
"value",
"(*float*)."
] | def zoomFactor(self):
return self._view.zoomFactor | ['def', 'zoomFactor(self):', 'return', 'self._view.zoomFactor'] | 523,701 |
RasaHQ/rasa | domain.py | Domain.from_path | from_path | Loads the `Domain` from a path. | [
"Loads",
"the",
"`Domain`",
"from",
"a",
"path."
] | def from_path(cls, path: Union[Text, Path]) -> 'Domain':
path = os.path.abspath(path)
if os.path.isfile(path):
domain = cls.from_file(path)
elif os.path.isdir(path):
domain = cls.from_directory(path)
else:
raise InvalidDomain("Failed to load domain specification from '{}'. File n... | ['def', 'from_path(cls,', 'path:', 'Union[Text,', 'Path])', '->', "'Domain':", 'path', '=', 'os.path.abspath(path)', 'if', 'os.path.isfile(path):', 'domain', '=', 'cls.from_file(path)', 'elif', 'os.path.isdir(path):', 'domain', '=', 'cls.from_directory(path)', 'else:', 'raise', 'InvalidDomain("Failed', 'to', 'load', 'd... | 837,392 |
microsoft/maro | scatter.py | multiplication_worker | multiplication_worker | The main worker logic includes initialize proxy and handle multiply jobs from the master. | [
"The",
"main",
"worker",
"logic",
"includes",
"initialize",
"proxy",
"and",
"handle",
"multiply",
"jobs",
"from",
"the",
"master."
] | def multiplication_worker(group_name):
proxy = Proxy(group_name=group_name, component_type='multiply_worker', expected_peers={'master': 1})
msg = proxy.receive_once()
print(f'{proxy.name} receive message from {msg.source}. the payload is {msg.body}.')
if msg.tag == 'job':
replied_payload = np.pr... | ['def', 'multiplication_worker(group_name):', 'proxy', '=', 'Proxy(group_name=group_name,', "component_type='multiply_worker',", "expected_peers={'master':", '1})', 'msg', '=', 'proxy.receive_once()', "print(f'{proxy.name}", 'receive', 'message', 'from', '{msg.source}.', 'the', 'payload', 'is', "{msg.body}.')", 'if', '... | 628,122 |
aeon-toolkit/aeon | _base.py | BaseForecaster.fh | fh | Forecasting horizon that was passed. | [
"Forecasting",
"horizon",
"that",
"was",
"passed."
] | def fh(self):
if self._fh is None:
raise ValueError('No `fh` has been set yet, please specify `fh` in `fit` or `predict`')
return self._fh | ['def', 'fh(self):', 'if', 'self._fh', 'is', 'None:', 'raise', "ValueError('No", '`fh`', 'has', 'been', 'set', 'yet,', 'please', 'specify', '`fh`', 'in', '`fit`', 'or', "`predict`')", 'return', 'self._fh'] | 399,547 |
google-research/scenic | base_clip_mlp_bert_mlp.py | get_config | get_config | Returns the experiment configuration. | [
"Returns",
"the",
"experiment",
"configuration."
] | def get_config(run_local: str='') -> ml_collections.ConfigDict:
config = base_clip_bert.get_config(run_local)
config.experiment_name = 'clip_mlp_bert_mlp'
del config.model.image_encoder.config_name
del config.model.text_encoder.config_name
config.model.num_layers = 1
config.model.hidden_size = 1... | ['def', 'get_config(run_local:', "str='')", '->', 'ml_collections.ConfigDict:', 'config', '=', 'base_clip_bert.get_config(run_local)', 'config.experiment_name', '=', "'clip_mlp_bert_mlp'", 'del', 'config.model.image_encoder.config_name', 'del', 'config.model.text_encoder.config_name', 'config.model.num_layers', '=', '1... | 846,880 |
flavioschneider/rl-transfer- | replay_buffer.py | ReplayBuffer.store_episode | store_episode | Add an episode to the buffer. | [
"Add",
"an",
"episode",
"to",
"the",
"buffer."
] | def store_episode(self):
episode_buffer = self._convert_episode_to_batch_major()
episode_batch_size = len(episode_buffer['observation'])
idx = self._get_storage_idx(episode_batch_size)
for key in self._buffer:
self._buffer[key][idx] = episode_buffer[key]
self._n_transitions_stored = min(self... | ['def', 'store_episode(self):', 'episode_buffer', '=', 'self._convert_episode_to_batch_major()', 'episode_batch_size', '=', "len(episode_buffer['observation'])", 'idx', '=', 'self._get_storage_idx(episode_batch_size)', 'for', 'key', 'in', 'self._buffer:', 'self._buffer[key][idx]', '=', 'episode_buffer[key]', 'self._n_t... | 861,245 |
paschalidoud/hierarchical_primitives | filter_sqs.py | qos_less | qos_less | Split iff qos is less than qos_th. | [
"Split",
"iff",
"qos",
"is",
"less",
"than",
"qos_th."
] | def qos_less(qos_th):
def inner(P, depth, idx):
return P[depth].qos[0, idx] < qos_th
return inner | ['def', 'qos_less(qos_th):', 'def', 'inner(P,', 'depth,', 'idx):', 'return', 'P[depth].qos[0,', 'idx]', '<', 'qos_th', 'return', 'inner'] | 206,482 |
sek788432/Waymo-2D-Object-Detection | preprocess_pretrain_data.py | get_input_fn | get_input_fn | Gets the input function. | [
"Gets",
"the",
"input",
"function."
] | def get_input_fn(tfrecord_dir, split, bsz_per_host, seq_len, reuse_len, bi_data, num_hosts=1, num_core_per_host=1, perm_size=None, mask_alpha=None, mask_beta=None, uncased=False, num_passes=None, use_bfloat16=False, num_predict=None):
record_glob_base = format_filename(prefix='record_info-{}-*'.format(split), bsz_p... | ['def', 'get_input_fn(tfrecord_dir,', 'split,', 'bsz_per_host,', 'seq_len,', 'reuse_len,', 'bi_data,', 'num_hosts=1,', 'num_core_per_host=1,', 'perm_size=None,', 'mask_alpha=None,', 'mask_beta=None,', 'uncased=False,', 'num_passes=None,', 'use_bfloat16=False,', 'num_predict=None):', 'record_glob_base', '=', "format_fil... | 972,908 |
MorvanZhou/Computer-Vision | flappybird.py | PipePair.rect | rect | Get the Rect which contains this PipePair. | [
"Get",
"the",
"Rect",
"which",
"contains",
"this",
"PipePair."
] | def rect(self):
return Rect(self.x, 0, PipePair.WIDTH, PipePair.PIECE_HEIGHT) | ['def', 'rect(self):', 'return', 'Rect(self.x,', '0,', 'PipePair.WIDTH,', 'PipePair.PIECE_HEIGHT)'] | 468,494 |
muhanzhang/D-VAE | test_2nd_order_grads.py | test_jacobian_disconnected_inputs | test_jacobian_disconnected_inputs | Test that disconnected inputs are properly handled by jacobian. | [
"Test",
"that",
"disconnected",
"inputs",
"are",
"properly",
"handled",
"by",
"jacobian."
] | def test_jacobian_disconnected_inputs():
v1 = tensor.vector()
v2 = tensor.vector()
jacobian_v = theano.gradient.jacobian(1 + v1, v2, disconnected_inputs='ignore')
func_v = theano.function([v1, v2], jacobian_v)
val = numpy.arange(4.0).astype(theano.config.floatX)
assert numpy.allclose(func_v(val,... | ['def', 'test_jacobian_disconnected_inputs():', 'v1', '=', 'tensor.vector()', 'v2', '=', 'tensor.vector()', 'jacobian_v', '=', 'theano.gradient.jacobian(1', '+', 'v1,', 'v2,', "disconnected_inputs='ignore')", 'func_v', '=', 'theano.function([v1,', 'v2],', 'jacobian_v)', 'val', '=', 'numpy.arange(4.0).astype(theano.conf... | 525,936 |
dlshriver/dnnv | input_data_loader.py | load_images_eran | load_images_eran | Loads the images from the eran csv. | [
"Loads",
"the",
"images",
"from",
"the",
"eran",
"csv."
] | def load_images_eran(img_csv: str='../../resources/images/cifar10_test.csv', num_images: int=100, image_shape: tuple=(3, 32, 32)) -> tuple:
num_images = 100
images_array = np.zeros((num_images, np.prod(image_shape)), dtype=np.float32)
targets_array = np.zeros(num_images, dtype=int)
with open(img_csv, 'r... | ['def', 'load_images_eran(img_csv:', "str='../../resources/images/cifar10_test.csv',", 'num_images:', 'int=100,', 'image_shape:', 'tuple=(3,', '32,', '32))', '->', 'tuple:', 'num_images', '=', '100', 'images_array', '=', 'np.zeros((num_images,', 'np.prod(image_shape)),', 'dtype=np.float32)', 'targets_array', '=', 'np.z... | 522,645 |
chribsen/simple-machine-learning-examples | ltisys.py | LinearTimeInvariant.D | D | Feedthrough matrix of the `StateSpace` system. | [
"Feedthrough",
"matrix",
"of",
"the",
"`StateSpace`",
"system."
] | def D(self):
warnings.warn('Cross-class properties have been deprecated in scipy 0.18.0 and will be removed in a future version of scipy. Please use `sys.to_ss().D`instead.', DeprecationWarning)
return self.to_ss().D | ['def', 'D(self):', "warnings.warn('Cross-class", 'properties', 'have', 'been', 'deprecated', 'in', 'scipy', '0.18.0', 'and', 'will', 'be', 'removed', 'in', 'a', 'future', 'version', 'of', 'scipy.', 'Please', 'use', "`sys.to_ss().D`instead.',", 'DeprecationWarning)', 'return', 'self.to_ss().D'] | 938,336 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | shapes_test.py | DataTest.testTransposingReshape_2_2_3_2_1 | testTransposingReshape_2_2_3_2_1 | Case: dest_a == src, dest_b < src: Split with Least sig part going left. | [
"Case:",
"dest_a",
"==",
"src,",
"dest_b",
"<",
"src:",
"Split",
"with",
"Least",
"sig",
"part",
"going",
"left."
] | def testTransposingReshape_2_2_3_2_1(self):
with self.test_session() as sess:
fake = tf.placeholder(tf.float32, shape=(None, None, None, 2), name='inputs')
outputs = shapes.transposing_reshape(fake, src_dim=2, part_a=2, part_b=3, dest_dim_a=2, dest_dim_b=1)
real = np.arange(120).reshape((5, ... | ['def', 'testTransposingReshape_2_2_3_2_1(self):', 'with', 'self.test_session()', 'as', 'sess:', 'fake', '=', 'tf.placeholder(tf.float32,', 'shape=(None,', 'None,', 'None,', '2),', "name='inputs')", 'outputs', '=', 'shapes.transposing_reshape(fake,', 'src_dim=2,', 'part_a=2,', 'part_b=3,', 'dest_dim_a=2,', 'dest_dim_b=... | 27,666 |
QLMX/semantic_segmentation | utils.py | get_trunk | get_trunk | Retrieve the network trunk and channel counts. | [
"Retrieve",
"the",
"network",
"trunk",
"and",
"channel",
"counts."
] | def get_trunk(trunk_name, output_stride=8):
assert output_stride == 8, 'Only stride8 supported right now'
if trunk_name == 'wrn38':
backbone = wrn38(pretrained=True)
s2_ch = 128
s4_ch = 256
high_level_ch = 4096
elif trunk_name == 'xception71':
backbone = xception71(ou... | ['def', 'get_trunk(trunk_name,', 'output_stride=8):', 'assert', 'output_stride', '==', '8,', "'Only", 'stride8', 'supported', 'right', "now'", 'if', 'trunk_name', '==', "'wrn38':", 'backbone', '=', 'wrn38(pretrained=True)', 's2_ch', '=', '128', 's4_ch', '=', '256', 'high_level_ch', '=', '4096', 'elif', 'trunk_name', '=... | 871,300 |
gunthercox/ChatterBot | datastructures.py | HeaderSet.to_header | to_header | Convert the header set into an HTTP header string. | [
"Convert",
"the",
"header",
"set",
"into",
"an",
"HTTP",
"header",
"string."
] | def to_header(self):
return ', '.join(map(quote_header_value, self._headers)) | ['def', 'to_header(self):', 'return', "',", "'.join(map(quote_header_value,", 'self._headers))'] | 483,145 |
flow-project/flow | test_util.py | TestRegistry.test_make_create_env | test_make_create_env | Tests that the make_create_env methods generates an environment with the expected flow parameters. | [
"Tests",
"that",
"the",
"make_create_env",
"methods",
"generates",
"an",
"environment",
"with",
"the",
"expected",
"flow",
"parameters."
] | def test_make_create_env(self):
vehicles = VehicleParams()
vehicles.add(veh_id='human', acceleration_controller=(IDMController, {'noise': 0.2}), routing_controller=(ContinuousRouter, {}), car_following_params=SumoCarFollowingParams(speed_mode='obey_safe_speed'), num_vehicles=13)
vehicles.add(veh_id='rl', ac... | ['def', 'test_make_create_env(self):', 'vehicles', '=', 'VehicleParams()', "vehicles.add(veh_id='human',", 'acceleration_controller=(IDMController,', "{'noise':", '0.2}),', 'routing_controller=(ContinuousRouter,', '{}),', "car_following_params=SumoCarFollowingParams(speed_mode='obey_safe_speed'),", 'num_vehicles=13)', ... | 212,010 |
kornia/kornia | imgwarp.py | get_affine_matrix2d | get_affine_matrix2d | Compose affine matrix from the components. | [
"Compose",
"affine",
"matrix",
"from",
"the",
"components."
] | def get_affine_matrix2d(translations: Tensor, center: Tensor, scale: Tensor, angle: Tensor, sx: Optional[Tensor]=None, sy: Optional[Tensor]=None) -> Tensor:
transform: Tensor = get_rotation_matrix2d(center, -angle, scale)
transform[..., 2] += translations
transform_h = convert_affinematrix_to_homography(tra... | ['def', 'get_affine_matrix2d(translations:', 'Tensor,', 'center:', 'Tensor,', 'scale:', 'Tensor,', 'angle:', 'Tensor,', 'sx:', 'Optional[Tensor]=None,', 'sy:', 'Optional[Tensor]=None)', '->', 'Tensor:', 'transform:', 'Tensor', '=', 'get_rotation_matrix2d(center,', '-angle,', 'scale)', 'transform[...,', '2]', '+=', 'tra... | 622,169 |
aisingapore/PeekingDuck | yolo_license_plate.py | Node.run | run | Reads the image input and returns the bboxes of the specified objects chosen to be detected. | [
"Reads",
"the",
"image",
"input",
"and",
"returns",
"the",
"bboxes",
"of",
"the",
"specified",
"objects",
"chosen",
"to",
"be",
"detected."
] | def run(self, inputs: Dict[str, Any]) -> Dict[str, Any]:
image = cv2.cvtColor(inputs['img'], cv2.COLOR_BGR2RGB)
(bboxes, labels, scores) = self.model.predict(image)
bboxes = np.clip(bboxes, 0, 1)
outputs = {'bboxes': bboxes, 'bbox_labels': labels, 'bbox_scores': scores}
return outputs | ['def', 'run(self,', 'inputs:', 'Dict[str,', 'Any])', '->', 'Dict[str,', 'Any]:', 'image', '=', "cv2.cvtColor(inputs['img'],", 'cv2.COLOR_BGR2RGB)', '(bboxes,', 'labels,', 'scores)', '=', 'self.model.predict(image)', 'bboxes', '=', 'np.clip(bboxes,', '0,', '1)', 'outputs', '=', "{'bboxes':", 'bboxes,', "'bbox_labels':"... | 766,894 |
scikit-learn/scikit-learn | test_classification.py | test_average_precision_score_duplicate_values | test_average_precision_score_duplicate_values | Duplicate values with precision-recall require a different processing than when computing the AUC of a ROC, because the precision-recall curve is a decreasing curve The following situation corresponds to a perfect test statistic, the average_precision_score should be 1. | [
"Duplicate",
"values",
"with",
"precision-recall",
"require",
"a",
"different",
"processing",
"than",
"when",
"computing",
"the",
"AUC",
"of",
"a",
"ROC,",
"because",
"the",
"precision-recall",
"curve",
"is",
"a",
"decreasing",
"curve",
"The",
"following",
"situat... | def test_average_precision_score_duplicate_values(y_true, y_score):
assert average_precision_score(y_true, y_score) == 1 | ['def', 'test_average_precision_score_duplicate_values(y_true,', 'y_score):', 'assert', 'average_precision_score(y_true,', 'y_score)', '==', '1'] | 853,685 |
RLE-Foundation/rllte | girm.py | GIRM.get_vae_loss | get_vae_loss | Compute the vae loss. | [
"Compute",
"the",
"vae",
"loss."
] | def get_vae_loss(self, recon_x: th.Tensor, x: th.Tensor, mean: th.Tensor, logvar: th.Tensor) -> Tuple[th.Tensor, th.Tensor]:
RECON = F.mse_loss(recon_x, x)
KLD = -0.5 * th.sum(1 + logvar - mean.pow(2) - logvar.exp())
return (RECON, KLD) | ['def', 'get_vae_loss(self,', 'recon_x:', 'th.Tensor,', 'x:', 'th.Tensor,', 'mean:', 'th.Tensor,', 'logvar:', 'th.Tensor)', '->', 'Tuple[th.Tensor,', 'th.Tensor]:', 'RECON', '=', 'F.mse_loss(recon_x,', 'x)', 'KLD', '=', '-0.5', '*', 'th.sum(1', '+', 'logvar', '-', 'mean.pow(2)', '-', 'logvar.exp())', 'return', '(RECON,... | 333,677 |
sentinel-hub/eo-learn | test_raster_io.py | test_export_import_sequence | test_export_import_sequence | Tests import and export tiff tasks on generated array with different values of no_data_value. | [
"Tests",
"import",
"and",
"export",
"tiff",
"tasks",
"on",
"generated",
"array",
"with",
"different",
"values",
"of",
"no_data_value."
] | def test_export_import_sequence(no_data_value, data_type):
eopatch = EOPatch(bbox=BBox((0, 0, 1, 1), crs=CRS.WGS84))
feature = (FeatureType.DATA_TIMELESS, 'DATA')
np_arr = np.zeros((10, 10, 1), dtype=data_type)
np_arr[:5, :5, :] = 1
np_arr[7:, 7:, :] = no_data_value
eopatch[feature] = np_arr
... | ['def', 'test_export_import_sequence(no_data_value,', 'data_type):', 'eopatch', '=', 'EOPatch(bbox=BBox((0,', '0,', '1,', '1),', 'crs=CRS.WGS84))', 'feature', '=', '(FeatureType.DATA_TIMELESS,', "'DATA')", 'np_arr', '=', 'np.zeros((10,', '10,', '1),', 'dtype=data_type)', 'np_arr[:5,', ':5,', ':]', '=', '1', 'np_arr[7:,... | 562,706 |
weimin17/Object-Detection_HelmetDetection | videos_to_tfrecords.py | GetViewInfo | GetViewInfo | Return information about a group of views. | [
"Return",
"information",
"about",
"a",
"group",
"of",
"views."
] | def GetViewInfo(views_fullname):
view_paths = sorted(glob.glob(views_fullname))
num_frames = [GetNumFrames(i) for i in view_paths]
min_num_frames = min(num_frames)
num_views = len(view_paths)
return (num_views, min_num_frames, view_paths, num_frames) | ['def', 'GetViewInfo(views_fullname):', 'view_paths', '=', 'sorted(glob.glob(views_fullname))', 'num_frames', '=', '[GetNumFrames(i)', 'for', 'i', 'in', 'view_paths]', 'min_num_frames', '=', 'min(num_frames)', 'num_views', '=', 'len(view_paths)', 'return', '(num_views,', 'min_num_frames,', 'view_paths,', 'num_frames)'] | 760,656 |
kukuruza/shuffler | general_test.py | Test_MatchPolygonPoints.test_identical | test_identical | Identical points are not matched if when ignoring names. | [
"Identical",
"points",
"are",
"not",
"matched",
"if",
"when",
"ignoring",
"names."
] | def test_identical(self):
objectid = 1
polygons1 = [(1, objectid, 10, 30, 'name1')]
polygons2 = [(2, objectid, 10, 30, 'name2')]
pairs = general_utils.matchPolygonPoints(polygons1, polygons2, 1.0, True)
self.assertEqual(pairs, [(1, 2)]) | ['def', 'test_identical(self):', 'objectid', '=', '1', 'polygons1', '=', '[(1,', 'objectid,', '10,', '30,', "'name1')]", 'polygons2', '=', '[(2,', 'objectid,', '10,', '30,', "'name2')]", 'pairs', '=', 'general_utils.matchPolygonPoints(polygons1,', 'polygons2,', '1.0,', 'True)', 'self.assertEqual(pairs,', '[(1,', '2)])'... | 933,908 |
ldkong1205/LaserMix | parta2_rpn_head.py | PartA2RPNHead.loss_and_predict | loss_and_predict | Perform forward propagation of the head, then calculate loss and predictions from the features and data samples. | [
"Perform",
"forward",
"propagation",
"of",
"the",
"head,",
"then",
"calculate",
"loss",
"and",
"predictions",
"from",
"the",
"features",
"and",
"data",
"samples."
] | def loss_and_predict(self, feats_dict: Dict, batch_data_samples: SampleList, proposal_cfg: ConfigDict=None, **kwargs) -> Tuple[dict, InstanceList]:
batch_gt_instances_3d = []
batch_gt_instances_ignore = []
batch_input_metas = []
for data_sample in batch_data_samples:
batch_input_metas.append(dat... | ['def', 'loss_and_predict(self,', 'feats_dict:', 'Dict,', 'batch_data_samples:', 'SampleList,', 'proposal_cfg:', 'ConfigDict=None,', '**kwargs)', '->', 'Tuple[dict,', 'InstanceList]:', 'batch_gt_instances_3d', '=', '[]', 'batch_gt_instances_ignore', '=', '[]', 'batch_input_metas', '=', '[]', 'for', 'data_sample', 'in',... | 624,011 |
scikit-multiflow/scikit-multiflow | dynamic_weighted_majority.py | DynamicWeightedMajorityClassifier.reset | reset | Reset this ensemble learner. | [
"Reset",
"this",
"ensemble",
"learner."
] | def reset(self):
self.epochs = 0
self.num_classes = 2
self.experts = [self._construct_new_expert()] | ['def', 'reset(self):', 'self.epochs', '=', '0', 'self.num_classes', '=', '2', 'self.experts', '=', '[self._construct_new_expert()]'] | 854,739 |
flavioschneider/rl-transfer- | maml_trpo_half_cheetah_dir.py | maml_trpo_half_cheetah_dir | maml_trpo_half_cheetah_dir | Set up environment and algorithm and run the task. | [
"Set",
"up",
"environment",
"and",
"algorithm",
"and",
"run",
"the",
"task."
] | def maml_trpo_half_cheetah_dir(ctxt, seed, epochs, episodes_per_task, meta_batch_size):
set_seed(seed)
max_episode_length = 100
env = normalize(GymEnv(HalfCheetahDirEnv(), max_episode_length=max_episode_length), expected_action_scale=10.0)
policy = GaussianMLPPolicy(env_spec=env.spec, hidden_sizes=[64, ... | ['def', 'maml_trpo_half_cheetah_dir(ctxt,', 'seed,', 'epochs,', 'episodes_per_task,', 'meta_batch_size):', 'set_seed(seed)', 'max_episode_length', '=', '100', 'env', '=', 'normalize(GymEnv(HalfCheetahDirEnv(),', 'max_episode_length=max_episode_length),', 'expected_action_scale=10.0)', 'policy', '=', 'GaussianMLPPolicy(... | 861,124 |
chenbinghui1/DSL | semivoc.py | SemiVOCDataset.evaluate | evaluate | Evaluate in VOC protocol. | [
"Evaluate",
"in",
"VOC",
"protocol."
] | def evaluate(self, results, metric='mAP', logger=None, proposal_nums=(100, 300, 1000), iou_thr=0.5, scale_ranges=None):
if not isinstance(metric, str):
assert len(metric) == 1
metric = metric[0]
allowed_metrics = ['mAP', 'recall']
if metric not in allowed_metrics:
raise KeyError(f'me... | ['def', 'evaluate(self,', 'results,', "metric='mAP',", 'logger=None,', 'proposal_nums=(100,', '300,', '1000),', 'iou_thr=0.5,', 'scale_ranges=None):', 'if', 'not', 'isinstance(metric,', 'str):', 'assert', 'len(metric)', '==', '1', 'metric', '=', 'metric[0]', 'allowed_metrics', '=', "['mAP',", "'recall']", 'if', 'metric... | 167,562 |
brendanm12345/imageSequenceGeneration | optimization.py | get_piecewise_constant_schedule | get_piecewise_constant_schedule | Create a schedule with a constant learning rate, using the learning rate set in optimizer. | [
"Create",
"a",
"schedule",
"with",
"a",
"constant",
"learning",
"rate,",
"using",
"the",
"learning",
"rate",
"set",
"in",
"optimizer."
] | def get_piecewise_constant_schedule(optimizer: Optimizer, step_rules: str, last_epoch: int=-1):
rules_dict = {}
rule_list = step_rules.split(',')
for rule_str in rule_list[:-1]:
(value_str, steps_str) = rule_str.split(':')
steps = int(steps_str)
value = float(value_str)
rules... | ['def', 'get_piecewise_constant_schedule(optimizer:', 'Optimizer,', 'step_rules:', 'str,', 'last_epoch:', 'int=-1):', 'rules_dict', '=', '{}', 'rule_list', '=', "step_rules.split(',')", 'for', 'rule_str', 'in', 'rule_list[:-1]:', '(value_str,', 'steps_str)', '=', "rule_str.split(':')", 'steps', '=', 'int(steps_str)', '... | 599,610 |
43Carrig/recurrent_neural_networks_practice | dtypes.py | DType.is_integer | is_integer | Returns whether this is a (non-quantized) integer type. | [
"Returns",
"whether",
"this",
"is",
"a",
"(non-quantized)",
"integer",
"type."
] | def is_integer(self):
return self.is_numpy_compatible and (not self.is_quantized) and np.issubdtype(self.as_numpy_dtype, np.integer) | ['def', 'is_integer(self):', 'return', 'self.is_numpy_compatible', 'and', '(not', 'self.is_quantized)', 'and', 'np.issubdtype(self.as_numpy_dtype,', 'np.integer)'] | 336,276 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.