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 |
|---|---|---|---|---|---|---|---|---|
AIChallenger/AI_Challenger_2018 | visualization_utils_test.py | VisualizationUtilsTest.test_draw_bounding_boxes_on_image_tensors_with_additional_channels | test_draw_bounding_boxes_on_image_tensors_with_additional_channels | Tests the case where input image tensor has more than 3 channels. | [
"Tests",
"the",
"case",
"where",
"input",
"image",
"tensor",
"has",
"more",
"than",
"3",
"channels."
] | def test_draw_bounding_boxes_on_image_tensors_with_additional_channels(self):
category_index = {1: {'id': 1, 'name': 'dog'}}
image_np = self.create_test_image_with_five_channels()
images_np = np.stack((image_np, image_np), axis=0)
with tf.Graph().as_default():
images_tensor = tf.constant(value=i... | ['def', 'test_draw_bounding_boxes_on_image_tensors_with_additional_channels(self):', 'category_index', '=', '{1:', "{'id':", '1,', "'name':", "'dog'}}", 'image_np', '=', 'self.create_test_image_with_five_channels()', 'images_np', '=', 'np.stack((image_np,', 'image_np),', 'axis=0)', 'with', 'tf.Graph().as_default():', '... | 87,050 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Expression.acceptBitShiftRight | acceptBitShiftRight | Accept and process a bit shift right expression. | [
"Accept",
"and",
"process",
"a",
"bit",
"shift",
"right",
"expression."
] | def acceptBitShiftRight(self, node, memo):
factory = self.factory.expr
self.fs = 'bsr(' + FS.l + ', ' + FS.r + ')'
(self.left, self.right) = visitors = (factory(parent=self), factory())
self.zipWalk(node.children, visitors, memo)
module = self.parents(lambda x: x.isModule).next()
module.needsBsr... | ['def', 'acceptBitShiftRight(self,', 'node,', 'memo):', 'factory', '=', 'self.factory.expr', 'self.fs', '=', "'bsr('", '+', 'FS.l', '+', "',", "'", '+', 'FS.r', '+', "')'", '(self.left,', 'self.right)', '=', 'visitors', '=', '(factory(parent=self),', 'factory())', 'self.zipWalk(node.children,', 'visitors,', 'memo)', 'm... | 17,171 |
ViTAE-Transformer/ViTDet | solo_head.py | SOLOHead.loss | loss | Calculate the loss of total batch. | [
"Calculate",
"the",
"loss",
"of",
"total",
"batch."
] | def loss(self, mlvl_mask_preds, mlvl_cls_preds, gt_labels, gt_masks, img_metas, gt_bboxes=None, **kwargs):
num_levels = self.num_levels
num_imgs = len(gt_labels)
featmap_sizes = [featmap.size()[-2:] for featmap in mlvl_mask_preds]
(pos_mask_targets, labels, pos_masks) = multi_apply(self._get_targets_sin... | ['def', 'loss(self,', 'mlvl_mask_preds,', 'mlvl_cls_preds,', 'gt_labels,', 'gt_masks,', 'img_metas,', 'gt_bboxes=None,', '**kwargs):', 'num_levels', '=', 'self.num_levels', 'num_imgs', '=', 'len(gt_labels)', 'featmap_sizes', '=', '[featmap.size()[-2:]', 'for', 'featmap', 'in', 'mlvl_mask_preds]', '(pos_mask_targets,', ... | 945,595 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | policy.py | Policy.multi_step | multi_step | Calculate log-probs and other calculations on batch of episodes. | [
"Calculate",
"log-probs",
"and",
"other",
"calculations",
"on",
"batch",
"of",
"episodes."
] | def multi_step(self, all_obs, initial_state, all_actions):
batch_size = tf.shape(initial_state)[0]
time_length = tf.shape(all_obs[0])[0]
initial_actions = [act[0] for act in all_actions]
all_actions = [tf.concat([act[1:], act[0:1]], 0) for act in all_actions]
(internal_states, _, logits, log_probs, ... | ['def', 'multi_step(self,', 'all_obs,', 'initial_state,', 'all_actions):', 'batch_size', '=', 'tf.shape(initial_state)[0]', 'time_length', '=', 'tf.shape(all_obs[0])[0]', 'initial_actions', '=', '[act[0]', 'for', 'act', 'in', 'all_actions]', 'all_actions', '=', '[tf.concat([act[1:],', 'act[0:1]],', '0)', 'for', 'act', ... | 26,154 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | feature_extractor.py | CalculateKeypointCenters | CalculateKeypointCenters | Helper function to compute feature centers, from RF boxes. | [
"Helper",
"function",
"to",
"compute",
"feature",
"centers,",
"from",
"RF",
"boxes."
] | def CalculateKeypointCenters(boxes):
return tf.divide(tf.add(tf.gather(boxes, [0, 1], axis=1), tf.gather(boxes, [2, 3], axis=1)), 2.0) | ['def', 'CalculateKeypointCenters(boxes):', 'return', 'tf.divide(tf.add(tf.gather(boxes,', '[0,', '1],', 'axis=1),', 'tf.gather(boxes,', '[2,', '3],', 'axis=1)),', '2.0)'] | 53,707 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | real_nvp_utils.py | convnet | convnet | Chaining of convolutional layers. | [
"Chaining",
"of",
"convolutional",
"layers."
] | def convnet(input_, dim_in, dim_hid, filter_sizes, dim_out, name, use_batch_norm=True, train=True, nonlinearity=tf.nn.relu):
dims_in = [dim_in] + dim_hid[:-1]
dims_out = dim_hid
res = input_
bias = not use_batch_norm
with tf.variable_scope(name):
for layer_idx in xrange(len(dim_hid)):
... | ['def', 'convnet(input_,', 'dim_in,', 'dim_hid,', 'filter_sizes,', 'dim_out,', 'name,', 'use_batch_norm=True,', 'train=True,', 'nonlinearity=tf.nn.relu):', 'dims_in', '=', '[dim_in]', '+', 'dim_hid[:-1]', 'dims_out', '=', 'dim_hid', 'res', '=', 'input_', 'bias', '=', 'not', 'use_batch_norm', 'with', 'tf.variable_scope(... | 26,645 |
AgnostiqHQ/covalent | write_result_to_db_test.py | test_store_file_valid_extension | test_store_file_valid_extension | Test the function used to write data corresponding to the filenames in the DB. | [
"Test",
"the",
"function",
"used",
"to",
"write",
"data",
"corresponding",
"to",
"the",
"filenames",
"in",
"the",
"DB."
] | def test_store_file_valid_extension():
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(InvalidFileExtension):
store_file(storage_path=temp_dir, filename='test.invalid', data='')
with pytest.raises(InvalidFileExtension):
store_file(storage_path=temp_dir, fil... | ['def', 'test_store_file_valid_extension():', 'with', 'tempfile.TemporaryDirectory()', 'as', 'temp_dir:', 'with', 'pytest.raises(InvalidFileExtension):', 'store_file(storage_path=temp_dir,', "filename='test.invalid',", "data='')", 'with', 'pytest.raises(InvalidFileExtension):', 'store_file(storage_path=temp_dir,', "fil... | 489,751 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | common_layers.py | maybe_zero_out_padding | maybe_zero_out_padding | If necessary, zero out inputs to a conv for padding positions. | [
"If",
"necessary,",
"zero",
"out",
"inputs",
"to",
"a",
"conv",
"for",
"padding",
"positions."
] | def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask):
if kernel_size != 1 and kernel_size != (1, 1) and (nonpadding_mask is not None):
while nonpadding_mask.get_shape().ndims < inputs.get_shape().ndims:
nonpadding_mask = tf.expand_dims(nonpadding_mask, -1)
return inputs * non... | ['def', 'maybe_zero_out_padding(inputs,', 'kernel_size,', 'nonpadding_mask):', 'if', 'kernel_size', '!=', '1', 'and', 'kernel_size', '!=', '(1,', '1)', 'and', '(nonpadding_mask', 'is', 'not', 'None):', 'while', 'nonpadding_mask.get_shape().ndims', '<', 'inputs.get_shape().ndims:', 'nonpadding_mask', '=', 'tf.expand_dim... | 965,284 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | axis.py | YAxis.tick_left | tick_left | Move ticks and ticklabels (if present) to the left of the axes. | [
"Move",
"ticks",
"and",
"ticklabels",
"(if",
"present)",
"to",
"the",
"left",
"of",
"the",
"axes."
] | def tick_left(self):
label = True
if 'label1On' in self._major_tick_kw:
label = self._major_tick_kw['label1On'] or self._major_tick_kw['label2On']
self.set_ticks_position('left')
self.set_tick_params(which='both', labelleft=label) | ['def', 'tick_left(self):', 'label', '=', 'True', 'if', "'label1On'", 'in', 'self._major_tick_kw:', 'label', '=', "self._major_tick_kw['label1On']", 'or', "self._major_tick_kw['label2On']", "self.set_ticks_position('left')", "self.set_tick_params(which='both',", 'labelleft=label)'] | 450,086 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | prediction_model.py | dna_transformation | dna_transformation | Apply dynamic neural advection to previous image. | [
"Apply",
"dynamic",
"neural",
"advection",
"to",
"previous",
"image."
] | def dna_transformation(prev_image, dna_input):
prev_image_pad = tf.pad(prev_image, [[0, 0], [2, 2], [2, 2], [0, 0]])
image_height = int(prev_image.get_shape()[1])
image_width = int(prev_image.get_shape()[2])
inputs = []
for xkern in range(DNA_KERN_SIZE):
for ykern in range(DNA_KERN_SIZE):
... | ['def', 'dna_transformation(prev_image,', 'dna_input):', 'prev_image_pad', '=', 'tf.pad(prev_image,', '[[0,', '0],', '[2,', '2],', '[2,', '2],', '[0,', '0]])', 'image_height', '=', 'int(prev_image.get_shape()[1])', 'image_width', '=', 'int(prev_image.get_shape()[2])', 'inputs', '=', '[]', 'for', 'xkern', 'in', 'range(D... | 112,841 |
myothida/Supervised-Machine-Learning | register.py | register.post_to_server | post_to_server | Post a query to the server, and return a string response. | [
"Post",
"a",
"query",
"to",
"the",
"server,",
"and",
"return",
"a",
"string",
"response."
] | def post_to_server(self, data, auth=None):
if 'name' in data:
self.announce('Registering %s to %s' % (data['name'], self.repository), log.INFO)
boundary = '--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
sep_boundary = '\n--' + boundary
end_boundary = sep_boundary + '--'
body = io.Strin... | ['def', 'post_to_server(self,', 'data,', 'auth=None):', 'if', "'name'", 'in', 'data:', "self.announce('Registering", '%s', 'to', "%s'", '%', "(data['name'],", 'self.repository),', 'log.INFO)', 'boundary', '=', "'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'", 'sep_boundary', '=', "'\\n--'", '+', 'boundary', 'end... | 447,210 |
pykale/pykale | visualize.py | distplot_1d | distplot_1d | Plot distribution of 1D data. | [
"Plot",
"distribution",
"of",
"1D",
"data."
] | def distplot_1d(data, labels=None, xlabel=None, ylabel=None, title=None, figsize=None, colors=None, title_kwargs=None, hist_kwargs=None):
hist_kwargs = _none2dict(hist_kwargs)
title_kwargs = _none2dict(title_kwargs)
fig = plt.figure(figsize=figsize)
if colors is None:
colors = plt.get_cmap('Set1... | ['def', 'distplot_1d(data,', 'labels=None,', 'xlabel=None,', 'ylabel=None,', 'title=None,', 'figsize=None,', 'colors=None,', 'title_kwargs=None,', 'hist_kwargs=None):', 'hist_kwargs', '=', '_none2dict(hist_kwargs)', 'title_kwargs', '=', '_none2dict(title_kwargs)', 'fig', '=', 'plt.figure(figsize=figsize)', 'if', 'color... | 819,669 |
kubeflow/pipelines | _container_op.py | BaseOp.add_sidecar | add_sidecar | Add a sidecar to the Op. | [
"Add",
"a",
"sidecar",
"to",
"the",
"Op."
] | def add_sidecar(self, sidecar: Sidecar):
self.sidecars.append(sidecar)
return self | ['def', 'add_sidecar(self,', 'sidecar:', 'Sidecar):', 'self.sidecars.append(sidecar)', 'return', 'self'] | 780,147 |
usmancheema89/computer_vision | static_shape.py | get_height | get_height | Returns height from the tensor shape. | [
"Returns",
"height",
"from",
"the",
"tensor",
"shape."
] | def get_height(tensor_shape):
tensor_shape.assert_has_rank(rank=4)
return tensor_shape[1].value | ['def', 'get_height(tensor_shape):', 'tensor_shape.assert_has_rank(rank=4)', 'return', 'tensor_shape[1].value'] | 513,769 |
BerkeleyLearnVerify/VerifAI | features.py | Domain.unstandardizeIterator | unstandardizeIterator | Unstandardize an iterator of coords to a point in this Domain. | [
"Unstandardize",
"an",
"iterator",
"of",
"coords",
"to",
"a",
"point",
"in",
"this",
"Domain."
] | def unstandardizeIterator(self, coords):
raise RuntimeError(f'Domain {self.__class__.__name__} does not support standardize') | ['def', 'unstandardizeIterator(self,', 'coords):', 'raise', "RuntimeError(f'Domain", '{self.__class__.__name__}', 'does', 'not', 'support', "standardize')"] | 379,384 |
Kvatsx/Artificial-Intelligence-Assignments | client.py | QtZMQSocketChannel.process_events | process_events | Process any pending GUI events. | [
"Process",
"any",
"pending",
"GUI",
"events."
] | def process_events(self):
QtCore.QCoreApplication.instance().processEvents() | ['def', 'process_events(self):', 'QtCore.QCoreApplication.instance().processEvents()'] | 77,218 |
sunishsheth2009/ChatterBot | api.py | CategorizedCorpusReader.fileids | fileids | Return a list of file identifiers for the files that make up this corpus, or that make up the given category(s) if specified. | [
"Return",
"a",
"list",
"of",
"file",
"identifiers",
"for",
"the",
"files",
"that",
"make",
"up",
"this",
"corpus,",
"or",
"that",
"make",
"up",
"the",
"given",
"category(s)",
"if",
"specified."
] | def fileids(self, categories=None):
if categories is None:
return super(CategorizedCorpusReader, self).fileids()
elif isinstance(categories, basestring):
if self._f2c is None:
self._init()
if categories in self._c2f:
return sorted(self._c2f[categories])
el... | ['def', 'fileids(self,', 'categories=None):', 'if', 'categories', 'is', 'None:', 'return', 'super(CategorizedCorpusReader,', 'self).fileids()', 'elif', 'isinstance(categories,', 'basestring):', 'if', 'self._f2c', 'is', 'None:', 'self._init()', 'if', 'categories', 'in', 'self._c2f:', 'return', 'sorted(self._c2f[categori... | 527,436 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_utils.py | print_out | print_out | Print a message out and log it to file. | [
"Print",
"a",
"message",
"out",
"and",
"log",
"it",
"to",
"file."
] | def print_out(s, newline=True):
if log_filename:
try:
with tf.gfile.GFile(log_filename, mode='a') as f:
f.write(s + ('\n' if newline else ''))
except:
sys.stderr.write('Error appending to %s\n' % log_filename)
sys.stdout.write(s + ('\n' if newline else '')... | ['def', 'print_out(s,', 'newline=True):', 'if', 'log_filename:', 'try:', 'with', 'tf.gfile.GFile(log_filename,', "mode='a')", 'as', 'f:', 'f.write(s', '+', "('\\n'", 'if', 'newline', 'else', "''))", 'except:', "sys.stderr.write('Error", 'appending', 'to', "%s\\n'", '%', 'log_filename)', 'sys.stdout.write(s', '+', "('\\... | 56,272 |
Farama-Foundation/Gymnasium | core.py | Wrapper.class_name | class_name | Returns the class name of the wrapper. | [
"Returns",
"the",
"class",
"name",
"of",
"the",
"wrapper."
] | def class_name(cls) -> str:
return cls.__name__ | ['def', 'class_name(cls)', '->', 'str:', 'return', 'cls.__name__'] | 572,980 |
deepmind/bsuite | csv_load.py | load_bsuite | load_bsuite | Returns a pandas DataFrame of bsuite results. | [
"Returns",
"a",
"pandas",
"DataFrame",
"of",
"bsuite",
"results."
] | def load_bsuite(results_dirs: logging_utils.PathCollection) -> Tuple[pd.DataFrame, List[str]]:
return logging_utils.load_multiple_runs(path_collection=results_dirs, single_load_fn=load_one_result_set) | ['def', 'load_bsuite(results_dirs:', 'logging_utils.PathCollection)', '->', 'Tuple[pd.DataFrame,', 'List[str]]:', 'return', 'logging_utils.load_multiple_runs(path_collection=results_dirs,', 'single_load_fn=load_one_result_set)'] | 410,252 |
weimin17/Object-Detection_HelmetDetection | accountant.py | MomentsAccountant.get_privacy_spent | get_privacy_spent | Compute privacy spending in (e, d)-DP form for a single or list of eps. | [
"Compute",
"privacy",
"spending",
"in",
"(e,",
"d)-DP",
"form",
"for",
"a",
"single",
"or",
"list",
"of",
"eps."
] | def get_privacy_spent(self, sess, target_eps=None, target_deltas=None):
assert (target_eps is None) ^ (target_deltas is None)
eps_deltas = []
log_moments = sess.run(self._log_moments)
log_moments_with_order = zip(self._moment_orders, log_moments)
if target_eps is not None:
for eps in target_... | ['def', 'get_privacy_spent(self,', 'sess,', 'target_eps=None,', 'target_deltas=None):', 'assert', '(target_eps', 'is', 'None)', '^', '(target_deltas', 'is', 'None)', 'eps_deltas', '=', '[]', 'log_moments', '=', 'sess.run(self._log_moments)', 'log_moments_with_order', '=', 'zip(self._moment_orders,', 'log_moments)', 'if... | 762,622 |
sunishsheth2009/ChatterBot | models.py | Response.raise_for_status | raise_for_status | Raises stored :class:`HTTPError`, if one occurred. | [
"Raises",
"stored",
":class:`HTTPError`,",
"if",
"one",
"occurred."
] | def raise_for_status(self):
http_error_msg = ''
if 400 <= self.status_code < 500:
http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
elif 500 <= self.status_code < 600:
http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)
if http_error_msg:
... | ['def', 'raise_for_status(self):', 'http_error_msg', '=', "''", 'if', '400', '<=', 'self.status_code', '<', '500:', 'http_error_msg', '=', "'%s", 'Client', 'Error:', "%s'", '%', '(self.status_code,', 'self.reason)', 'elif', '500', '<=', 'self.status_code', '<', '600:', 'http_error_msg', '=', "'%s", 'Server', 'Error:', ... | 480,573 |
ashwanitanwar/nmt-transfer-learning-xlm-r | wav2vec.py | Wav2VecModel.build_model | build_model | Build a new model instance. | [
"Build",
"a",
"new",
"model",
"instance."
] | def build_model(cls, args, task):
base_wav2vec_architecture(args)
model = Wav2VecModel(args)
logger.info(model)
return model | ['def', 'build_model(cls,', 'args,', 'task):', 'base_wav2vec_architecture(args)', 'model', '=', 'Wav2VecModel(args)', 'logger.info(model)', 'return', 'model'] | 732,645 |
kemaloksuz/RankSortLoss | test_heads.py | test_bbox_head_loss | test_bbox_head_loss | Tests bbox head loss when truth is empty and non-empty. | [
"Tests",
"bbox",
"head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_bbox_head_loss():
self = BBoxHead(in_channels=8, roi_feat_size=3)
proposal_list = [torch.Tensor([[23.6667, 23.8757, 228.6326, 153.8874]])]
target_cfg = mmcv.Config(dict(pos_weight=1))
gt_bboxes = [torch.empty((0, 4))]
gt_labels = [torch.LongTensor([])]
sampling_results = _dummy_bbox_sam... | ['def', 'test_bbox_head_loss():', 'self', '=', 'BBoxHead(in_channels=8,', 'roi_feat_size=3)', 'proposal_list', '=', '[torch.Tensor([[23.6667,', '23.8757,', '228.6326,', '153.8874]])]', 'target_cfg', '=', 'mmcv.Config(dict(pos_weight=1))', 'gt_bboxes', '=', '[torch.empty((0,', '4))]', 'gt_labels', '=', '[torch.LongTenso... | 836,413 |
awalsh128/nlp | rnnlm.py | PTBModel.export_ops | export_ops | Exports ops to collections. | [
"Exports",
"ops",
"to",
"collections."
] | def export_ops(self, name):
self._name = name
ops = {util.with_prefix(self._name, 'cost'): self._cost}
if self._is_training:
ops.update(lr=self._lr, new_lr=self._new_lr, lr_update=self._lr_update)
if self._rnn_params:
ops.update(rnn_params=self._rnn_params)
ops.update({util.w... | ['def', 'export_ops(self,', 'name):', 'self._name', '=', 'name', 'ops', '=', '{util.with_prefix(self._name,', "'cost'):", 'self._cost}', 'if', 'self._is_training:', 'ops.update(lr=self._lr,', 'new_lr=self._new_lr,', 'lr_update=self._lr_update)', 'if', 'self._rnn_params:', 'ops.update(rnn_params=self._rnn_params)', 'ops... | 986,082 |
Katja-M/Python_NaturalLanguageProcessing | setup.py | is_npy_no_signal | is_npy_no_signal | Return True if the NPY_NO_SIGNAL symbol must be defined in configuration header. | [
"Return",
"True",
"if",
"the",
"NPY_NO_SIGNAL",
"symbol",
"must",
"be",
"defined",
"in",
"configuration",
"header."
] | def is_npy_no_signal():
return sys.platform == 'win32' | ['def', 'is_npy_no_signal():', 'return', 'sys.platform', '==', "'win32'"] | 867,420 |
Eric3911/OpenAGI | mellon_qa_data_processor.py | DialogueMellonQADataProcessor.get_train_examples | get_train_examples | Gets a collection of `InputExample`s for the train set. | [
"Gets",
"a",
"collection",
"of",
"`InputExample`s",
"for",
"the",
"train",
"set."
] | def get_train_examples(self):
return self.get_dialog_examples('train') | ['def', 'get_train_examples(self):', 'return', "self.get_dialog_examples('train')"] | 273,209 |
flavioschneider/rl-transfer- | categorical_mlp_policy.py | CategoricalMLPPolicy.input_dim | input_dim | int: Dimension of the policy input. | [
"int:",
"Dimension",
"of",
"the",
"policy",
"input."
] | def input_dim(self):
return self._obs_dim | ['def', 'input_dim(self):', 'return', 'self._obs_dim'] | 861,447 |
kolikaran1992/NaturalLanguageProcessing | ptb-lm.py | run_epoch | run_epoch | One epoch of training/validation (depending on flag is_train). | [
"One",
"epoch",
"of",
"training/validation",
"(depending",
"on",
"flag",
"is_train)."
] | def run_epoch(model, data, is_train=False, lr=1.0):
if is_train:
model.train()
else:
model.eval()
epoch_size = (len(data) // model.batch_size - 1) // model.seq_len
start_time = time.time()
if args.model != 'TRANSFORMER':
hidden = model.init_hidden()
hidden = hidden.to... | ['def', 'run_epoch(model,', 'data,', 'is_train=False,', 'lr=1.0):', 'if', 'is_train:', 'model.train()', 'else:', 'model.eval()', 'epoch_size', '=', '(len(data)', '//', 'model.batch_size', '-', '1)', '//', 'model.seq_len', 'start_time', '=', 'time.time()', 'if', 'args.model', '!=', "'TRANSFORMER':", 'hidden', '=', 'mode... | 673,634 |
googleapis/python-aiplatform | client.py | MatchServiceClient.common_billing_account_path | common_billing_account_path | Returns a fully-qualified billing_account string. | [
"Returns",
"a",
"fully-qualified",
"billing_account",
"string."
] | def common_billing_account_path(billing_account: str) -> str:
return 'billingAccounts/{billing_account}'.format(billing_account=billing_account) | ['def', 'common_billing_account_path(billing_account:', 'str)', '->', 'str:', 'return', "'billingAccounts/{billing_account}'.format(billing_account=billing_account)"] | 811,072 |
Kvatsx/Artificial-Intelligence-Assignments | server.py | CGIHTTPRequestHandler.is_python | is_python | Test whether argument path is a Python script. | [
"Test",
"whether",
"argument",
"path",
"is",
"a",
"Python",
"script."
] | def is_python(self, path):
(head, tail) = os.path.splitext(path)
return tail.lower() in ('.py', '.pyw') | ['def', 'is_python(self,', 'path):', '(head,', 'tail)', '=', 'os.path.splitext(path)', 'return', 'tail.lower()', 'in', "('.py',", "'.pyw')"] | 36,989 |
KalleHallden/InstaAutomator | compat.py | BaseConfigurator.cfg_convert | cfg_convert | Default converter for the cfg:// protocol. | [
"Default",
"converter",
"for",
"the",
"cfg://",
"protocol."
] | def cfg_convert(self, value):
rest = value
m = self.WORD_PATTERN.match(rest)
if m is None:
raise ValueError('Unable to convert %r' % value)
else:
rest = rest[m.end():]
d = self.config[m.groups()[0]]
while rest:
m = self.DOT_PATTERN.match(rest)
if m... | ['def', 'cfg_convert(self,', 'value):', 'rest', '=', 'value', 'm', '=', 'self.WORD_PATTERN.match(rest)', 'if', 'm', 'is', 'None:', 'raise', "ValueError('Unable", 'to', 'convert', "%r'", '%', 'value)', 'else:', 'rest', '=', 'rest[m.end():]', 'd', '=', 'self.config[m.groups()[0]]', 'while', 'rest:', 'm', '=', 'self.DOT_P... | 244,157 |
thaines/helit | corpus.py | Corpus.getGamma | getGamma | Returns the PriorConcDP for the gamma parameter. | [
"Returns",
"the",
"PriorConcDP",
"for",
"the",
"gamma",
"parameter."
] | def getGamma(self):
return self.gamma | ['def', 'getGamma(self):', 'return', 'self.gamma'] | 591,398 |
aws/sagemaker-python-sdk | _base_types.py | ApiObject.from_boto | from_boto | Construct an instance of this ApiObject from a boto response. | [
"Construct",
"an",
"instance",
"of",
"this",
"ApiObject",
"from",
"a",
"boto",
"response."
] | def from_boto(cls, boto_dict, **kwargs):
if boto_dict is None:
return None
boto_dict = {k: v for (k, v) in boto_dict.items() if k not in cls._boto_ignore()}
custom_boto_names_to_member_names = {a: b for (b, a) in cls._custom_boto_names.items()}
cls_kwargs = _boto_functions.from_boto(boto_dict, c... | ['def', 'from_boto(cls,', 'boto_dict,', '**kwargs):', 'if', 'boto_dict', 'is', 'None:', 'return', 'None', 'boto_dict', '=', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'boto_dict.items()', 'if', 'k', 'not', 'in', 'cls._boto_ignore()}', 'custom_boto_names_to_member_names', '=', '{a:', 'b', 'for', '(b,', 'a)', 'in', 'cls._cust... | 829,778 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | pg_train.py | write_hparams_to_config | write_hparams_to_config | Write hparams given by the tuner into the Config object. | [
"Write",
"hparams",
"given",
"by",
"the",
"tuner",
"into",
"the",
"Config",
"object."
] | def write_hparams_to_config(config, hparams, hparam_space_type):
if hparam_space_type not in ('pg', 'pg-topk', 'topk', 'is'):
raise ValueError('Hparam space is not valid: "%s"' % hparam_space_type)
config.agent.lr = hparams.lr
config.agent.entropy_beta = hparams.entropy_beta
if hparam_space_type... | ['def', 'write_hparams_to_config(config,', 'hparams,', 'hparam_space_type):', 'if', 'hparam_space_type', 'not', 'in', "('pg',", "'pg-topk',", "'topk',", "'is'):", 'raise', "ValueError('Hparam", 'space', 'is', 'not', 'valid:', '"%s"\'', '%', 'hparam_space_type)', 'config.agent.lr', '=', 'hparams.lr', 'config.agent.entro... | 46,695 |
vmware-archive/salt-contrib | flup_fcgi_client.py | Record.write | write | Encode and write a Record to a socket. | [
"Encode",
"and",
"write",
"a",
"Record",
"to",
"a",
"socket."
] | def write(self, sock):
self.paddingLength = -self.contentLength & 7
if __debug__:
_debug(9, 'write: fd = %d, type = %d, requestId = %d, contentLength = %d' % (sock.fileno(), self.type, self.requestId, self.contentLength))
header = struct.pack(FCGI_Header, self.version, self.type, self.requestId, sel... | ['def', 'write(self,', 'sock):', 'self.paddingLength', '=', '-self.contentLength', '&', '7', 'if', '__debug__:', '_debug(9,', "'write:", 'fd', '=', '%d,', 'type', '=', '%d,', 'requestId', '=', '%d,', 'contentLength', '=', "%d'", '%', '(sock.fileno(),', 'self.type,', 'self.requestId,', 'self.contentLength))', 'header', ... | 328,717 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | sentence_io.py | FormatSentenceReader.corpus | corpus | Reads the entire corpus, and returns in a list. | [
"Reads",
"the",
"entire",
"corpus,",
"and",
"returns",
"in",
"a",
"list."
] | def corpus(self):
tf.logging.info('Reading corpus...')
corpus = []
while True:
(sentences, is_last) = self.read()
corpus.extend(sentences)
if is_last:
break
tf.logging.info('Read %d sentences.' % len(corpus))
return corpus | ['def', 'corpus(self):', "tf.logging.info('Reading", "corpus...')", 'corpus', '=', '[]', 'while', 'True:', '(sentences,', 'is_last)', '=', 'self.read()', 'corpus.extend(sentences)', 'if', 'is_last:', 'break', "tf.logging.info('Read", '%d', "sentences.'", '%', 'len(corpus))', 'return', 'corpus'] | 28,574 |
flow-project/flow | test_environments.py | TestWaveAttenuationEnv.test_v_eq_max_function | test_v_eq_max_function | Tests that the v_eq_max_function returns appropriate values. | [
"Tests",
"that",
"the",
"v_eq_max_function",
"returns",
"appropriate",
"values."
] | def test_v_eq_max_function(self):
self.assertAlmostEqual(float(fsolve(v_eq_max_function, np.array([4]), args=(22, 230))[0]), 3.7136148111012934)
self.assertAlmostEqual(float(fsolve(v_eq_max_function, np.array([4]), args=(22, 270))[0]), 5.6143732387852054) | ['def', 'test_v_eq_max_function(self):', 'self.assertAlmostEqual(float(fsolve(v_eq_max_function,', 'np.array([4]),', 'args=(22,', '230))[0]),', '3.7136148111012934)', 'self.assertAlmostEqual(float(fsolve(v_eq_max_function,', 'np.array([4]),', 'args=(22,', '270))[0]),', '5.6143732387852054)'] | 211,908 |
intel/neural-compressor | tuning_space.py | pattern_to_path | pattern_to_path | Convert pattern to path. | [
"Convert",
"pattern",
"to",
"path."
] | def pattern_to_path(pattern):
act_path = (pattern[0], 'activation', *pattern[1][0])
weight_path = (pattern[0], 'weight', *pattern[1][1])
return (act_path, weight_path) | ['def', 'pattern_to_path(pattern):', 'act_path', '=', '(pattern[0],', "'activation',", '*pattern[1][0])', 'weight_path', '=', '(pattern[0],', "'weight',", '*pattern[1][1])', 'return', '(act_path,', 'weight_path)'] | 738,763 |
Katja-M/Python_NaturalLanguageProcessing | demo.py | demo_multifeature_template | demo_multifeature_template | Templates can have more than a single feature. | [
"Templates",
"can",
"have",
"more",
"than",
"a",
"single",
"feature."
] | def demo_multifeature_template():
postag(templates=[Template(Word([0]), Pos([-2, -1]))]) | ['def', 'demo_multifeature_template():', 'postag(templates=[Template(Word([0]),', 'Pos([-2,', '-1]))])'] | 867,049 |
rchurchley/IMA-Deep-Learning | train.py | compile_model | compile_model | Compile Theano functions for learning process. | [
"Compile",
"Theano",
"functions",
"for",
"learning",
"process."
] | def compile_model(model):
network = model['network']
test_acc = theano.tensor.mean(theano.tensor.eq(theano.tensor.argmax(get_output(network, deterministic=True), axis=1), model['target_var']), dtype=theano.config.floatX)
train_fn = theano.function([model['input_var'], model['target_var']], model['loss'](), ... | ['def', 'compile_model(model):', 'network', '=', "model['network']", 'test_acc', '=', 'theano.tensor.mean(theano.tensor.eq(theano.tensor.argmax(get_output(network,', 'deterministic=True),', 'axis=1),', "model['target_var']),", 'dtype=theano.config.floatX)', 'train_fn', '=', "theano.function([model['input_var'],", "mode... | 598,840 |
sotudian/Natural-Language-Processing | wingnus.py | WINGNUS.candidate_selection | candidate_selection | Select noun phrases (NP) and NP containing a pre-propositional phrase (NP IN NP) as keyphrase candidates. | [
"Select",
"noun",
"phrases",
"(NP)",
"and",
"NP",
"containing",
"a",
"pre-propositional",
"phrase",
"(NP",
"IN",
"NP)",
"as",
"keyphrase",
"candidates."
] | def candidate_selection(self, grammar=None):
if grammar is None:
grammar = '\n NBAR:\n {<NOUN|PROPN|ADJ>{,2}<NOUN|PROPN>} \n \n NP:\n {<NBAR>}\n {<NBAR><ADP><NBAR>}\n '
self.grammar_selec... | ['def', 'candidate_selection(self,', 'grammar=None):', 'if', 'grammar', 'is', 'None:', 'grammar', '=', "'\\n", 'NBAR:\\n', '{<NOUN|PROPN|ADJ>{,2}<NOUN|PROPN>}', '\\n', '\\n', 'NP:\\n', '{<NBAR>}\\n', '{<NBAR><ADP><NBAR>}\\n', "'", 'self.grammar_selection(grammar)'] | 659,404 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | cifar10_main.py | preprocess_image | preprocess_image | Preprocess a single image of layout [height, width, depth]. | [
"Preprocess",
"a",
"single",
"image",
"of",
"layout",
"[height,",
"width,",
"depth]."
] | def preprocess_image(image, is_training):
if is_training:
image = tf.image.resize_image_with_crop_or_pad(image, _HEIGHT + 8, _WIDTH + 8)
image = tf.random_crop(image, [_HEIGHT, _WIDTH, _DEPTH])
image = tf.image.random_flip_left_right(image)
image = tf.image.per_image_standardization(imag... | ['def', 'preprocess_image(image,', 'is_training):', 'if', 'is_training:', 'image', '=', 'tf.image.resize_image_with_crop_or_pad(image,', '_HEIGHT', '+', '8,', '_WIDTH', '+', '8)', 'image', '=', 'tf.random_crop(image,', '[_HEIGHT,', '_WIDTH,', '_DEPTH])', 'image', '=', 'tf.image.random_flip_left_right(image)', 'image', ... | 13,965 |
Xianpeng919/MonoCon | mean_ap.py | tpfp_imagenet | tpfp_imagenet | Check if detected bboxes are true positive or false positive. | [
"Check",
"if",
"detected",
"bboxes",
"are",
"true",
"positive",
"or",
"false",
"positive."
] | def tpfp_imagenet(det_bboxes, gt_bboxes, gt_bboxes_ignore=None, default_iou_thr=0.5, area_ranges=None):
gt_ignore_inds = np.concatenate((np.zeros(gt_bboxes.shape[0], dtype=np.bool), np.ones(gt_bboxes_ignore.shape[0], dtype=np.bool)))
gt_bboxes = np.vstack((gt_bboxes, gt_bboxes_ignore))
num_dets = det_bboxes... | ['def', 'tpfp_imagenet(det_bboxes,', 'gt_bboxes,', 'gt_bboxes_ignore=None,', 'default_iou_thr=0.5,', 'area_ranges=None):', 'gt_ignore_inds', '=', 'np.concatenate((np.zeros(gt_bboxes.shape[0],', 'dtype=np.bool),', 'np.ones(gt_bboxes_ignore.shape[0],', 'dtype=np.bool)))', 'gt_bboxes', '=', 'np.vstack((gt_bboxes,', 'gt_bb... | 653,699 |
bachiraoun/fullrmc | Engine.py | Engine.moleculesIndex | moleculesIndex | Atoms molecule index list. | [
"Atoms",
"molecule",
"index",
"list."
] | def moleculesIndex(self):
return self.__moleculesIndex | ['def', 'moleculesIndex(self):', 'return', 'self.__moleculesIndex'] | 213,410 |
k2kobayashi/crank | sinc_conv.py | MelScale.convert | convert | Convert Hz to mel. | [
"Convert",
"Hz",
"to",
"mel."
] | def convert(f):
return 1125.0 * torch.log(torch.div(f, 700.0) + 1.0) | ['def', 'convert(f):', 'return', '1125.0', '*', 'torch.log(torch.div(f,', '700.0)', '+', '1.0)'] | 490,664 |
GatorEducator/GatorMiner | streamlit_web.py | entities | entities | Page to display entity analysis. | [
"Page",
"to",
"display",
"entity",
"analysis."
] | def entities():
st.write('Entity analysis inspects the given text for known entities and returns information about those entities. It is a way to extract information that seeks to locate and classify named entities in text into pre-defined categories such as the names of persons, organizations, loca... | ['def', 'entities():', "st.write('Entity", 'analysis', 'inspects', 'the', 'given', 'text', 'for', 'known', 'entities', 'and', 'returns', 'information', 'about', 'those', 'entities.', 'It', 'is', 'a', 'way', 'to', 'extract', 'information', 'that', 'seeks', 'to', 'locate', 'and', 'classify', 'named', 'entities', 'in', 't... | 567,429 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | texmanager.py | TexManager.get_font_preamble | get_font_preamble | Return a string containing font configuration for the tex preamble. | [
"Return",
"a",
"string",
"containing",
"font",
"configuration",
"for",
"the",
"tex",
"preamble."
] | def get_font_preamble(self):
return self._font_preamble | ['def', 'get_font_preamble(self):', 'return', 'self._font_preamble'] | 257,290 |
mhubii/artificial_intelligence | tarfile.py | TarInfo.create_gnu_header | create_gnu_header | Return the object as a GNU header block sequence. | [
"Return",
"the",
"object",
"as",
"a",
"GNU",
"header",
"block",
"sequence."
] | def create_gnu_header(self, info, encoding, errors):
info['magic'] = GNU_MAGIC
buf = b''
if len(info['linkname']) > LENGTH_LINK:
buf += self._create_gnu_long_header(info['linkname'], GNUTYPE_LONGLINK, encoding, errors)
if len(info['name']) > LENGTH_NAME:
buf += self._create_gnu_long_head... | ['def', 'create_gnu_header(self,', 'info,', 'encoding,', 'errors):', "info['magic']", '=', 'GNU_MAGIC', 'buf', '=', "b''", 'if', "len(info['linkname'])", '>', 'LENGTH_LINK:', 'buf', '+=', "self._create_gnu_long_header(info['linkname'],", 'GNUTYPE_LONGLINK,', 'encoding,', 'errors)', 'if', "len(info['name'])", '>', 'LENG... | 154,716 |
rudranil723/mini-main | api.py | CorpusReader.fileids | fileids | Return a list of file identifiers for the fileids that make up this corpus. | [
"Return",
"a",
"list",
"of",
"file",
"identifiers",
"for",
"the",
"fileids",
"that",
"make",
"up",
"this",
"corpus."
] | def fileids(self):
return self._fileids | ['def', 'fileids(self):', 'return', 'self._fileids'] | 320,910 |
Pari02/Natural-Language-Processing | tfidf.py | TfIdf.candidate_selection | candidate_selection | Select 1-3 grams as keyphrase candidates. | [
"Select",
"1-3",
"grams",
"as",
"keyphrase",
"candidates."
] | def candidate_selection(self, n=3, stoplist=None, **kwargs):
self.ngram_selection(n=n)
if stoplist is None:
stoplist = list(string.punctuation)
self.candidate_filtering(stoplist=stoplist) | ['def', 'candidate_selection(self,', 'n=3,', 'stoplist=None,', '**kwargs):', 'self.ngram_selection(n=n)', 'if', 'stoplist', 'is', 'None:', 'stoplist', '=', 'list(string.punctuation)', 'self.candidate_filtering(stoplist=stoplist)'] | 662,266 |
mj-will/nessai | test_model.py | test_bounds | test_bounds | Assert bounds returns the correct value. | [
"Assert",
"bounds",
"returns",
"the",
"correct",
"value."
] | def test_bounds(model):
model._bounds = {'x': [-1, 1], 'y': [-1, 1]}
assert Model.bounds.__get__(model) is model._bounds | ['def', 'test_bounds(model):', 'model._bounds', '=', "{'x':", '[-1,', '1],', "'y':", '[-1,', '1]}', 'assert', 'Model.bounds.__get__(model)', 'is', 'model._bounds'] | 292,279 |
taokong/FoveaBox | transforms.py | bbox2result | bbox2result | Convert detection results to a list of numpy arrays. | [
"Convert",
"detection",
"results",
"to",
"a",
"list",
"of",
"numpy",
"arrays."
] | def bbox2result(bboxes, labels, num_classes):
if bboxes.shape[0] == 0:
return [np.zeros((0, 5), dtype=np.float32) for i in range(num_classes - 1)]
else:
bboxes = bboxes.cpu().numpy()
labels = labels.cpu().numpy()
return [bboxes[labels == i, :] for i in range(num_classes - 1)] | ['def', 'bbox2result(bboxes,', 'labels,', 'num_classes):', 'if', 'bboxes.shape[0]', '==', '0:', 'return', '[np.zeros((0,', '5),', 'dtype=np.float32)', 'for', 'i', 'in', 'range(num_classes', '-', '1)]', 'else:', 'bboxes', '=', 'bboxes.cpu().numpy()', 'labels', '=', 'labels.cpu().numpy()', 'return', '[bboxes[labels', '==... | 564,085 |
zhoroh/ObjectDetection | fp16util.py | convert_module | convert_module | Converts a module's immediate parameters and buffers to dtype. | [
"Converts",
"a",
"module's",
"immediate",
"parameters",
"and",
"buffers",
"to",
"dtype."
] | def convert_module(module, dtype):
for param in module.parameters(recurse=False):
if param is not None:
if param.data.dtype.is_floating_point:
param.data = param.data.to(dtype=dtype)
if param._grad is not None and param._grad.data.dtype.is_floating_point:
... | ['def', 'convert_module(module,', 'dtype):', 'for', 'param', 'in', 'module.parameters(recurse=False):', 'if', 'param', 'is', 'not', 'None:', 'if', 'param.data.dtype.is_floating_point:', 'param.data', '=', 'param.data.to(dtype=dtype)', 'if', 'param._grad', 'is', 'not', 'None', 'and', 'param._grad.data.dtype.is_floating_... | 744,382 |
Koushikl0l/Artificial-Intelligence | search.py | NQueensProblem.result | result | Place the next queen at the given row. | [
"Place",
"the",
"next",
"queen",
"at",
"the",
"given",
"row."
] | def result(self, state, row):
col = state.index(-1)
new = list(state[:])
new[col] = row
return tuple(new) | ['def', 'result(self,', 'state,', 'row):', 'col', '=', 'state.index(-1)', 'new', '=', 'list(state[:])', 'new[col]', '=', 'row', 'return', 'tuple(new)'] | 117,220 |
ELEKTRONN/elektronn3 | cnndata.py | PatchCreator.check_files | check_files | Check if all files are accessible. | [
"Check",
"if",
"all",
"files",
"are",
"accessible."
] | def check_files(self) -> None:
notfound = False
give_neuro_data_hint = False
fullpaths = [f for (f, _) in self.input_sources]
if self.target_sources is not None:
fullpaths.extend([f for (f, _) in self.target_sources])
for p in fullpaths:
if not os.path.exists(p):
print('{... | ['def', 'check_files(self)', '->', 'None:', 'notfound', '=', 'False', 'give_neuro_data_hint', '=', 'False', 'fullpaths', '=', '[f', 'for', '(f,', '_)', 'in', 'self.input_sources]', 'if', 'self.target_sources', 'is', 'not', 'None:', 'fullpaths.extend([f', 'for', '(f,', '_)', 'in', 'self.target_sources])', 'for', 'p', 'i... | 175,599 |
sarnsdev/social-alignment-data-mining | utils.py | hash_from_file | hash_from_file | Return the SHA256 hash of a file. | [
"Return",
"the",
"SHA256",
"hash",
"of",
"a",
"file."
] | def hash_from_file(file_path):
with open(file_path, 'rb') as f:
file_content = f.read()
return hash_from_code(file_content) | ['def', 'hash_from_file(file_path):', 'with', 'open(file_path,', "'rb')", 'as', 'f:', 'file_content', '=', 'f.read()', 'return', 'hash_from_code(file_content)'] | 392,768 |
sarnsdev/social-alignment-data-mining | test_memory.py | test_memory_exception | test_memory_exception | Smoketest the exception handling of Memory. | [
"Smoketest",
"the",
"exception",
"handling",
"of",
"Memory."
] | def test_memory_exception(tmpdir):
memory = Memory(location=tmpdir.strpath, verbose=0)
class MyException(Exception):
pass
@memory.cache
def h(exc=0):
if exc:
raise MyException
h()
for _ in range(3):
with raises(MyException):
h(1) | ['def', 'test_memory_exception(tmpdir):', 'memory', '=', 'Memory(location=tmpdir.strpath,', 'verbose=0)', 'class', 'MyException(Exception):', 'pass', '@memory.cache', 'def', 'h(exc=0):', 'if', 'exc:', 'raise', 'MyException', 'h()', 'for', '_', 'in', 'range(3):', 'with', 'raises(MyException):', 'h(1)'] | 352,565 |
deepmind/dm_control | engine.py | Camera.option | option | Returns the camera's visualization options. | [
"Returns",
"the",
"camera's",
"visualization",
"options."
] | def option(self):
return self._scene_option | ['def', 'option(self):', 'return', 'self._scene_option'] | 166,179 |
jbwang1997/CrossKD | pisa_roi_head.py | PISARoIHead.bbox_loss | bbox_loss | Perform forward propagation and loss calculation of the bbox head on the features of the upstream network. | [
"Perform",
"forward",
"propagation",
"and",
"loss",
"calculation",
"of",
"the",
"bbox",
"head",
"on",
"the",
"features",
"of",
"the",
"upstream",
"network."
] | def bbox_loss(self, x: Tuple[Tensor], sampling_results: List[SamplingResult], neg_label_weights: List[Tensor]=None) -> dict:
rois = bbox2roi([res.priors for res in sampling_results])
bbox_results = self._bbox_forward(x, rois)
bbox_targets = self.bbox_head.get_targets(sampling_results, self.train_cfg)
if... | ['def', 'bbox_loss(self,', 'x:', 'Tuple[Tensor],', 'sampling_results:', 'List[SamplingResult],', 'neg_label_weights:', 'List[Tensor]=None)', '->', 'dict:', 'rois', '=', 'bbox2roi([res.priors', 'for', 'res', 'in', 'sampling_results])', 'bbox_results', '=', 'self._bbox_forward(x,', 'rois)', 'bbox_targets', '=', 'self.bbo... | 491,400 |
KalleHallden/InstaAutomator | config.py | config.check_compiler_gcc4 | check_compiler_gcc4 | Return True if the C compiler is gcc >= 4. | [
"Return",
"True",
"if",
"the",
"C",
"compiler",
"is",
"gcc",
">=",
"4."
] | def check_compiler_gcc4(self):
return check_compiler_gcc4(self) | ['def', 'check_compiler_gcc4(self):', 'return', 'check_compiler_gcc4(self)'] | 243,280 |
ADLab3Ds/TiG-BEV | waymo_dataset.py | WaymoDataset.bbox2result_kitti | bbox2result_kitti | Convert results to kitti format for evaluation and test submission. | [
"Convert",
"results",
"to",
"kitti",
"format",
"for",
"evaluation",
"and",
"test",
"submission."
] | def bbox2result_kitti(self, net_outputs, class_names, pklfile_prefix=None, submission_prefix=None):
assert len(net_outputs) == len(self.data_infos), 'invalid list length of network outputs'
if submission_prefix is not None:
mmcv.mkdir_or_exist(submission_prefix)
det_annos = []
print('\nConvertin... | ['def', 'bbox2result_kitti(self,', 'net_outputs,', 'class_names,', 'pklfile_prefix=None,', 'submission_prefix=None):', 'assert', 'len(net_outputs)', '==', 'len(self.data_infos),', "'invalid", 'list', 'length', 'of', 'network', "outputs'", 'if', 'submission_prefix', 'is', 'not', 'None:', 'mmcv.mkdir_or_exist(submission_... | 916,962 |
googleapis/python-aiplatform | pipeline_jobs.py | PipelineJob.submit | submit | Run this configured PipelineJob. | [
"Run",
"this",
"configured",
"PipelineJob."
] | def submit(self, service_account: Optional[str]=None, network: Optional[str]=None, create_request_timeout: Optional[float]=None, *, experiment: Optional[Union[str, experiment_resources.Experiment]]=None) -> None:
network = network or initializer.global_config.network
service_account = service_account or initial... | ['def', 'submit(self,', 'service_account:', 'Optional[str]=None,', 'network:', 'Optional[str]=None,', 'create_request_timeout:', 'Optional[float]=None,', '*,', 'experiment:', 'Optional[Union[str,', 'experiment_resources.Experiment]]=None)', '->', 'None:', 'network', '=', 'network', 'or', 'initializer.global_config.netw... | 809,826 |
rudranil723/mini-main | intranges.py | intranges_contain | intranges_contain | Determine if `int_` falls into one of the ranges in `ranges`. | [
"Determine",
"if",
"`int_`",
"falls",
"into",
"one",
"of",
"the",
"ranges",
"in",
"`ranges`."
] | def intranges_contain(int_: int, ranges: Tuple[int, ...]) -> bool:
tuple_ = _encode_range(int_, 0)
pos = bisect.bisect_left(ranges, tuple_)
if pos > 0:
(left, right) = _decode_range(ranges[pos - 1])
if left <= int_ < right:
return True
if pos < len(ranges):
(left, _) ... | ['def', 'intranges_contain(int_:', 'int,', 'ranges:', 'Tuple[int,', '...])', '->', 'bool:', 'tuple_', '=', '_encode_range(int_,', '0)', 'pos', '=', 'bisect.bisect_left(ranges,', 'tuple_)', 'if', 'pos', '>', '0:', '(left,', 'right)', '=', '_decode_range(ranges[pos', '-', '1])', 'if', 'left', '<=', 'int_', '<', 'right:',... | 318,768 |
adamshamsudeen/vision.ai | core.py | Parameter.process_value | process_value | Given a value and context this runs the logic to convert the value as necessary. | [
"Given",
"a",
"value",
"and",
"context",
"this",
"runs",
"the",
"logic",
"to",
"convert",
"the",
"value",
"as",
"necessary."
] | def process_value(self, ctx, value):
if value is not None:
return self.type_cast_value(ctx, value) | ['def', 'process_value(self,', 'ctx,', 'value):', 'if', 'value', 'is', 'not', 'None:', 'return', 'self.type_cast_value(ctx,', 'value)'] | 942,774 |
arshpreetsingh/quantopian-machinelearning | base.py | IndexOpsMixin.ndim | ndim | Number of dimensions of the underlying data, by definition 1. | [
"Number",
"of",
"dimensions",
"of",
"the",
"underlying",
"data,",
"by",
"definition",
"1."
] | def ndim(self):
return 1 | ['def', 'ndim(self):', 'return', '1'] | 889,548 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | __init__.py | Config.last | last | Returns the value at the key from the last config defining it. | [
"Returns",
"the",
"value",
"at",
"the",
"key",
"from",
"the",
"last",
"config",
"defining",
"it."
] | def last(self, key, default=None):
for config in reversed(self.configs):
if hasattr(config, key):
return getattr(config, key)
return default | ['def', 'last(self,', 'key,', 'default=None):', 'for', 'config', 'in', 'reversed(self.configs):', 'if', 'hasattr(config,', 'key):', 'return', 'getattr(config,', 'key)', 'return', 'default'] | 11,320 |
Qualcomm-AI-research/weakly-supervised-causal-representation- | scm.py | FixedOrderSCM.log_prob_noise_weakly_supervised | log_prob_noise_weakly_supervised | Given weakly supervised as noise encodings epsilon1, epsilon2 and the intervention mask, computes the corresponding causal variables and log likelihoods. | [
"Given",
"weakly",
"supervised",
"as",
"noise",
"encodings",
"epsilon1,",
"epsilon2",
"and",
"the",
"intervention",
"mask,",
"computes",
"the",
"corresponding",
"causal",
"variables",
"and",
"log",
"likelihoods."
] | def log_prob_noise_weakly_supervised(self, epsilon1, epsilon2, intervention, adjacency_matrix):
raise NotImplementedError | ['def', 'log_prob_noise_weakly_supervised(self,', 'epsilon1,', 'epsilon2,', 'intervention,', 'adjacency_matrix):', 'raise', 'NotImplementedError'] | 373,211 |
cqlengine/cqlengine | test_updates.py | ModelUpdateTests.test_noop_model_update | test_noop_model_update | tests that calling update on a model with no changes will do nothing. | [
"tests",
"that",
"calling",
"update",
"on",
"a",
"model",
"with",
"no",
"changes",
"will",
"do",
"nothing."
] | def test_noop_model_update(self):
m0 = TestUpdateModel.create(count=5, text='monkey')
with patch.object(self.session, 'execute') as execute:
m0.update()
assert execute.call_count == 0
with patch.object(self.session, 'execute') as execute:
m0.update(count=5)
assert execute.call_count ... | ['def', 'test_noop_model_update(self):', 'm0', '=', 'TestUpdateModel.create(count=5,', "text='monkey')", 'with', 'patch.object(self.session,', "'execute')", 'as', 'execute:', 'm0.update()', 'assert', 'execute.call_count', '==', '0', 'with', 'patch.object(self.session,', "'execute')", 'as', 'execute:', 'm0.update(count=... | 138,350 |
facebookresearch/CompilerGym | env_without_bazel_test.py | test_invalid_reward_space | test_invalid_reward_space | Test error handling with invalid reward space. | [
"Test",
"error",
"handling",
"with",
"invalid",
"reward",
"space."
] | def test_invalid_reward_space(env: CompilerEnv):
with pytest.raises(LookupError):
env.reward_space = 100 | ['def', 'test_invalid_reward_space(env:', 'CompilerEnv):', 'with', 'pytest.raises(LookupError):', 'env.reward_space', '=', '100'] | 135,636 |
paulorauber/rl | transforms.py | Transform.reset | reset | Resets a transform if it is stateful. | [
"Resets",
"a",
"transform",
"if",
"it",
"is",
"stateful."
] | def reset(self, tensordict: TensorDictBase) -> TensorDictBase:
return tensordict | ['def', 'reset(self,', 'tensordict:', 'TensorDictBase)', '->', 'TensorDictBase:', 'return', 'tensordict'] | 859,128 |
jimtin/Stock_Comparison | test_paths.py | test_get_ipython_dir_2 | test_get_ipython_dir_2 | test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions. | [
"test_get_ipython_dir_2,",
"Testcase",
"to",
"see",
"if",
"we",
"can",
"call",
"get_ipython_dir",
"without",
"Exceptions."
] | def test_get_ipython_dir_2():
with patch_get_home_dir('someplace'), patch.object(paths, 'get_xdg_dir', return_value=None), patch.object(paths, '_writable_dir', return_value=True), patch('os.name', 'posix'), modified_env({'IPYTHON_DIR': None, 'IPYTHONDIR': None, 'XDG_CONFIG_HOME': None}):
ipdir = paths.get_i... | ['def', 'test_get_ipython_dir_2():', 'with', "patch_get_home_dir('someplace'),", 'patch.object(paths,', "'get_xdg_dir',", 'return_value=None),', 'patch.object(paths,', "'_writable_dir',", 'return_value=True),', "patch('os.name',", "'posix'),", "modified_env({'IPYTHON_DIR':", 'None,', "'IPYTHONDIR':", 'None,', "'XDG_CON... | 385,124 |
fyqqyf/UC-Berkeley-CS188-2020 | inference.py | InferenceModule.observe | observe | Collect the relevant noisy distance observation and pass it along. | [
"Collect",
"the",
"relevant",
"noisy",
"distance",
"observation",
"and",
"pass",
"it",
"along."
] | def observe(self, gameState):
distances = gameState.getNoisyGhostDistances()
if len(distances) >= self.index:
obs = distances[self.index - 1]
self.obs = obs
self.observeUpdate(obs, gameState) | ['def', 'observe(self,', 'gameState):', 'distances', '=', 'gameState.getNoisyGhostDistances()', 'if', 'len(distances)', '>=', 'self.index:', 'obs', '=', 'distances[self.index', '-', '1]', 'self.obs', '=', 'obs', 'self.observeUpdate(obs,', 'gameState)'] | 427,069 |
xyc2690/Raspberry_ObjectDetection_Camera | model_test.py | ModelTflearnTest.testModelFnInEvalMode | testModelFnInEvalMode | Tests the model function in EVAL mode. | [
"Tests",
"the",
"model",
"function",
"in",
"EVAL",
"mode."
] | def testModelFnInEvalMode(self):
configs = _get_configs_for_model(MODEL_NAME_FOR_TEST)
self._assert_outputs_for_train_eval(configs, tf.estimator.ModeKeys.EVAL) | ['def', 'testModelFnInEvalMode(self):', 'configs', '=', '_get_configs_for_model(MODEL_NAME_FOR_TEST)', 'self._assert_outputs_for_train_eval(configs,', 'tf.estimator.ModeKeys.EVAL)'] | 838,421 |
ahangchen/ncs_detection | visualization_utils.py | draw_bounding_boxes_on_image | draw_bounding_boxes_on_image | Draws bounding boxes on image. | [
"Draws",
"bounding",
"boxes",
"on",
"image."
] | def draw_bounding_boxes_on_image(image, boxes, color='red', thickness=4, display_str_list_list=()):
boxes_shape = boxes.shape
if not boxes_shape:
return
if len(boxes_shape) != 2 or boxes_shape[1] != 4:
raise ValueError('Input must be of size [N, 4]')
for i in range(boxes_shape[0]):
... | ['def', 'draw_bounding_boxes_on_image(image,', 'boxes,', "color='red',", 'thickness=4,', 'display_str_list_list=()):', 'boxes_shape', '=', 'boxes.shape', 'if', 'not', 'boxes_shape:', 'return', 'if', 'len(boxes_shape)', '!=', '2', 'or', 'boxes_shape[1]', '!=', '4:', 'raise', "ValueError('Input", 'must', 'be', 'of', 'siz... | 735,117 |
weimin17/Object-Detection_HelmetDetection | detection_inference.py | build_inference_graph | build_inference_graph | Loads the inference graph and connects it to the input image. | [
"Loads",
"the",
"inference",
"graph",
"and",
"connects",
"it",
"to",
"the",
"input",
"image."
] | def build_inference_graph(image_tensor, inference_graph_path):
with tf.gfile.Open(inference_graph_path, 'r') as graph_def_file:
graph_content = graph_def_file.read()
graph_def = tf.GraphDef()
graph_def.MergeFromString(graph_content)
tf.import_graph_def(graph_def, name='', input_map={'image_tenso... | ['def', 'build_inference_graph(image_tensor,', 'inference_graph_path):', 'with', 'tf.gfile.Open(inference_graph_path,', "'r')", 'as', 'graph_def_file:', 'graph_content', '=', 'graph_def_file.read()', 'graph_def', '=', 'tf.GraphDef()', 'graph_def.MergeFromString(graph_content)', 'tf.import_graph_def(graph_def,', "name='... | 758,852 |
noambassat/SpeechTrainer | tarfile.py | _FileInFile.seek | seek | Seek to a position in the file. | [
"Seek",
"to",
"a",
"position",
"in",
"the",
"file."
] | def seek(self, position):
self.position = position | ['def', 'seek(self,', 'position):', 'self.position', '=', 'position'] | 895,450 |
facebookresearch/deep_bisim4control | pendulum.py | Physics.pole_orientation | pole_orientation | Returns both horizontal and vertical components of pole frame. | [
"Returns",
"both",
"horizontal",
"and",
"vertical",
"components",
"of",
"pole",
"frame."
] | def pole_orientation(self):
return self.named.data.xmat['pole', ['zz', 'xz']] | ['def', 'pole_orientation(self):', 'return', "self.named.data.xmat['pole',", "['zz',", "'xz']]"] | 536,418 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | real_nvp_utils.py | as_one_hot | as_one_hot | Convert indices to one-hot. | [
"Convert",
"indices",
"to",
"one-hot."
] | def as_one_hot(input_, n_indices):
shape = input_.get_shape().as_list()
n_elem = numpy.prod(shape)
indices = tf.range(n_elem)
indices = tf.cast(indices, tf.int64)
indices_input = tf.concat(axis=0, values=[indices, tf.reshape(input_, [-1])])
indices_input = tf.reshape(indices_input, [2, -1])
... | ['def', 'as_one_hot(input_,', 'n_indices):', 'shape', '=', 'input_.get_shape().as_list()', 'n_elem', '=', 'numpy.prod(shape)', 'indices', '=', 'tf.range(n_elem)', 'indices', '=', 'tf.cast(indices,', 'tf.int64)', 'indices_input', '=', 'tf.concat(axis=0,', 'values=[indices,', 'tf.reshape(input_,', '[-1])])', 'indices_inp... | 109,422 |
wandb/wandb | util.py | add_metaclass | add_metaclass | Class decorator for creating a class with a metaclass. | [
"Class",
"decorator",
"for",
"creating",
"a",
"class",
"with",
"a",
"metaclass."
] | def add_metaclass(metaclass):
def wrapper(cls):
orig_vars = cls.__dict__.copy()
orig_vars.pop('__dict__', None)
orig_vars.pop('__weakref__', None)
for slots_var in orig_vars.get('__slots__', ()):
orig_vars.pop(slots_var)
return metaclass(cls.__name__, cls.__bases... | ['def', 'add_metaclass(metaclass):', 'def', 'wrapper(cls):', 'orig_vars', '=', 'cls.__dict__.copy()', "orig_vars.pop('__dict__',", 'None)', "orig_vars.pop('__weakref__',", 'None)', 'for', 'slots_var', 'in', "orig_vars.get('__slots__',", '()):', 'orig_vars.pop(slots_var)', 'return', 'metaclass(cls.__name__,', 'cls.__bas... | 942,053 |
matsu0228/nlp-jp | connection.py | MWSConnection.register_destination | register_destination | Specifies a new destination where you want to receive notifications. | [
"Specifies",
"a",
"new",
"destination",
"where",
"you",
"want",
"to",
"receive",
"notifications."
] | def register_destination(self, request, response, **kw):
return self._post_request(request, kw, response) | ['def', 'register_destination(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)'] | 784,996 |
weimin17/Object-Detection_HelmetDetection | create_timit_dataset.py | create_tfrecord_from_wavs | create_tfrecord_from_wavs | Writes processed wav files to disk as sharded TFRecord files. | [
"Writes",
"processed",
"wav",
"files",
"to",
"disk",
"as",
"sharded",
"TFRecord",
"files."
] | def create_tfrecord_from_wavs(wavs, output_file):
with tf.python_io.TFRecordWriter(output_file) as builder:
for wav in wavs:
builder.write(wav.astype(np.float32).tobytes()) | ['def', 'create_tfrecord_from_wavs(wavs,', 'output_file):', 'with', 'tf.python_io.TFRecordWriter(output_file)', 'as', 'builder:', 'for', 'wav', 'in', 'wavs:', 'builder.write(wav.astype(np.float32).tobytes())'] | 750,015 |
Kurotsuba/CVProjectVideoAvatar | robustifiers.py | GMOf | GMOf | Given x and sigma in some units (say mm), returns robustified values (in same units), by making use of the Geman-McClure robustifier. | [
"Given",
"x",
"and",
"sigma",
"in",
"some",
"units",
"(say",
"mm),",
"returns",
"robustified",
"values",
"(in",
"same",
"units),",
"by",
"making",
"use",
"of",
"the",
"Geman-McClure",
"robustifier."
] | def GMOf(x, sigma):
result = SignedSqrt(x=GMOfInternal(x=x, sigma=sigma))
return result | ['def', 'GMOf(x,', 'sigma):', 'result', '=', 'SignedSqrt(x=GMOfInternal(x=x,', 'sigma=sigma))', 'return', 'result'] | 523,360 |
metadriverse/metadrive | effect.py | Effect.do_load | do_load | Internal method to load the effect from the given filename, do not use this directly, instead use load(). | [
"Internal",
"method",
"to",
"load",
"the",
"effect",
"from",
"the",
"given",
"filename,",
"do",
"not",
"use",
"this",
"directly,",
"instead",
"use",
"load()."
] | def do_load(self, filename):
self.filename = filename
self.effect_name = self._convert_filename_to_name(filename)
self.effect_hash = self._generate_hash(filename, self._options)
parsed_yaml = load_yaml_file(filename) or {}
self._parse_content(parsed_yaml)
for pass_id in self._PASSES:
ver... | ['def', 'do_load(self,', 'filename):', 'self.filename', '=', 'filename', 'self.effect_name', '=', 'self._convert_filename_to_name(filename)', 'self.effect_hash', '=', 'self._generate_hash(filename,', 'self._options)', 'parsed_yaml', '=', 'load_yaml_file(filename)', 'or', '{}', 'self._parse_content(parsed_yaml)', 'for',... | 633,957 |
neokarn/computer_vision | ssd_meta_arch.py | SSDFeatureExtractor.restore_from_classification_checkpoint_fn | restore_from_classification_checkpoint_fn | Returns a map of variables to load from a foreign checkpoint. | [
"Returns",
"a",
"map",
"of",
"variables",
"to",
"load",
"from",
"a",
"foreign",
"checkpoint."
] | def restore_from_classification_checkpoint_fn(self, feature_extractor_scope):
variables_to_restore = {}
for variable in tf.global_variables():
var_name = variable.op.name
if var_name.startswith(feature_extractor_scope + '/'):
var_name = var_name.replace(feature_extractor_scope + '/',... | ['def', 'restore_from_classification_checkpoint_fn(self,', 'feature_extractor_scope):', 'variables_to_restore', '=', '{}', 'for', 'variable', 'in', 'tf.global_variables():', 'var_name', '=', 'variable.op.name', 'if', 'var_name.startswith(feature_extractor_scope', '+', "'/'):", 'var_name', '=', 'var_name.replace(feature... | 510,960 |
Akash671/AI | heuristic_search.py | State.has_collected_coin_at_location | has_collected_coin_at_location | Returns True if the coin at the given location has been collected. | [
"Returns",
"True",
"if",
"the",
"coin",
"at",
"the",
"given",
"location",
"has",
"been",
"collected."
] | def has_collected_coin_at_location(self, x, y):
assert grid.is_coin(x, y)
return self.has_collected_coin(grid.get_coin_id(x, y)) | ['def', 'has_collected_coin_at_location(self,', 'x,', 'y):', 'assert', 'grid.is_coin(x,', 'y)', 'return', 'self.has_collected_coin(grid.get_coin_id(x,', 'y))'] | 69,786 |
weimin17/Object-Detection_HelmetDetection | policy.py | Policy.entropy | entropy | Calculate entropy of distribution. | [
"Calculate",
"entropy",
"of",
"distribution."
] | def entropy(self, logits, sampling_dim, act_dim, act_type):
if self.env_spec.is_discrete(act_type):
entropy = tf.reduce_sum(-tf.nn.softmax(logits) * tf.nn.log_softmax(logits), -1)
elif self.env_spec.is_box(act_type):
means = logits[:, :sampling_dim / 2]
std = logits[:, sampling_dim / 2:]... | ['def', 'entropy(self,', 'logits,', 'sampling_dim,', 'act_dim,', 'act_type):', 'if', 'self.env_spec.is_discrete(act_type):', 'entropy', '=', 'tf.reduce_sum(-tf.nn.softmax(logits)', '*', 'tf.nn.log_softmax(logits),', '-1)', 'elif', 'self.env_spec.is_box(act_type):', 'means', '=', 'logits[:,', ':sampling_dim', '/', '2]',... | 752,514 |
mkusner/grammarVAE | type.py | CLinkerType.c_literal | c_literal | Optional: WRITEME Parameters ---------- data : WRITEME WRITEME Raises ------ MethodNotDefined Subclass does not implement this method. | [
"Optional:",
"WRITEME",
"Parameters",
"----------",
"data",
":",
"WRITEME",
"WRITEME",
"Raises",
"------",
"MethodNotDefined",
"Subclass",
"does",
"not",
"implement",
"this",
"method."
] | def c_literal(self, data):
raise MethodNotDefined('c_literal', type(self), self.__class__.__name__) | ['def', 'c_literal(self,', 'data):', 'raise', "MethodNotDefined('c_literal',", 'type(self),', 'self.__class__.__name__)'] | 579,335 |
openvinotoolkit/training_extensions | report.py | get_otx_cli_ascii_banner | get_otx_cli_ascii_banner | Get OTX ASCII banner. | [
"Get",
"OTX",
"ASCII",
"banner."
] | def get_otx_cli_ascii_banner():
return '\n\n âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x95Â\x97 âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x95Â\x97 âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x95Â\x97 âÂ\x96Â\x88âÂ\x96Â\x88âÂ\x95Â... | ['def', 'get_otx_cli_ascii_banner():', 'return', "'\\n\\n", 'âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x95Â\\x97', 'âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x96Â\\x88âÂ\\x95Â\\x97', 'âÂ\\x96Â\\x88âÂ\\x96Â\\x8... | 919,028 |
rifqind/Agent-Programs-3KS1 | logger.py | Logger.logstate | logstate | Print a status message about the logger. | [
"Print",
"a",
"status",
"message",
"about",
"the",
"logger."
] | def logstate(self):
if self.logfile is None:
print('Logging has not been activated.')
else:
state = self.log_active and 'active' or 'temporarily suspended'
print('Filename :', self.logfname)
print('Mode :', self.logmode)
print('Output logging :', self.log_... | ['def', 'logstate(self):', 'if', 'self.logfile', 'is', 'None:', "print('Logging", 'has', 'not', 'been', "activated.')", 'else:', 'state', '=', 'self.log_active', 'and', "'active'", 'or', "'temporarily", "suspended'", "print('Filename", ":',", 'self.logfname)', "print('Mode", ":',", 'self.logmode)', "print('Output", 'lo... | 41,154 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nb_007a.py | Vocab.create | create | Create a vocabulary from a set of tokens. | [
"Create",
"a",
"vocabulary",
"from",
"a",
"set",
"of",
"tokens."
] | def create(cls, path: PathOrStr, tokens: Tokens, max_vocab: int, min_freq: int) -> 'Vocab':
freq = Counter((p for o in tokens for p in o))
itos = [o for (o, c) in freq.most_common(max_vocab) if c > min_freq]
itos.insert(0, PAD)
if UNK in itos:
itos.remove(UNK)
itos.insert(0, UNK)
pickle.... | ['def', 'create(cls,', 'path:', 'PathOrStr,', 'tokens:', 'Tokens,', 'max_vocab:', 'int,', 'min_freq:', 'int)', '->', "'Vocab':", 'freq', '=', 'Counter((p', 'for', 'o', 'in', 'tokens', 'for', 'p', 'in', 'o))', 'itos', '=', '[o', 'for', '(o,', 'c)', 'in', 'freq.most_common(max_vocab)', 'if', 'c', '>', 'min_freq]', 'itos.... | 81,649 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjvCameraWrapper.trackbodyid | trackbodyid | body id to track. | [
"body",
"id",
"to",
"track."
] | def trackbodyid(self):
return self._ptr.contents.trackbodyid | ['def', 'trackbodyid(self):', 'return', 'self._ptr.contents.trackbodyid'] | 440,721 |
arshpreetsingh/quantopian-machinelearning | base.py | ExtensionArray.dtype | dtype | An instance of 'ExtensionDtype'. | [
"An",
"instance",
"of",
"'ExtensionDtype'."
] | def dtype(self) -> ExtensionDtype:
raise AbstractMethodError(self) | ['def', 'dtype(self)', '->', 'ExtensionDtype:', 'raise', 'AbstractMethodError(self)'] | 889,718 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model_ptn.py | model_PTN.get_loss | get_loss | Computes the loss used for PTN paper (projection + volume loss). | [
"Computes",
"the",
"loss",
"used",
"for",
"PTN",
"paper",
"(projection",
"+",
"volume",
"loss)."
] | def get_loss(self, inputs, outputs):
g_loss = tf.zeros(dtype=tf.float32, shape=[])
if self._params.proj_weight:
g_loss += losses.add_volume_proj_loss(inputs, outputs, self._params.step_size, self._params.proj_weight)
if self._params.volume_weight:
g_loss += losses.add_volume_loss(inputs, out... | ['def', 'get_loss(self,', 'inputs,', 'outputs):', 'g_loss', '=', 'tf.zeros(dtype=tf.float32,', 'shape=[])', 'if', 'self._params.proj_weight:', 'g_loss', '+=', 'losses.add_volume_proj_loss(inputs,', 'outputs,', 'self._params.step_size,', 'self._params.proj_weight)', 'if', 'self._params.volume_weight:', 'g_loss', '+=', '... | 109,183 |
suarez12138/AI-Reversi_IMP_TextDichotomy | reduction.py | _ReducerRegistry.register | register | Attach a reducer function to a given type in the dispatch table. | [
"Attach",
"a",
"reducer",
"function",
"to",
"a",
"given",
"type",
"in",
"the",
"dispatch",
"table."
] | def register(cls, type, reduce_func):
if sys.version_info < (3,):
def dispatcher(cls, obj):
reduced = reduce_func(obj)
cls.save_reduce(*reduced, obj=obj)
cls.dispatch_table[type] = dispatcher
else:
cls.dispatch_table[type] = reduce_func | ['def', 'register(cls,', 'type,', 'reduce_func):', 'if', 'sys.version_info', '<', '(3,):', 'def', 'dispatcher(cls,', 'obj):', 'reduced', '=', 'reduce_func(obj)', 'cls.save_reduce(*reduced,', 'obj=obj)', 'cls.dispatch_table[type]', '=', 'dispatcher', 'else:', 'cls.dispatch_table[type]', '=', 'reduce_func'] | 95,935 |
rudranil723/mini-main | polygon.py | Polygon.kml | kml | Return the KML representation of this Polygon. | [
"Return",
"the",
"KML",
"representation",
"of",
"this",
"Polygon."
] | def kml(self):
inner_kml = ''.join(('<innerBoundaryIs>%s</innerBoundaryIs>' % self[i + 1].kml for i in range(self.num_interior_rings)))
return '<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>' % (self[0].kml, inner_kml) | ['def', 'kml(self):', 'inner_kml', '=', "''.join(('<innerBoundaryIs>%s</innerBoundaryIs>'", '%', 'self[i', '+', '1].kml', 'for', 'i', 'in', 'range(self.num_interior_rings)))', 'return', "'<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>'", '%', '(self[0].kml,', 'inner_kml)'] | 315,365 |
NoGameNoLife00/mybolg | tests.py | test_even | test_even | Return true if the variable is even. | [
"Return",
"true",
"if",
"the",
"variable",
"is",
"even."
] | def test_even(value):
return value % 2 == 0 | ['def', 'test_even(value):', 'return', 'value', '%', '2', '==', '0'] | 289,609 |
Alexander-Parker/youtube_nlp | common.py | raise_config_error | raise_config_error | Raise ConfigurationError with the given key name. | [
"Raise",
"ConfigurationError",
"with",
"the",
"given",
"key",
"name."
] | def raise_config_error(key, dummy):
raise ConfigurationError('Unknown option %s' % (key,)) | ['def', 'raise_config_error(key,', 'dummy):', 'raise', "ConfigurationError('Unknown", 'option', "%s'", '%', '(key,))'] | 970,350 |
Sea1004/artificial_intelligence | wheel.py | root_is_purelib | root_is_purelib | Return True if the extracted wheel in wheeldir should go into purelib. | [
"Return",
"True",
"if",
"the",
"extracted",
"wheel",
"in",
"wheeldir",
"should",
"go",
"into",
"purelib."
] | def root_is_purelib(name, wheeldir):
name_folded = name.replace('-', '_')
for item in os.listdir(wheeldir):
match = dist_info_re.match(item)
if match and match.group('name') == name_folded:
with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel:
for line in wheel:
... | ['def', 'root_is_purelib(name,', 'wheeldir):', 'name_folded', '=', "name.replace('-',", "'_')", 'for', 'item', 'in', 'os.listdir(wheeldir):', 'match', '=', 'dist_info_re.match(item)', 'if', 'match', 'and', "match.group('name')", '==', 'name_folded:', 'with', 'open(os.path.join(wheeldir,', 'item,', "'WHEEL'))", 'as', 'w... | 141,318 |
CosmiQ/solaris | evaluator_test.py | TestEvaluator.test_score_proposals | test_score_proposals | Test reading in a proposal GDF from a geojson and scoring it. | [
"Test",
"reading",
"in",
"a",
"proposal",
"GDF",
"from",
"a",
"geojson",
"and",
"scoring",
"it."
] | def test_score_proposals(self):
eb = Evaluator(os.path.join(solaris.data.data_dir, 'gt.geojson'))
eb.load_proposal(os.path.join(solaris.data.data_dir, 'pred.geojson'))
pred_gdf = solaris.data.pred_gdf()
assert eb.proposal_GDF.iloc[:, 0:3].sort_index().equals(pred_gdf)
expected_score = [{'class_id': ... | ['def', 'test_score_proposals(self):', 'eb', '=', 'Evaluator(os.path.join(solaris.data.data_dir,', "'gt.geojson'))", 'eb.load_proposal(os.path.join(solaris.data.data_dir,', "'pred.geojson'))", 'pred_gdf', '=', 'solaris.data.pred_gdf()', 'assert', 'eb.proposal_GDF.iloc[:,', '0:3].sort_index().equals(pred_gdf)', 'expecte... | 879,440 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.