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 |
|---|---|---|---|---|---|---|---|---|
Qbanxiaoxu/NaturalLanguageProcessingExperiment | operator.py | iconcat | iconcat | Same as a += b, for a and b sequences. | [
"Same",
"as",
"a",
"+=",
"b,",
"for",
"a",
"and",
"b",
"sequences."
] | def iconcat(a, b):
if not hasattr(a, '__getitem__'):
msg = "'%s' object can't be concatenated" % type(a).__name__
raise TypeError(msg)
a += b
return a | ['def', 'iconcat(a,', 'b):', 'if', 'not', 'hasattr(a,', "'__getitem__'):", 'msg', '=', '"\'%s\'', 'object', "can't", 'be', 'concatenated"', '%', 'type(a).__name__', 'raise', 'TypeError(msg)', 'a', '+=', 'b', 'return', 'a'] | 801,566 |
openremote/or-objectdetection | track.py | Track.mark_missed | mark_missed | Mark this track as missed (no association at the current time step). | [
"Mark",
"this",
"track",
"as",
"missed",
"(no",
"association",
"at",
"the",
"current",
"time",
"step)."
] | def mark_missed(self):
if self.state == TrackState.Tentative:
self.state = TrackState.Deleted
elif self.time_since_update > self._max_age:
self.state = TrackState.Deleted | ['def', 'mark_missed(self):', 'if', 'self.state', '==', 'TrackState.Tentative:', 'self.state', '=', 'TrackState.Deleted', 'elif', 'self.time_since_update', '>', 'self._max_age:', 'self.state', '=', 'TrackState.Deleted'] | 776,385 |
huawei-noah/xingtian | __init__.py | register_datasets | register_datasets | Import and register datasets automatically. | [
"Import",
"and",
"register",
"datasets",
"automatically."
] | def register_datasets(backend):
if backend == 'pytorch':
from . import pytorch
from .common.auto_lane_datasets import AutoLaneConfig
elif backend == 'tensorflow':
from . import tensorflow
if zeus.is_gpu_device():
from .common.auto_lane_datasets import AutoLaneConfig
... | ['def', 'register_datasets(backend):', 'if', 'backend', '==', "'pytorch':", 'from', '.', 'import', 'pytorch', 'from', '.common.auto_lane_datasets', 'import', 'AutoLaneConfig', 'elif', 'backend', '==', "'tensorflow':", 'from', '.', 'import', 'tensorflow', 'if', 'zeus.is_gpu_device():', 'from', '.common.auto_lane_dataset... | 962,459 |
tzaiyang/SpeechEmoRec | alexnet.py | lrn | lrn | Create a local response normalization layer. | [
"Create",
"a",
"local",
"response",
"normalization",
"layer."
] | def lrn(x, radius, alpha, beta, name, bias=1.0):
return tf.nn.local_response_normalization(x, depth_radius=radius, alpha=alpha, beta=beta, bias=bias, name=name) | ['def', 'lrn(x,', 'radius,', 'alpha,', 'beta,', 'name,', 'bias=1.0):', 'return', 'tf.nn.local_response_normalization(x,', 'depth_radius=radius,', 'alpha=alpha,', 'beta=beta,', 'bias=bias,', 'name=name)'] | 371,670 |
gunthercox/ChatterBot | session.py | Session.add_all | add_all | Add the given collection of instances to this ``Session``. | [
"Add",
"the",
"given",
"collection",
"of",
"instances",
"to",
"this",
"``Session``."
] | def add_all(self, instances):
for instance in instances:
self.add(instance) | ['def', 'add_all(self,', 'instances):', 'for', 'instance', 'in', 'instances:', 'self.add(instance)'] | 534,727 |
enuguru/artificial_intelligence_and_machine_learning | dist.py | Distribution.handle_display_options | handle_display_options | If there were any non-global "display-only" options (--help-commands or the metadata display options) on the command line, display the requested info and return true; else return false. | [
"If",
"there",
"were",
"any",
"non-global",
"\"display-only\"",
"options",
"(--help-commands",
"or",
"the",
"metadata",
"display",
"options)",
"on",
"the",
"command",
"line,",
"display",
"the",
"requested",
"info",
"and",
"return",
"true;",
"else",
"return",
"fals... | def handle_display_options(self, option_order):
import sys
if sys.version_info < (3,) or self.help_commands:
return _Distribution.handle_display_options(self, option_order)
import io
if not isinstance(sys.stdout, io.TextIOWrapper):
return _Distribution.handle_display_options(self, option... | ['def', 'handle_display_options(self,', 'option_order):', 'import', 'sys', 'if', 'sys.version_info', '<', '(3,)', 'or', 'self.help_commands:', 'return', '_Distribution.handle_display_options(self,', 'option_order)', 'import', 'io', 'if', 'not', 'isinstance(sys.stdout,', 'io.TextIOWrapper):', 'return', '_Distribution.ha... | 160,573 |
devashish-patel/webcam-motion-detector | base.py | Index.to_series | to_series | Create a Series with both index and values equal to the index keys useful with map for returning an indexer based on an index Returns ------- Series : dtype will be based on the type of the Index values. | [
"Create",
"a",
"Series",
"with",
"both",
"index",
"and",
"values",
"equal",
"to",
"the",
"index",
"keys",
"useful",
"with",
"map",
"for",
"returning",
"an",
"indexer",
"based",
"on",
"an",
"index",
"Returns",
"-------",
"Series",
":",
"dtype",
"will",
"be"... | def to_series(self, **kwargs):
from pandas import Series
return Series(self._to_embed(), index=self._shallow_copy(), name=self.name) | ['def', 'to_series(self,', '**kwargs):', 'from', 'pandas', 'import', 'Series', 'return', 'Series(self._to_embed(),', 'index=self._shallow_copy(),', 'name=self.name)'] | 982,091 |
43Carrig/recurrent_neural_networks_practice | ops.py | Operation.inputs | inputs | The list of `Tensor` objects representing the data inputs of this op. | [
"The",
"list",
"of",
"`Tensor`",
"objects",
"representing",
"the",
"data",
"inputs",
"of",
"this",
"op."
] | def inputs(self):
if self._inputs_val is None:
tf_outputs = c_api.GetOperationInputs(self._c_op)
retval = [self.graph._get_tensor_by_tf_output(tf_output) for tf_output in tf_outputs]
self._inputs_val = Operation._InputList(retval)
return self._inputs_val | ['def', 'inputs(self):', 'if', 'self._inputs_val', 'is', 'None:', 'tf_outputs', '=', 'c_api.GetOperationInputs(self._c_op)', 'retval', '=', '[self.graph._get_tensor_by_tf_output(tf_output)', 'for', 'tf_output', 'in', 'tf_outputs]', 'self._inputs_val', '=', 'Operation._InputList(retval)', 'return', 'self._inputs_val'] | 336,394 |
apeterswu/RL4NMT | common_attention.py | split_heads_2d | split_heads_2d | Split channels (dimension 4) into multiple heads (becomes dimension 1). | [
"Split",
"channels",
"(dimension",
"4)",
"into",
"multiple",
"heads",
"(becomes",
"dimension",
"1)."
] | def split_heads_2d(x, num_heads):
return tf.transpose(split_last_dimension(x, num_heads), [0, 3, 1, 2, 4]) | ['def', 'split_heads_2d(x,', 'num_heads):', 'return', 'tf.transpose(split_last_dimension(x,', 'num_heads),', '[0,', '3,', '1,', '2,', '4])'] | 331,455 |
accel-brain/accel-brain-code | variational_auto_encoder.py | VariationalAutoEncoder.inference | inference | Inference the feature points. | [
"Inference",
"the",
"feature",
"points."
] | def inference(self, observed_arr):
pred_arr = self.forward(observed_arr)
return pred_arr | ['def', 'inference(self,', 'observed_arr):', 'pred_arr', '=', 'self.forward(observed_arr)', 'return', 'pred_arr'] | 6,993 |
AndrewYinLi/lstm-neural-network-spam-filter | api.py | ClusterI.cluster_name | cluster_name | Returns the names of the cluster at index. | [
"Returns",
"the",
"names",
"of",
"the",
"cluster",
"at",
"index."
] | def cluster_name(self, index):
return index | ['def', 'cluster_name(self,', 'index):', 'return', 'index'] | 217,597 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | caption_generator.py | TopN.push | push | Pushes a new element. | [
"Pushes",
"a",
"new",
"element."
] | def push(self, x):
assert self._data is not None
if len(self._data) < self._n:
heapq.heappush(self._data, x)
else:
heapq.heappushpop(self._data, x) | ['def', 'push(self,', 'x):', 'assert', 'self._data', 'is', 'not', 'None', 'if', 'len(self._data)', '<', 'self._n:', 'heapq.heappush(self._data,', 'x)', 'else:', 'heapq.heappushpop(self._data,', 'x)'] | 48,759 |
gopinath-balu/computer_vision | coco_evaluation_test.py | CocoDetectionEvaluationTest.testGetOneMAPWithMatchingGroundtruthAndDetectionsEmptyCrowd | testGetOneMAPWithMatchingGroundtruthAndDetectionsEmptyCrowd | Tests computing mAP with empty is_crowd array passed in. | [
"Tests",
"computing",
"mAP",
"with",
"empty",
"is_crowd",
"array",
"passed",
"in."
] | def testGetOneMAPWithMatchingGroundtruthAndDetectionsEmptyCrowd(self):
coco_evaluator = coco_evaluation.CocoDetectionEvaluator(_get_categories_list())
coco_evaluator.add_single_ground_truth_image_info(image_id='image1', groundtruth_dict={standard_fields.InputDataFields.groundtruth_boxes: np.array([[100.0, 100.0... | ['def', 'testGetOneMAPWithMatchingGroundtruthAndDetectionsEmptyCrowd(self):', 'coco_evaluator', '=', 'coco_evaluation.CocoDetectionEvaluator(_get_categories_list())', "coco_evaluator.add_single_ground_truth_image_info(image_id='image1',", 'groundtruth_dict={standard_fields.InputDataFields.groundtruth_boxes:', 'np.array... | 511,220 |
salesforce/CodeRL | run_summarization.py | format_summary | format_summary | Transforms the output of the `from_batch` function into nicely formatted summaries. | [
"Transforms",
"the",
"output",
"of",
"the",
"`from_batch`",
"function",
"into",
"nicely",
"formatted",
"summaries."
] | def format_summary(translation):
(raw_summary, _, _) = translation
summary = raw_summary.replace('[unused0]', '').replace('[unused3]', '').replace('[PAD]', '').replace('[unused1]', '').replace(' +', ' ').replace(' [unused2] ', '. ').replace('[unused2]', '').strip()
return summary | ['def', 'format_summary(translation):', '(raw_summary,', '_,', '_)', '=', 'translation', 'summary', '=', "raw_summary.replace('[unused0]',", "'').replace('[unused3]',", "'').replace('[PAD]',", "'').replace('[unused1]',", "'').replace('", "+',", "'", "').replace('", '[unused2]', "',", "'.", "').replace('[unused2]',", "'... | 493,743 |
TangJiahui/6.034_Artificial_Intelligence | bayes_api.py | BayesNet.link | link | Make var_parent a parent of var_child. | [
"Make",
"var_parent",
"a",
"parent",
"of",
"var_child."
] | def link(self, var_parent, var_child):
if var_parent not in self.adjacency:
self.adjacency[var_parent] = set([])
self.adjacency[var_parent].add(var_child)
return self | ['def', 'link(self,', 'var_parent,', 'var_child):', 'if', 'var_parent', 'not', 'in', 'self.adjacency:', 'self.adjacency[var_parent]', '=', 'set([])', 'self.adjacency[var_parent].add(var_child)', 'return', 'self'] | 5,034 |
deepmind/meltingpot | bot.py | get_config | get_config | Returns the config for the specified bot. | [
"Returns",
"the",
"config",
"for",
"the",
"specified",
"bot."
] | def get_config(bot_name: str) -> bot_configs.BotConfig:
return bot_configs.BOT_CONFIGS[bot_name] | ['def', 'get_config(bot_name:', 'str)', '->', 'bot_configs.BotConfig:', 'return', 'bot_configs.BOT_CONFIGS[bot_name]'] | 285,601 |
ifwe/digsby | imwin_ctrl.py | ImWinCtrl.set_profile_html | set_profile_html | Sets the HTML info window's contents to buddy's profile. | [
"Sets",
"the",
"HTML",
"info",
"window's",
"contents",
"to",
"buddy's",
"profile."
] | def set_profile_html(self, buddy):
profilewindow = self.profile_html
try:
html = GetInfo(self.Buddy, showprofile=True, showhide=False, overflow_hidden=False)
except Exception:
print_exc()
html = buddy.name
with self.Frozen():
profilewindow.SetHTML(html) | ['def', 'set_profile_html(self,', 'buddy):', 'profilewindow', '=', 'self.profile_html', 'try:', 'html', '=', 'GetInfo(self.Buddy,', 'showprofile=True,', 'showhide=False,', 'overflow_hidden=False)', 'except', 'Exception:', 'print_exc()', 'html', '=', 'buddy.name', 'with', 'self.Frozen():', 'profilewindow.SetHTML(html)'] | 185,392 |
Ruturaj123/Flowchart-Detection | sparse_tensor.py | SparseTensor.dtype | dtype | The `DType` of elements in this tensor. | [
"The",
"`DType`",
"of",
"elements",
"in",
"this",
"tensor."
] | def dtype(self):
return self._values.dtype | ['def', 'dtype(self):', 'return', 'self._values.dtype'] | 605,491 |
weimin17/Object-Detection_HelmetDetection | data_utils.py | split_by_punct | split_by_punct | Splits str segment by punctuation, filters our empties and spaces. | [
"Splits",
"str",
"segment",
"by",
"punctuation,",
"filters",
"our",
"empties",
"and",
"spaces."
] | def split_by_punct(segment):
return [s for s in re.split('\\W+', segment) if s and (not s.isspace())] | ['def', 'split_by_punct(segment):', 'return', '[s', 'for', 's', 'in', "re.split('\\\\W+',", 'segment)', 'if', 's', 'and', '(not', 's.isspace())]'] | 761,495 |
s3prl/s3prl | sws2013_dataset.py | find_queries | find_queries | Find all queries under sws2013_dev & sws2013_eval. | [
"Find",
"all",
"queries",
"under",
"sws2013_dev",
"&",
"sws2013_eval."
] | def find_queries(query_dir_path):
pattern = re.compile('(_[0-9]{2})?\\.wav')
query2tensors = defaultdict(list)
for query_path in tqdm(list(query_dir_path.glob('*.wav')), ncols=0, desc='Load queries'):
query_name = pattern.sub('', query_path.name)
(wav_tensor, sample_rate) = apply_effects_fil... | ['def', 'find_queries(query_dir_path):', 'pattern', '=', "re.compile('(_[0-9]{2})?\\\\.wav')", 'query2tensors', '=', 'defaultdict(list)', 'for', 'query_path', 'in', "tqdm(list(query_dir_path.glob('*.wav')),", 'ncols=0,', "desc='Load", "queries'):", 'query_name', '=', "pattern.sub('',", 'query_path.name)', '(wav_tensor,... | 327,487 |
imoscovitz/wittgenstein | base.py | Ruleset.get_selected_features | get_selected_features | Return list of selected features in order they were added. | [
"Return",
"list",
"of",
"selected",
"features",
"in",
"order",
"they",
"were",
"added."
] | def get_selected_features(self):
feature_list = []
feature_set = set()
for rule in self.rules:
for cond in rule.conds:
feature = cond.feature
if feature not in feature_set:
feature_list.append(feature)
feature_set.add(feature)
return featur... | ['def', 'get_selected_features(self):', 'feature_list', '=', '[]', 'feature_set', '=', 'set()', 'for', 'rule', 'in', 'self.rules:', 'for', 'cond', 'in', 'rule.conds:', 'feature', '=', 'cond.feature', 'if', 'feature', 'not', 'in', 'feature_set:', 'feature_list.append(feature)', 'feature_set.add(feature)', 'return', 'fea... | 959,856 |
Mahesh-Shirsath/Natural-Language- | batcher.py | Example.pad_encoder_input | pad_encoder_input | For rewriter, pad the encoder input sequence with pad_id up to max_len. | [
"For",
"rewriter,",
"pad",
"the",
"encoder",
"input",
"sequence",
"with",
"pad_id",
"up",
"to",
"max_len."
] | def pad_encoder_input(self, max_len, pad_id):
while len(self.enc_input) < max_len:
self.enc_input.append(pad_id)
while len(self.enc_input_extend_vocab) < max_len:
self.enc_input_extend_vocab.append(pad_id)
if self.hps.model == 'end2end':
while len(self.enc_input_sent_ids) < max_len:
... | ['def', 'pad_encoder_input(self,', 'max_len,', 'pad_id):', 'while', 'len(self.enc_input)', '<', 'max_len:', 'self.enc_input.append(pad_id)', 'while', 'len(self.enc_input_extend_vocab)', '<', 'max_len:', 'self.enc_input_extend_vocab.append(pad_id)', 'if', 'self.hps.model', '==', "'end2end':", 'while', 'len(self.enc_inpu... | 665,856 |
OrvilleX/MachineLearning | i4features.py | edginess_sobel | edginess_sobel | Measure the "edginess" of an image image should be a 2d numpy array (an image) Returns a floating point value which is higher the "edgier" the image is. | [
"Measure",
"the",
"\"edginess\"",
"of",
"an",
"image",
"image",
"should",
"be",
"a",
"2d",
"numpy",
"array",
"(an",
"image)",
"Returns",
"a",
"floating",
"point",
"value",
"which",
"is",
"higher",
"the",
"\"edgier\"",
"the",
"image",
"is."
] | def edginess_sobel(image):
edges = mh.sobel(image, just_filter=True)
edges = edges.ravel()
return np.sqrt(np.dot(edges, edges)) | ['def', 'edginess_sobel(image):', 'edges', '=', 'mh.sobel(image,', 'just_filter=True)', 'edges', '=', 'edges.ravel()', 'return', 'np.sqrt(np.dot(edges,', 'edges))'] | 600,026 |
rnsandeep/ObjectDetection | box_utils.py | nms | nms | Apply non-maximum suppression at test time to avoid detecting too many overlapping bounding boxes for a given object. | [
"Apply",
"non-maximum",
"suppression",
"at",
"test",
"time",
"to",
"avoid",
"detecting",
"too",
"many",
"overlapping",
"bounding",
"boxes",
"for",
"a",
"given",
"object."
] | def nms(boxes, scores, overlap=0.5, top_k=200):
keep = torch.Tensor(scores.size(0)).fill_(0).long()
if boxes.numel() == 0:
return keep
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
area = torch.mul(x2 - x1, y2 - y1)
(v, idx) = scores.sort(0)
idx = idx[-t... | ['def', 'nms(boxes,', 'scores,', 'overlap=0.5,', 'top_k=200):', 'keep', '=', 'torch.Tensor(scores.size(0)).fill_(0).long()', 'if', 'boxes.numel()', '==', '0:', 'return', 'keep', 'x1', '=', 'boxes[:,', '0]', 'y1', '=', 'boxes[:,', '1]', 'x2', '=', 'boxes[:,', '2]', 'y2', '=', 'boxes[:,', '3]', 'area', '=', 'torch.mul(x2... | 742,405 |
kemaloksuz/RankSortLoss | pisa_loss.py | carl_loss | carl_loss | Classification-Aware Regression Loss (CARL). | [
"Classification-Aware",
"Regression",
"Loss",
"(CARL)."
] | def carl_loss(cls_score, labels, bbox_pred, bbox_targets, loss_bbox, k=1, bias=0.2, avg_factor=None, sigmoid=False, num_class=80):
pos_label_inds = ((labels >= 0) & (labels < num_class)).nonzero().reshape(-1)
if pos_label_inds.numel() == 0:
return dict(loss_carl=cls_score.sum()[None] * 0.0)
pos_labe... | ['def', 'carl_loss(cls_score,', 'labels,', 'bbox_pred,', 'bbox_targets,', 'loss_bbox,', 'k=1,', 'bias=0.2,', 'avg_factor=None,', 'sigmoid=False,', 'num_class=80):', 'pos_label_inds', '=', '((labels', '>=', '0)', '&', '(labels', '<', 'num_class)).nonzero().reshape(-1)', 'if', 'pos_label_inds.numel()', '==', '0:', 'retur... | 836,307 |
dustin/twitty-twister | test_streaming.py | LengthDelimitedStreamTest.test_receiveTwoDatagrams | test_receiveTwoDatagrams | Two encoded datagrams should result in two calls to datagramReceived. | [
"Two",
"encoded",
"datagrams",
"should",
"result",
"in",
"two",
"calls",
"to",
"datagramReceived."
] | def test_receiveTwoDatagrams(self):
self.protocol.dataReceived('4\r\ntest5\r\ntest2')
self.assertEquals(['test', 'test2'], self.protocol.datagrams)
self.assertEquals(0, self.protocol.keepAlives) | ['def', 'test_receiveTwoDatagrams(self):', "self.protocol.dataReceived('4\\r\\ntest5\\r\\ntest2')", "self.assertEquals(['test',", "'test2'],", 'self.protocol.datagrams)', 'self.assertEquals(0,', 'self.protocol.keepAlives)'] | 426,481 |
clvrai/spirl | sawyer.py | SawyerEnv.move_indicator | move_indicator | Sets 3d position of indicator object to @pos. | [
"Sets",
"3d",
"position",
"of",
"indicator",
"object",
"to",
"@pos."
] | def move_indicator(self, pos):
if self.use_indicator_object:
index = self._ref_indicator_pos_low
self.sim.data.qpos[index:index + 3] = pos | ['def', 'move_indicator(self,', 'pos):', 'if', 'self.use_indicator_object:', 'index', '=', 'self._ref_indicator_pos_low', 'self.sim.data.qpos[index:index', '+', '3]', '=', 'pos'] | 896,809 |
Z7Gao/CS181-Artificial-Intelligence | agents.py | RandomAgentProgram | RandomAgentProgram | An agent that chooses an action at random, ignoring all percepts. | [
"An",
"agent",
"that",
"chooses",
"an",
"action",
"at",
"random,",
"ignoring",
"all",
"percepts."
] | def RandomAgentProgram(actions):
return lambda percept: random.choice(actions) | ['def', 'RandomAgentProgram(actions):', 'return', 'lambda', 'percept:', 'random.choice(actions)'] | 220,706 |
MarvinBertin/Stanford-NLP-Course | Sentence.py | Sentence.getErrorSentence | getErrorSentence | Returns a list of strings with the sentence containing all errors. | [
"Returns",
"a",
"list",
"of",
"strings",
"with",
"the",
"sentence",
"containing",
"all",
"errors."
] | def getErrorSentence(self):
errorSentence = []
for datum in self.data:
if datum.hasError():
errorSentence.append(datum.error)
else:
errorSentence.append(datum.word)
return errorSentence | ['def', 'getErrorSentence(self):', 'errorSentence', '=', '[]', 'for', 'datum', 'in', 'self.data:', 'if', 'datum.hasError():', 'errorSentence.append(datum.error)', 'else:', 'errorSentence.append(datum.word)', 'return', 'errorSentence'] | 873,436 |
tusen-ai/SST | free_anchor3d_head.py | FreeAnchor3DHead.loss | loss | Calculate loss of FreeAnchor head. | [
"Calculate",
"loss",
"of",
"FreeAnchor",
"head."
] | def loss(self, cls_scores, bbox_preds, dir_cls_preds, gt_bboxes, gt_labels, input_metas, gt_bboxes_ignore=None):
featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
assert len(featmap_sizes) == self.anchor_generator.num_levels
anchor_list = self.get_anchors(featmap_sizes, input_metas)
anchor... | ['def', 'loss(self,', 'cls_scores,', 'bbox_preds,', 'dir_cls_preds,', 'gt_bboxes,', 'gt_labels,', 'input_metas,', 'gt_bboxes_ignore=None):', 'featmap_sizes', '=', '[featmap.size()[-2:]', 'for', 'featmap', 'in', 'cls_scores]', 'assert', 'len(featmap_sizes)', '==', 'self.anchor_generator.num_levels', 'anchor_list', '=', ... | 872,496 |
google-research/scenic | autoaugment.py | shear_x | shear_x | Equivalent of PIL Shearing in X dimension. | [
"Equivalent",
"of",
"PIL",
"Shearing",
"in",
"X",
"dimension."
] | def shear_x(image, level, replace):
image = contrib_image.transform(wrap(image), [1.0, level, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0])
return unwrap(image, replace) | ['def', 'shear_x(image,', 'level,', 'replace):', 'image', '=', 'contrib_image.transform(wrap(image),', '[1.0,', 'level,', '0.0,', '0.0,', '1.0,', '0.0,', '0.0,', '0.0])', 'return', 'unwrap(image,', 'replace)'] | 846,085 |
Uehwan/SimVODIS | __init__.py | evaluate | evaluate | evaluate dataset using different methods based on dataset type. | [
"evaluate",
"dataset",
"using",
"different",
"methods",
"based",
"on",
"dataset",
"type."
] | def evaluate(dataset, predictions, output_folder, **kwargs):
args = dict(dataset=dataset, predictions=predictions, output_folder=output_folder, **kwargs)
if isinstance(dataset, datasets.COCODataset):
return coco_evaluation(**args)
elif isinstance(dataset, datasets.PascalVOCDataset):
return v... | ['def', 'evaluate(dataset,', 'predictions,', 'output_folder,', '**kwargs):', 'args', '=', 'dict(dataset=dataset,', 'predictions=predictions,', 'output_folder=output_folder,', '**kwargs)', 'if', 'isinstance(dataset,', 'datasets.COCODataset):', 'return', 'coco_evaluation(**args)', 'elif', 'isinstance(dataset,', 'datasets... | 884,204 |
ruoqianguo/DetNet_pytorch | ds_utils.py | validate_boxes | validate_boxes | Check that a set of boxes are valid. | [
"Check",
"that",
"a",
"set",
"of",
"boxes",
"are",
"valid."
] | def validate_boxes(boxes, width=0, height=0):
x1 = boxes[:, 0]
y1 = boxes[:, 1]
x2 = boxes[:, 2]
y2 = boxes[:, 3]
assert (x1 >= 0).all()
assert (y1 >= 0).all()
assert (x2 >= x1).all()
assert (y2 >= y1).all()
assert (x2 < width).all()
assert (y2 < height).all() | ['def', 'validate_boxes(boxes,', 'width=0,', 'height=0):', 'x1', '=', 'boxes[:,', '0]', 'y1', '=', 'boxes[:,', '1]', 'x2', '=', 'boxes[:,', '2]', 'y2', '=', 'boxes[:,', '3]', 'assert', '(x1', '>=', '0).all()', 'assert', '(y1', '>=', '0).all()', 'assert', '(x2', '>=', 'x1).all()', 'assert', '(y2', '>=', 'y1).all()', 'as... | 549,626 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | norb_input_record_test.py | NorbInputRecordTest.testImageResize | testImageResize | Checks the returned image is resized to the given dimmensions. | [
"Checks",
"the",
"returned",
"image",
"is",
"resized",
"to",
"the",
"given",
"dimmensions."
] | def testImageResize(self):
with self.test_session(graph=tf.Graph()) as session:
features = norb_input_record.inputs(data_dir=os.path.join(DATA_DIR), batch_size=1, split='train', height=32, distort=False, batch_capacity=6)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(... | ['def', 'testImageResize(self):', 'with', 'self.test_session(graph=tf.Graph())', 'as', 'session:', 'features', '=', 'norb_input_record.inputs(data_dir=os.path.join(DATA_DIR),', 'batch_size=1,', "split='train',", 'height=32,', 'distort=False,', 'batch_capacity=6)', 'coord', '=', 'tf.train.Coordinator()', 'threads', '=',... | 53,204 |
piggyandy/artificial-intelligence | _internal.py | array_function_errmsg_formatter | array_function_errmsg_formatter | Format the error message for when __array_ufunc__ gives up. | [
"Format",
"the",
"error",
"message",
"for",
"when",
"__array_ufunc__",
"gives",
"up."
] | def array_function_errmsg_formatter(public_api, types):
func_name = '{}.{}'.format(public_api.__module__, public_api.__name__)
return "no implementation found for '{}' on types that implement __array_function__: {}".format(func_name, list(types)) | ['def', 'array_function_errmsg_formatter(public_api,', 'types):', 'func_name', '=', "'{}.{}'.format(public_api.__module__,", 'public_api.__name__)', 'return', '"no', 'implementation', 'found', 'for', "'{}'", 'on', 'types', 'that', 'implement', '__array_function__:', '{}".format(func_name,', 'list(types))'] | 60,912 |
AndrewYinLi/lstm-neural-network-spam-filter | tree.py | TreeWidget.bind_drag_nodes | bind_drag_nodes | Add a binding to all nodes. | [
"Add",
"a",
"binding",
"to",
"all",
"nodes."
] | def bind_drag_nodes(self, callback, button=1):
for node in self._nodes:
node.bind_drag(callback, button)
for node in self._nodes:
node.bind_drag(callback, button) | ['def', 'bind_drag_nodes(self,', 'callback,', 'button=1):', 'for', 'node', 'in', 'self._nodes:', 'node.bind_drag(callback,', 'button)', 'for', 'node', 'in', 'self._nodes:', 'node.bind_drag(callback,', 'button)'] | 217,882 |
iffiX/machin | pool.py | BasePool.imap | imap | Equivalent of `map()`, but will not store all results, instead, get one at a time in the sequential order. | [
"Equivalent",
"of",
"`map()`,",
"but",
"will",
"not",
"store",
"all",
"results,",
"instead,",
"get",
"one",
"at",
"a",
"time",
"in",
"the",
"sequential",
"order."
] | def imap(self, func: Callable[[Any], Any], iterable: Collection[Any], chunksize: int=1) -> Union[IMapIterator, List[Any]]:
return self._imap(func, iterable, IMapIterator, chunksize) | ['def', 'imap(self,', 'func:', 'Callable[[Any],', 'Any],', 'iterable:', 'Collection[Any],', 'chunksize:', 'int=1)', '->', 'Union[IMapIterator,', 'List[Any]]:', 'return', 'self._imap(func,', 'iterable,', 'IMapIterator,', 'chunksize)'] | 620,377 |
paulorauber/rl | transforms.py | RewardSum.transform_observation_spec | transform_observation_spec | Transforms the observation spec, adding the new keys generated by RewardSum. | [
"Transforms",
"the",
"observation",
"spec,",
"adding",
"the",
"new",
"keys",
"generated",
"by",
"RewardSum."
] | def transform_observation_spec(self, observation_spec: TensorSpec) -> TensorSpec:
if not isinstance(observation_spec, CompositeSpec):
observation_spec = CompositeSpec(observation=observation_spec, shape=self.parent.batch_size)
observation_spec.update(self._generate_episode_reward_spec())
return obse... | ['def', 'transform_observation_spec(self,', 'observation_spec:', 'TensorSpec)', '->', 'TensorSpec:', 'if', 'not', 'isinstance(observation_spec,', 'CompositeSpec):', 'observation_spec', '=', 'CompositeSpec(observation=observation_spec,', 'shape=self.parent.batch_size)', 'observation_spec.update(self._generate_episode_re... | 859,148 |
BLVLab/PiMAE | box_util.py | roty | roty | Rotation about the y-axis. | [
"Rotation",
"about",
"the",
"y-axis."
] | def roty(t):
c = np.cos(t)
s = np.sin(t)
return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) | ['def', 'roty(t):', 'c', '=', 'np.cos(t)', 's', '=', 'np.sin(t)', 'return', 'np.array([[c,', '0,', 's],', '[0,', '1,', '0],', '[-s,', '0,', 'c]])'] | 769,697 |
myothida/Supervised-Machine-Learning | __init__.py | FCompiler.get_flags_linker_so | get_flags_linker_so | List of linker flags to build a shared library. | [
"List",
"of",
"linker",
"flags",
"to",
"build",
"a",
"shared",
"library."
] | def get_flags_linker_so(self):
return self._get_command_flags('linker_so') | ['def', 'get_flags_linker_so(self):', 'return', "self._get_command_flags('linker_so')"] | 441,697 |
adamshamsudeen/vision.ai | _compat.py | get_best_encoding | get_best_encoding | Returns the default stream encoding if not found. | [
"Returns",
"the",
"default",
"stream",
"encoding",
"if",
"not",
"found."
] | def get_best_encoding(stream):
rv = getattr(stream, 'encoding', None) or sys.getdefaultencoding()
if is_ascii_encoding(rv):
return 'utf-8'
return rv | ['def', 'get_best_encoding(stream):', 'rv', '=', 'getattr(stream,', "'encoding',", 'None)', 'or', 'sys.getdefaultencoding()', 'if', 'is_ascii_encoding(rv):', 'return', "'utf-8'", 'return', 'rv'] | 942,836 |
LiYingwei/ghost-network | inception_resnet_v2.py | inception_resnet_v2_arg_scope | inception_resnet_v2_arg_scope | Returns the scope with the default parameters for inception_resnet_v2. | [
"Returns",
"the",
"scope",
"with",
"the",
"default",
"parameters",
"for",
"inception_resnet_v2."
] | def inception_resnet_v2_arg_scope(weight_decay=4e-05, batch_norm_decay=0.9997, batch_norm_epsilon=0.001, activation_fn=tf.nn.relu):
with slim.arg_scope([slim.conv2d, slim.fully_connected], weights_regularizer=slim.l2_regularizer(weight_decay), biases_regularizer=slim.l2_regularizer(weight_decay)):
batch_nor... | ['def', 'inception_resnet_v2_arg_scope(weight_decay=4e-05,', 'batch_norm_decay=0.9997,', 'batch_norm_epsilon=0.001,', 'activation_fn=tf.nn.relu):', 'with', 'slim.arg_scope([slim.conv2d,', 'slim.fully_connected],', 'weights_regularizer=slim.l2_regularizer(weight_decay),', 'biases_regularizer=slim.l2_regularizer(weight_d... | 557,928 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | sample_generation_tools.py | chirp_mass | chirp_mass | Takes two masses and calculates the corresponding chirpmass. | [
"Takes",
"two",
"masses",
"and",
"calculates",
"the",
"corresponding",
"chirpmass."
] | def chirp_mass(mass1, mass2):
return (mass1 * mass2) ** (3 / 5) / (mass1 + mass2) ** (1 / 5) | ['def', 'chirp_mass(mass1,', 'mass2):', 'return', '(mass1', '*', 'mass2)', '**', '(3', '/', '5)', '/', '(mass1', '+', 'mass2)', '**', '(1', '/', '5)'] | 18,507 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | webcam.py | get_view_dirs | get_view_dirs | Creates and returns one view directory per webcam. | [
"Creates",
"and",
"returns",
"one",
"view",
"directory",
"per",
"webcam."
] | def get_view_dirs(vidbase, tmp_imagedir):
if FLAGS.seqname:
seqname = FLAGS.seqname
else:
if not os.listdir(vidbase):
seqname = '0'
else:
seq_names = [i.split('_')[0] for i in os.listdir(vidbase)]
latest_seq = sorted(map(int, seq_names), reverse=True)[... | ['def', 'get_view_dirs(vidbase,', 'tmp_imagedir):', 'if', 'FLAGS.seqname:', 'seqname', '=', 'FLAGS.seqname', 'else:', 'if', 'not', 'os.listdir(vidbase):', 'seqname', '=', "'0'", 'else:', 'seq_names', '=', "[i.split('_')[0]", 'for', 'i', 'in', 'os.listdir(vidbase)]', 'latest_seq', '=', 'sorted(map(int,', 'seq_names),', ... | 29,627 |
ezliu/dream | embed.py | TrajectoryEmbedder.label_rewards | label_rewards | Computes rewards for each experience in the trajectory. | [
"Computes",
"rewards",
"for",
"each",
"experience",
"in",
"the",
"trajectory."
] | def label_rewards(self, trajectories):
(id_contexts, all_transition_contexts, _, mask) = self._compute_contexts(trajectories)
distances = ((all_transition_contexts - id_contexts.unsqueeze(1).expand_as(all_transition_contexts).detach()) ** 2).sum(-1)
rewards = distances[:, :-1] - distances[:, 1:] - self._pen... | ['def', 'label_rewards(self,', 'trajectories):', '(id_contexts,', 'all_transition_contexts,', '_,', 'mask)', '=', 'self._compute_contexts(trajectories)', 'distances', '=', '((all_transition_contexts', '-', 'id_contexts.unsqueeze(1).expand_as(all_transition_contexts).detach())', '**', '2).sum(-1)', 'rewards', '=', 'dist... | 552,578 |
boostcampaitech2/semantic-segmentation-level2-cv-07 | test_corner_head.py | test_corner_head_loss | test_corner_head_loss | Tests corner head loss when truth is empty and non-empty. | [
"Tests",
"corner",
"head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_corner_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]
self = CornerHead(num_classes=4, in_channels=1)
feat = [torch.rand(1, 1, s // 4, s // 4) for _ in range(self.num_feat_levels)]
(tl_heats, br_heats, tl_embs, br_embs, tl_offs, br_off... | ['def', 'test_corner_head_loss():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3)}]', 'self', '=', 'CornerHead(num_classes=4,', 'in_channels=1)', 'feat', '=', '[torch.rand(1,', '1,', 's', '//', '4,', 's', '//', '4)', 'for', '_', 'in', ... | 857,344 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_subplots.py | check_shared | check_shared | x_shared and y_shared are n x n boolean matrices; entry (i, j) indicates whether the x (or y) axes of subplots i and j should be shared. | [
"x_shared",
"and",
"y_shared",
"are",
"n",
"x",
"n",
"boolean",
"matrices;",
"entry",
"(i,",
"j)",
"indicates",
"whether",
"the",
"x",
"(or",
"y)",
"axes",
"of",
"subplots",
"i",
"and",
"j",
"should",
"be",
"shared."
] | def check_shared(axs, x_shared, y_shared):
for ((i1, ax1), (i2, ax2), (i3, (name, shared))) in itertools.product(enumerate(axs), enumerate(axs), enumerate(zip('xy', [x_shared, y_shared]))):
if i2 <= i1:
continue
assert getattr(axs[0], '_shared_{}_axes'.format(name)).joined(ax1, ax2) == s... | ['def', 'check_shared(axs,', 'x_shared,', 'y_shared):', 'for', '((i1,', 'ax1),', '(i2,', 'ax2),', '(i3,', '(name,', 'shared)))', 'in', 'itertools.product(enumerate(axs),', 'enumerate(axs),', "enumerate(zip('xy',", '[x_shared,', 'y_shared]))):', 'if', 'i2', '<=', 'i1:', 'continue', 'assert', 'getattr(axs[0],', "'_shared... | 97,400 |
microsoft/nni | base.py | ParametrizedModule.freeze_init_arguments | freeze_init_arguments | Freeze the init arguments with the given context, and return the frozen arguments. | [
"Freeze",
"the",
"init",
"arguments",
"with",
"the",
"given",
"context,",
"and",
"return",
"the",
"frozen",
"arguments."
] | def freeze_init_arguments(sample: Optional[Sample], *args, **kwargs) -> Tuple[tuple, dict]:
args_ = tuple((ensure_frozen(arg, sample=sample) for arg in args))
kwargs_ = {kw: ensure_frozen(arg, sample=sample) for (kw, arg) in kwargs.items()}
return (args_, kwargs_) | ['def', 'freeze_init_arguments(sample:', 'Optional[Sample],', '*args,', '**kwargs)', '->', 'Tuple[tuple,', 'dict]:', 'args_', '=', 'tuple((ensure_frozen(arg,', 'sample=sample)', 'for', 'arg', 'in', 'args))', 'kwargs_', '=', '{kw:', 'ensure_frozen(arg,', 'sample=sample)', 'for', '(kw,', 'arg)', 'in', 'kwargs.items()}', ... | 728,772 |
aws/sagemaker-python-sdk | steps.py | ConfigurableRetryStep.to_request | to_request | Gets the request structure for `ConfigurableRetryStep`. | [
"Gets",
"the",
"request",
"structure",
"for",
"`ConfigurableRetryStep`."
] | def to_request(self) -> RequestType:
step_dict = super().to_request()
if self.retry_policies:
step_dict['RetryPolicies'] = self._resolve_retry_policy(self.retry_policies)
return step_dict | ['def', 'to_request(self)', '->', 'RequestType:', 'step_dict', '=', 'super().to_request()', 'if', 'self.retry_policies:', "step_dict['RetryPolicies']", '=', 'self._resolve_retry_policy(self.retry_policies)', 'return', 'step_dict'] | 830,676 |
openvinotoolkit/training_extensions | test_tiling_detection.py | TestTilingDetection.setUp | setUp | Setup the test case. | [
"Setup",
"the",
"test",
"case."
] | def setUp(self) -> None:
self.height = 1024
self.width = 1024
self.label_names = ['rectangle', 'ellipse', 'triangle']
self.tile_cfg = dict(tile_size=np.random.randint(low=100, high=500), overlap_ratio=np.random.uniform(low=0.0, high=0.5), max_per_img=np.random.randint(low=1, high=10000), max_annotation=... | ['def', 'setUp(self)', '->', 'None:', 'self.height', '=', '1024', 'self.width', '=', '1024', 'self.label_names', '=', "['rectangle',", "'ellipse',", "'triangle']", 'self.tile_cfg', '=', 'dict(tile_size=np.random.randint(low=100,', 'high=500),', 'overlap_ratio=np.random.uniform(low=0.0,', 'high=0.5),', 'max_per_img=np.r... | 919,352 |
suarez12138/AI-Reversi_IMP_TextDichotomy | csc.py | csc_matrix.getrow | getrow | Returns a copy of row i of the matrix, as a (1 x n) CSR matrix (row vector). | [
"Returns",
"a",
"copy",
"of",
"row",
"i",
"of",
"the",
"matrix,",
"as",
"a",
"(1",
"x",
"n)",
"CSR",
"matrix",
"(row",
"vector)."
] | def getrow(self, i):
(M, N) = self.shape
i = int(i)
if i < 0:
i += M
if i < 0 or i >= M:
raise IndexError('index (%d) out of range' % i)
return self._get_submatrix(minor=i).tocsr() | ['def', 'getrow(self,', 'i):', '(M,', 'N)', '=', 'self.shape', 'i', '=', 'int(i)', 'if', 'i', '<', '0:', 'i', '+=', 'M', 'if', 'i', '<', '0', 'or', 'i', '>=', 'M:', 'raise', "IndexError('index", '(%d)', 'out', 'of', "range'", '%', 'i)', 'return', 'self._get_submatrix(minor=i).tocsr()'] | 100,130 |
gunthercox/ChatterBot | __init__.py | FCompiler.get_flags_ar | get_flags_ar | List of archiver flags. | [
"List",
"of",
"archiver",
"flags."
] | def get_flags_ar(self):
return self._get_command_flags('archiver') | ['def', 'get_flags_ar(self):', 'return', "self._get_command_flags('archiver')"] | 531,225 |
deepmind/dm_control | rewards.py | compute_squared_differences | compute_squared_differences | Computes squared differences of features. | [
"Computes",
"squared",
"differences",
"of",
"features."
] | def compute_squared_differences(walker_features, reference_features, exclude_keys=()):
squared_differences = {}
for k in walker_features:
if k not in exclude_keys:
if 'quaternion' not in k:
squared_differences[k] = np.sum((walker_features[k] - reference_features[k]) ** 2)
... | ['def', 'compute_squared_differences(walker_features,', 'reference_features,', 'exclude_keys=()):', 'squared_differences', '=', '{}', 'for', 'k', 'in', 'walker_features:', 'if', 'k', 'not', 'in', 'exclude_keys:', 'if', "'quaternion'", 'not', 'in', 'k:', 'squared_differences[k]', '=', 'np.sum((walker_features[k]', '-', ... | 165,961 |
jbeomlee93/BBAM | voc_eval.py | eval_detection_voc | eval_detection_voc | Evaluate on voc dataset. | [
"Evaluate",
"on",
"voc",
"dataset."
] | def eval_detection_voc(pred_boxlists, gt_boxlists, iou_thresh=0.5, use_07_metric=False):
assert len(gt_boxlists) == len(pred_boxlists), 'Length of gt and pred lists need to be same.'
(prec, rec) = calc_detection_voc_prec_rec(pred_boxlists=pred_boxlists, gt_boxlists=gt_boxlists, iou_thresh=iou_thresh)
ap = c... | ['def', 'eval_detection_voc(pred_boxlists,', 'gt_boxlists,', 'iou_thresh=0.5,', 'use_07_metric=False):', 'assert', 'len(gt_boxlists)', '==', 'len(pred_boxlists),', "'Length", 'of', 'gt', 'and', 'pred', 'lists', 'need', 'to', 'be', "same.'", '(prec,', 'rec)', '=', 'calc_detection_voc_prec_rec(pred_boxlists=pred_boxlists... | 423,085 |
accel-brain/accel-brain-code | portfolio_optimization.py | PortfolioOptimization.set_portfolio_n | set_portfolio_n | setter for the number of portfolio. | [
"setter",
"for",
"the",
"number",
"of",
"portfolio."
] | def set_portfolio_n(self, value):
self.__portfolio_n = value | ['def', 'set_portfolio_n(self,', 'value):', 'self.__portfolio_n', '=', 'value'] | 7,072 |
google-research/scenic | main.py | get_trainer | get_trainer | Returns trainer given its name. | [
"Returns",
"trainer",
"given",
"its",
"name."
] | def get_trainer(trainer_name: str) -> Callable[..., Any]:
if trainer_name == 'vivit_trainer':
return vivit_trainer.train
raise ValueError(f'Unsupported trainer: {trainer_name}.') | ['def', 'get_trainer(trainer_name:', 'str)', '->', 'Callable[...,', 'Any]:', 'if', 'trainer_name', '==', "'vivit_trainer':", 'return', 'vivit_trainer.train', 'raise', "ValueError(f'Unsupported", 'trainer:', "{trainer_name}.')"] | 847,549 |
airaria/TextBrewer | tokenization_transfo_xl.py | TransfoXLTokenizer.save_vocabulary | save_vocabulary | Save the tokenizer vocabulary to a directory or file. | [
"Save",
"the",
"tokenizer",
"vocabulary",
"to",
"a",
"directory",
"or",
"file."
] | def save_vocabulary(self, vocab_path):
index = 0
if os.path.isdir(vocab_path):
vocab_file = os.path.join(vocab_path, VOCAB_NAME)
torch.save(self.__dict__, vocab_file)
return vocab_file | ['def', 'save_vocabulary(self,', 'vocab_path):', 'index', '=', '0', 'if', 'os.path.isdir(vocab_path):', 'vocab_file', '=', 'os.path.join(vocab_path,', 'VOCAB_NAME)', 'torch.save(self.__dict__,', 'vocab_file)', 'return', 'vocab_file'] | 925,832 |
dvlab-research/UVTR | uvtr_kd_m.py | UVTRKDM.aug_test_pts | aug_test_pts | Test function of point cloud branch with augmentaiton. | [
"Test",
"function",
"of",
"point",
"cloud",
"branch",
"with",
"augmentaiton."
] | def aug_test_pts(self, pts_feats, img_feats, img_depths, img_metas, rescale=False):
aug_bboxes = []
for (_idx, img_meta) in enumerate(img_metas):
outs = self.pts_bbox_head(pts_feats[_idx], img_feats[_idx], img_meta, img_depths[_idx])
bbox_list = self.pts_bbox_head.get_bboxes(outs, img_meta, resc... | ['def', 'aug_test_pts(self,', 'pts_feats,', 'img_feats,', 'img_depths,', 'img_metas,', 'rescale=False):', 'aug_bboxes', '=', '[]', 'for', '(_idx,', 'img_meta)', 'in', 'enumerate(img_metas):', 'outs', '=', 'self.pts_bbox_head(pts_feats[_idx],', 'img_feats[_idx],', 'img_meta,', 'img_depths[_idx])', 'bbox_list', '=', 'sel... | 930,557 |
noambassat/SpeechTrainer | dist.py | DistributionMetadata.read_pkg_file | read_pkg_file | Reads the metadata values from a file object. | [
"Reads",
"the",
"metadata",
"values",
"from",
"a",
"file",
"object."
] | def read_pkg_file(self, file):
msg = message_from_file(file)
def _read_field(name):
value = msg[name]
if value == 'UNKNOWN':
return None
return value
def _read_list(name):
values = msg.get_all(name, None)
if values == []:
return None
... | ['def', 'read_pkg_file(self,', 'file):', 'msg', '=', 'message_from_file(file)', 'def', '_read_field(name):', 'value', '=', 'msg[name]', 'if', 'value', '==', "'UNKNOWN':", 'return', 'None', 'return', 'value', 'def', '_read_list(name):', 'values', '=', 'msg.get_all(name,', 'None)', 'if', 'values', '==', '[]:', 'return', ... | 896,237 |
weimin17/Object-Detection_HelmetDetection | networks.py | discriminator | discriminator | A thin wrapper around the Pix2Pix discriminator to conform to TFGAN API. | [
"A",
"thin",
"wrapper",
"around",
"the",
"Pix2Pix",
"discriminator",
"to",
"conform",
"to",
"TFGAN",
"API."
] | def discriminator(image_batch, unused_conditioning=None):
with tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()):
(logits_4d, _) = pix2pix.pix2pix_discriminator(image_batch, num_filters=[64, 128, 256, 512])
logits_4d.shape.assert_has_rank(4)
logits_2d = tf.contrib.layers.flatten(logits... | ['def', 'discriminator(image_batch,', 'unused_conditioning=None):', 'with', 'tf.contrib.framework.arg_scope(pix2pix.pix2pix_arg_scope()):', '(logits_4d,', '_)', '=', 'pix2pix.pix2pix_discriminator(image_batch,', 'num_filters=[64,', '128,', '256,', '512])', 'logits_4d.shape.assert_has_rank(4)', 'logits_2d', '=', 'tf.con... | 750,107 |
microsoft/InnerEye-DeepLearning | test_lr_scheduler.py | test_warmup_against_original_schedule | test_warmup_against_original_schedule | Tests if LR scheduler with warmup matches the Pytorch implementation after the warmup stage is completed. | [
"Tests",
"if",
"LR",
"scheduler",
"with",
"warmup",
"matches",
"the",
"Pytorch",
"implementation",
"after",
"the",
"warmup",
"stage",
"is",
"completed."
] | def test_warmup_against_original_schedule(lr_scheduler_type: LRSchedulerType, warmup_epochs: int) -> None:
config = DummyModel(num_epochs=6, l_rate=0.01, l_rate_scheduler=lr_scheduler_type, l_rate_exponential_gamma=0.9, l_rate_step_gamma=0.9, l_rate_step_step_size=2, l_rate_multi_step_gamma=0.9, l_rate_multi_step_m... | ['def', 'test_warmup_against_original_schedule(lr_scheduler_type:', 'LRSchedulerType,', 'warmup_epochs:', 'int)', '->', 'None:', 'config', '=', 'DummyModel(num_epochs=6,', 'l_rate=0.01,', 'l_rate_scheduler=lr_scheduler_type,', 'l_rate_exponential_gamma=0.9,', 'l_rate_step_gamma=0.9,', 'l_rate_step_step_size=2,', 'l_rat... | 613,810 |
awslabs/predictive-maintenance-using-- | ops.py | BinOp.convert_values | convert_values | Convert datetimes to a comparable value in an expression. | [
"Convert",
"datetimes",
"to",
"a",
"comparable",
"value",
"in",
"an",
"expression."
] | def convert_values(self):
def stringify(value):
if self.encoding is not None:
encoder = partial(pprint_thing_encoded, encoding=self.encoding)
else:
encoder = pprint_thing
return encoder(value)
(lhs, rhs) = (self.lhs, self.rhs)
if is_term(lhs) and lhs.is_datet... | ['def', 'convert_values(self):', 'def', 'stringify(value):', 'if', 'self.encoding', 'is', 'not', 'None:', 'encoder', '=', 'partial(pprint_thing_encoded,', 'encoding=self.encoding)', 'else:', 'encoder', '=', 'pprint_thing', 'return', 'encoder(value)', '(lhs,', 'rhs)', '=', '(self.lhs,', 'self.rhs)', 'if', 'is_term(lhs)'... | 823,379 |
jingjingli01/TGLS | optimization.py | get_cosine_schedule_with_warmup | get_cosine_schedule_with_warmup | Create a schedule with a learning rate that decreases following the values of the cosine function between 0 and `pi * cycles` after a warmup period during which it increases linearly between 0 and 1. | [
"Create",
"a",
"schedule",
"with",
"a",
"learning",
"rate",
"that",
"decreases",
"following",
"the",
"values",
"of",
"the",
"cosine",
"function",
"between",
"0",
"and",
"`pi",
"*",
"cycles`",
"after",
"a",
"warmup",
"period",
"during",
"which",
"it",
"increa... | def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=0.5, last_epoch=-1):
def lr_lambda(current_step):
if current_step < num_warmup_steps:
return float(current_step) / float(max(1, num_warmup_steps))
progress = float(current_step - num_warmup_s... | ['def', 'get_cosine_schedule_with_warmup(optimizer,', 'num_warmup_steps,', 'num_training_steps,', 'num_cycles=0.5,', 'last_epoch=-1):', 'def', 'lr_lambda(current_step):', 'if', 'current_step', '<', 'num_warmup_steps:', 'return', 'float(current_step)', '/', 'float(max(1,', 'num_warmup_steps))', 'progress', '=', 'float(c... | 354,196 |
ishwnews/MASS | transformer.py | PredLayer.forward | forward | Compute the loss, and optionally the scores. | [
"Compute",
"the",
"loss,",
"and",
"optionally",
"the",
"scores."
] | def forward(self, x, y, get_scores=False):
assert (y == self.pad_index).sum().item() == 0
if self.asm is False:
scores = self.proj(x).view(-1, self.n_words)
loss = F.cross_entropy(scores, y, reduction='elementwise_mean')
else:
(_, loss) = self.proj(x, y)
scores = self.proj.lo... | ['def', 'forward(self,', 'x,', 'y,', 'get_scores=False):', 'assert', '(y', '==', 'self.pad_index).sum().item()', '==', '0', 'if', 'self.asm', 'is', 'False:', 'scores', '=', 'self.proj(x).view(-1,', 'self.n_words)', 'loss', '=', 'F.cross_entropy(scores,', 'y,', "reduction='elementwise_mean')", 'else:', '(_,', 'loss)', '... | 646,110 |
Koushikl0l/Artificial-Intelligence | search.py | OnlineSearchProblem.h | h | Returns least possible cost to reach a goal for the given state. | [
"Returns",
"least",
"possible",
"cost",
"to",
"reach",
"a",
"goal",
"for",
"the",
"given",
"state."
] | def h(self, state):
return self.graph.least_costs[state] | ['def', 'h(self,', 'state):', 'return', 'self.graph.least_costs[state]'] | 117,207 |
intel/neural-compressor | quantizer.py | Quantizer.convert_qdq_to_operator_oriented | convert_qdq_to_operator_oriented | Convert QDQ to QOperator format. | [
"Convert",
"QDQ",
"to",
"QOperator",
"format."
] | def convert_qdq_to_operator_oriented(self):
self.new_nodes = []
self.remove_nodes = []
self.replace_input = []
for node in self.model.nodes():
if node.op_type not in ['QuantizeLinear', 'DequantizeLinear'] and self.should_convert(node):
op_converter = OPERATORS[node.op_type](self, nod... | ['def', 'convert_qdq_to_operator_oriented(self):', 'self.new_nodes', '=', '[]', 'self.remove_nodes', '=', '[]', 'self.replace_input', '=', '[]', 'for', 'node', 'in', 'self.model.nodes():', 'if', 'node.op_type', 'not', 'in', "['QuantizeLinear',", "'DequantizeLinear']", 'and', 'self.should_convert(node):', 'op_converter'... | 737,462 |
Kvatsx/Artificial-Intelligence-Assignments | prefilter.py | AutocallChecker.check | check | Check if the initial word/function is callable and autocall is on. | [
"Check",
"if",
"the",
"initial",
"word/function",
"is",
"callable",
"and",
"autocall",
"is",
"on."
] | def check(self, line_info):
if not self.shell.autocall:
return None
oinfo = line_info.ofind(self.shell)
if not oinfo['found']:
return None
ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf']
ifun = line_info.ifun
line = line_info.line
if ifun.lower() in ignored_funs a... | ['def', 'check(self,', 'line_info):', 'if', 'not', 'self.shell.autocall:', 'return', 'None', 'oinfo', '=', 'line_info.ofind(self.shell)', 'if', 'not', "oinfo['found']:", 'return', 'None', 'ignored_funs', '=', "['b',", "'f',", "'r',", "'u',", "'br',", "'rb',", "'fr',", "'rf']", 'ifun', '=', 'line_info.ifun', 'line', '='... | 38,217 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | nb_007a.py | LanguageModelLoader.batchify | batchify | Splits the corpus in batches. | [
"Splits",
"the",
"corpus",
"in",
"batches."
] | def batchify(self, data: np.ndarray) -> LongTensor:
nb = data.shape[0] // self.bs
data = np.array(data[:nb * self.bs]).reshape(self.bs, -1).T
if self.backwards:
data = data[::-1]
return LongTensor(data) | ['def', 'batchify(self,', 'data:', 'np.ndarray)', '->', 'LongTensor:', 'nb', '=', 'data.shape[0]', '//', 'self.bs', 'data', '=', 'np.array(data[:nb', '*', 'self.bs]).reshape(self.bs,', '-1).T', 'if', 'self.backwards:', 'data', '=', 'data[::-1]', 'return', 'LongTensor(data)'] | 32,449 |
nhelvig/reinforcement | game.py | Game.draw_changes | draw_changes | Draw changes in scenario. | [
"Draw",
"changes",
"in",
"scenario."
] | def draw_changes(self):
around = self.draw_around()
background = self.draw_map()
interactive = self.draw_interactive()
return (around, background, interactive) | ['def', 'draw_changes(self):', 'around', '=', 'self.draw_around()', 'background', '=', 'self.draw_map()', 'interactive', '=', 'self.draw_interactive()', 'return', '(around,', 'background,', 'interactive)'] | 286,768 |
matsu0228/nlp-jp | format.py | LatexFormatter.write_result | write_result | Render a DataFrame to a LaTeX tabular/longtable environment output. | [
"Render",
"a",
"DataFrame",
"to",
"a",
"LaTeX",
"tabular/longtable",
"environment",
"output."
] | def write_result(self, buf):
if len(self.frame.columns) == 0 or len(self.frame.index) == 0:
info_line = u('Empty {name}\nColumns: {col}\nIndex: {idx}').format(name=type(self.frame).__name__, col=self.frame.columns, idx=self.frame.index)
strcols = [[info_line]]
else:
strcols = self.fmt._t... | ['def', 'write_result(self,', 'buf):', 'if', 'len(self.frame.columns)', '==', '0', 'or', 'len(self.frame.index)', '==', '0:', 'info_line', '=', "u('Empty", '{name}\\nColumns:', '{col}\\nIndex:', "{idx}').format(name=type(self.frame).__name__,", 'col=self.frame.columns,', 'idx=self.frame.index)', 'strcols', '=', '[[info... | 802,888 |
gunthercox/ChatterBot | wrappers.py | BaseRequest.host | host | Just the host including the port if available. | [
"Just",
"the",
"host",
"including",
"the",
"port",
"if",
"available."
] | def host(self):
return get_host(self.environ, trusted_hosts=self.trusted_hosts) | ['def', 'host(self):', 'return', 'get_host(self.environ,', 'trusted_hosts=self.trusted_hosts)'] | 483,573 |
apeterswu/RL4NMT | cnn_dailymail.py | example_splits | example_splits | Generate splits of the data. | [
"Generate",
"splits",
"of",
"the",
"data."
] | def example_splits(url_file, all_files):
def generate_hash(inp):
h = hashlib.sha1()
h.update(inp)
return h.hexdigest()
all_files_map = {f.split('/')[-1]: f for f in all_files}
urls = []
for line in tf.gfile.Open(url_file):
urls.append(line.strip().encode('utf-8'))
fi... | ['def', 'example_splits(url_file,', 'all_files):', 'def', 'generate_hash(inp):', 'h', '=', 'hashlib.sha1()', 'h.update(inp)', 'return', 'h.hexdigest()', 'all_files_map', '=', "{f.split('/')[-1]:", 'f', 'for', 'f', 'in', 'all_files}', 'urls', '=', '[]', 'for', 'line', 'in', 'tf.gfile.Open(url_file):', "urls.append(line.... | 330,878 |
ashwanitanwar/nmt-transfer-learning-xlm-r | fp16_optimizer.py | MemoryEfficientFP16Optimizer.step | step | Performs a single optimization step. | [
"Performs",
"a",
"single",
"optimization",
"step."
] | def step(self, closure=None):
self._unscale_grads()
self.wrapped_optimizer.step(closure) | ['def', 'step(self,', 'closure=None):', 'self._unscale_grads()', 'self.wrapped_optimizer.step(closure)'] | 733,074 |
astooke/rlpyt | serial_sampler.py | AsyncSerialSampler.evaluate_agent | evaluate_agent | First calls the agent to retrieve new parameter values from the training process's agent. | [
"First",
"calls",
"the",
"agent",
"to",
"retrieve",
"new",
"parameter",
"values",
"from",
"the",
"training",
"process's",
"agent."
] | def evaluate_agent(self, itr):
self.agent.recv_shared_memory()
return self.eval_collector.collect_evaluation(itr) | ['def', 'evaluate_agent(self,', 'itr):', 'self.agent.recv_shared_memory()', 'return', 'self.eval_collector.collect_evaluation(itr)'] | 334,665 |
huawei-noah/xingtian | callback_list.py | CallbackList.before_valid_step | before_valid_step | Call before_valid_step of the managed callbacks. | [
"Call",
"before_valid_step",
"of",
"the",
"managed",
"callbacks."
] | def before_valid_step(self, batch_index, logs=None):
logs = logs or {}
for callback in self.callbacks:
callback.before_valid_step(batch_index, logs) | ['def', 'before_valid_step(self,', 'batch_index,', 'logs=None):', 'logs', '=', 'logs', 'or', '{}', 'for', 'callback', 'in', 'self.callbacks:', 'callback.before_valid_step(batch_index,', 'logs)'] | 968,442 |
shanglianlm0525/CvPytorch | test_cityscapes.py | deeplabv3plus_resnet50 | deeplabv3plus_resnet50 | Constructs a DeepLabV3 model with a ResNet-50 backbone. | [
"Constructs",
"a",
"DeepLabV3",
"model",
"with",
"a",
"ResNet-50",
"backbone."
] | def deeplabv3plus_resnet50(num_classes=21, output_stride=8, pretrained_backbone=True):
return _load_model('deeplabv3plus', 'resnet50', num_classes, output_stride=output_stride, pretrained_backbone=pretrained_backbone) | ['def', 'deeplabv3plus_resnet50(num_classes=21,', 'output_stride=8,', 'pretrained_backbone=True):', 'return', "_load_model('deeplabv3plus',", "'resnet50',", 'num_classes,', 'output_stride=output_stride,', 'pretrained_backbone=pretrained_backbone)'] | 523,649 |
rifqind/Agent-Programs-3KS1 | utils.py | PriorityQueue.append | append | Insert item at its correct position. | [
"Insert",
"item",
"at",
"its",
"correct",
"position."
] | def append(self, item):
heapq.heappush(self.heap, (self.f(item), item)) | ['def', 'append(self,', 'item):', 'heapq.heappush(self.heap,', '(self.f(item),', 'item))'] | 40,446 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | videos_to_tfrecords.py | ShardSequences | ShardSequences | Find all sequences, shard and randomize them. | [
"Find",
"all",
"sequences,",
"shard",
"and",
"randomize",
"them."
] | def ShardSequences(sequences, max_per_shard):
total_shards_len = 0
total_shards = 0
assert max_per_shard > 0
for sequence in sequences:
if sequence['shard']:
sequence['shard'] = False
length = sequence['len']
start = sequence['start']
end = sequenc... | ['def', 'ShardSequences(sequences,', 'max_per_shard):', 'total_shards_len', '=', '0', 'total_shards', '=', '0', 'assert', 'max_per_shard', '>', '0', 'for', 'sequence', 'in', 'sequences:', 'if', "sequence['shard']:", "sequence['shard']", '=', 'False', 'length', '=', "sequence['len']", 'start', '=', "sequence['start']", ... | 29,541 |
atilla00/TurPy | _preprocess_functions.py | replace_tags | replace_tags | Replace tags in atext series. | [
"Replace",
"tags",
"in",
"atext",
"series."
] | def replace_tags(s: pd.Series, to_replace: str, *args) -> pd.Series:
pattern = '@[a-zA-Z0-9_]+'
return s.str.replace(pattern, to_replace, regex=True) | ['def', 'replace_tags(s:', 'pd.Series,', 'to_replace:', 'str,', '*args)', '->', 'pd.Series:', 'pattern', '=', "'@[a-zA-Z0-9_]+'", 'return', 's.str.replace(pattern,', 'to_replace,', 'regex=True)'] | 952,850 |
TangJiahui/6.034_Artificial_Intelligence | bayes_api.py | filter_dict | filter_dict | Return a subset of the dictionary d, consisting only of the keys that satisfy pred(key). | [
"Return",
"a",
"subset",
"of",
"the",
"dictionary",
"d,",
"consisting",
"only",
"of",
"the",
"keys",
"that",
"satisfy",
"pred(key)."
] | def filter_dict(pred, d):
ret = {}
for k in d:
if pred(k):
ret[k] = d[k]
return ret | ['def', 'filter_dict(pred,', 'd):', 'ret', '=', '{}', 'for', 'k', 'in', 'd:', 'if', 'pred(k):', 'ret[k]', '=', 'd[k]', 'return', 'ret'] | 5,029 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | visitor.py | Base.insertComments | insertComments | Add comments to the template from tokens in the tree. | [
"Add",
"comments",
"to",
"the",
"template",
"from",
"tokens",
"in",
"the",
"tree."
] | def insertComments(self, tmpl, tree, index, memo):
prefix = self.config.last('commentPrefix', '# ')
(cache, parser, comTypes) = (memo.comments, tree.parser, tokens.commentTypes)
comNew = lambda t: t.type in comTypes and t.index not in cache
for tok in ifilter(comNew, parser.input.tokens[memo.last:index]... | ['def', 'insertComments(self,', 'tmpl,', 'tree,', 'index,', 'memo):', 'prefix', '=', "self.config.last('commentPrefix',", "'#", "')", '(cache,', 'parser,', 'comTypes)', '=', '(memo.comments,', 'tree.parser,', 'tokens.commentTypes)', 'comNew', '=', 'lambda', 't:', 't.type', 'in', 'comTypes', 'and', 't.index', 'not', 'in... | 11,122 |
zichunhao/lgn-autoencoder | lgn_encoder.py | get_msq | get_msq | Get mass squared of a 4-momentum. | [
"Get",
"mass",
"squared",
"of",
"a",
"4-momentum."
] | def get_msq(p4: torch.Tensor, keep_dim=False):
(E, p3) = (p4[..., 0], p4[..., 1:])
msq = E ** 2 - torch.norm(p3, dim=-1) ** 2
if keep_dim:
return msq.unsqueeze(-1)
return msq | ['def', 'get_msq(p4:', 'torch.Tensor,', 'keep_dim=False):', '(E,', 'p3)', '=', '(p4[...,', '0],', 'p4[...,', '1:])', 'msq', '=', 'E', '**', '2', '-', 'torch.norm(p3,', 'dim=-1)', '**', '2', 'if', 'keep_dim:', 'return', 'msq.unsqueeze(-1)', 'return', 'msq'] | 600,256 |
SamsungLabs/fcaf3d | shape_aware_head.py | ShapeAwareHead.forward_single | forward_single | Forward function on a single-scale feature map. | [
"Forward",
"function",
"on",
"a",
"single-scale",
"feature",
"map."
] | def forward_single(self, x):
results = []
for head in self.heads:
results.append(head(x))
cls_score = torch.cat([result['cls_score'] for result in results], dim=1)
bbox_pred = torch.cat([result['bbox_pred'] for result in results], dim=1)
dir_cls_preds = None
if self.use_direction_classif... | ['def', 'forward_single(self,', 'x):', 'results', '=', '[]', 'for', 'head', 'in', 'self.heads:', 'results.append(head(x))', 'cls_score', '=', "torch.cat([result['cls_score']", 'for', 'result', 'in', 'results],', 'dim=1)', 'bbox_pred', '=', "torch.cat([result['bbox_pred']", 'for', 'result', 'in', 'results],', 'dim=1)', ... | 560,446 |
dgseten/bad-cv-tfm | oid_hierarchical_labels_expansion.py | OIDHierarchicalLabelsExpansion.expand_labels_from_csv | expand_labels_from_csv | Expands a row containing bounding boxes from CSV file. | [
"Expands",
"a",
"row",
"containing",
"bounding",
"boxes",
"from",
"CSV",
"file."
] | def expand_labels_from_csv(self, csv_row):
cvs_row_splited = csv_row.split(',')
assert len(cvs_row_splited) == 4
result = [csv_row]
if int(cvs_row_splited[3]) == 1:
assert cvs_row_splited[2] in self._hierarchy_keyed_child
parent_nodes = self._hierarchy_keyed_child[cvs_row_splited[2]]
... | ['def', 'expand_labels_from_csv(self,', 'csv_row):', 'cvs_row_splited', '=', "csv_row.split(',')", 'assert', 'len(cvs_row_splited)', '==', '4', 'result', '=', '[csv_row]', 'if', 'int(cvs_row_splited[3])', '==', '1:', 'assert', 'cvs_row_splited[2]', 'in', 'self._hierarchy_keyed_child', 'parent_nodes', '=', 'self._hierar... | 421,592 |
openvinotoolkit/datumaro | annotation.py | Mask.paint | paint | Applies a colormap to the mask and produces the resulting image. | [
"Applies",
"a",
"colormap",
"to",
"the",
"mask",
"and",
"produces",
"the",
"resulting",
"image."
] | def paint(self, colormap: Colormap) -> np.ndarray:
from datumaro.util.mask_tools import paint_mask
return paint_mask(self.as_class_mask(), colormap) | ['def', 'paint(self,', 'colormap:', 'Colormap)', '->', 'np.ndarray:', 'from', 'datumaro.util.mask_tools', 'import', 'paint_mask', 'return', 'paint_mask(self.as_class_mask(),', 'colormap)'] | 498,048 |
techexpert1611/Natural-Language-Processing | base.py | LoadFile.ngram_selection | ngram_selection | Select all the n-grams and populate the candidate container. | [
"Select",
"all",
"the",
"n-grams",
"and",
"populate",
"the",
"candidate",
"container."
] | def ngram_selection(self, n=3):
for (i, sentence) in enumerate(self.sentences):
skip = min(n, sentence.length)
shift = sum([s.length for s in self.sentences[0:i]])
for j in range(sentence.length):
for k in range(j + 1, min(j + 1 + skip, sentence.length + 1)):
self... | ['def', 'ngram_selection(self,', 'n=3):', 'for', '(i,', 'sentence)', 'in', 'enumerate(self.sentences):', 'skip', '=', 'min(n,', 'sentence.length)', 'shift', '=', 'sum([s.length', 'for', 's', 'in', 'self.sentences[0:i]])', 'for', 'j', 'in', 'range(sentence.length):', 'for', 'k', 'in', 'range(j', '+', '1,', 'min(j', '+',... | 637,529 |
Realdr4g0n/RDGAN | functional.py | adjust_contrast | adjust_contrast | Adjust contrast of an Image. | [
"Adjust",
"contrast",
"of",
"an",
"Image."
] | def adjust_contrast(img, contrast_factor):
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
enhancer = ImageEnhance.Contrast(img)
img = enhancer.enhance(contrast_factor)
return img | ['def', 'adjust_contrast(img,', 'contrast_factor):', 'if', 'not', '_is_pil_image(img):', 'raise', "TypeError('img", 'should', 'be', 'PIL', 'Image.', 'Got', "{}'.format(type(img)))", 'enhancer', '=', 'ImageEnhance.Contrast(img)', 'img', '=', 'enhancer.enhance(contrast_factor)', 'return', 'img'] | 848,588 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | variables.py | get_variables_by_name | get_variables_by_name | Gets the list of variables that were given that name. | [
"Gets",
"the",
"list",
"of",
"variables",
"that",
"were",
"given",
"that",
"name."
] | def get_variables_by_name(given_name, scope=None):
return get_variables(scope=scope, suffix=given_name) | ['def', 'get_variables_by_name(given_name,', 'scope=None):', 'return', 'get_variables(scope=scope,', 'suffix=given_name)'] | 55,392 |
neardws/Game-Theoretic-Deep-Reinforcement-Learning | dataStruct.py | location.get_distance | get_distance | get the distance between two locations. | [
"get",
"the",
"distance",
"between",
"two",
"locations."
] | def get_distance(self, location: 'location') -> float:
return np.math.sqrt((self._x - location.get_x()) ** 2 + (self._y - location.get_y()) ** 2) | ['def', 'get_distance(self,', 'location:', "'location')", '->', 'float:', 'return', 'np.math.sqrt((self._x', '-', 'location.get_x())', '**', '2', '+', '(self._y', '-', 'location.get_y())', '**', '2)'] | 199,952 |
coder-mano/Shi-Tomasi-Corner-Detector | hashes.py | Hashes.is_hash_allowed | is_hash_allowed | Return whether the given hex digest is allowed. | [
"Return",
"whether",
"the",
"given",
"hex",
"digest",
"is",
"allowed."
] | def is_hash_allowed(self, hash_name, hex_digest):
return hex_digest in self._allowed.get(hash_name, []) | ['def', 'is_hash_allowed(self,', 'hash_name,', 'hex_digest):', 'return', 'hex_digest', 'in', 'self._allowed.get(hash_name,', '[])'] | 899,913 |
JunweiLiang/Object_Detection_Tracking | utils.py | get_ckpt_var_map_ema | get_ckpt_var_map_ema | Get a ema var map for restoring from pretrained checkpoints. | [
"Get",
"a",
"ema",
"var",
"map",
"for",
"restoring",
"from",
"pretrained",
"checkpoints."
] | def get_ckpt_var_map_ema(ckpt_path, ckpt_scope, var_scope, var_exclude_expr):
logging.info('Init model from checkpoint {}'.format(ckpt_path))
if not ckpt_scope.endswith('/') or not var_scope.endswith('/'):
raise ValueError('Please specific scope name ending with /')
if ckpt_scope.startswith('/'):
... | ['def', 'get_ckpt_var_map_ema(ckpt_path,', 'ckpt_scope,', 'var_scope,', 'var_exclude_expr):', "logging.info('Init", 'model', 'from', 'checkpoint', "{}'.format(ckpt_path))", 'if', 'not', "ckpt_scope.endswith('/')", 'or', 'not', "var_scope.endswith('/'):", 'raise', "ValueError('Please", 'specific', 'scope', 'name', 'endi... | 796,222 |
RangiLyu/nanodet | yacs.py | CfgNode.merge_from_other_cfg | merge_from_other_cfg | Merge `cfg_other` into this CfgNode. | [
"Merge",
"`cfg_other`",
"into",
"this",
"CfgNode."
] | def merge_from_other_cfg(self, cfg_other):
_merge_a_into_b(cfg_other, self, self, []) | ['def', 'merge_from_other_cfg(self,', 'cfg_other):', '_merge_a_into_b(cfg_other,', 'self,', 'self,', '[])'] | 651,880 |
RLE-Foundation/rllte | discrete.py | PixelEnv.step | step | Take a step in the environment. | [
"Take",
"a",
"step",
"in",
"the",
"environment."
] | def step(self, action: Any) -> Tuple[Any, SupportsFloat, bool, bool, Dict[str, Any]]:
obs = self.observation_space.sample()
reward = 0.5
if np.random.rand() > 0.5:
terminated = True
else:
terminated = False
truncated = terminated
info = {}
return (obs, reward, terminated, tru... | ['def', 'step(self,', 'action:', 'Any)', '->', 'Tuple[Any,', 'SupportsFloat,', 'bool,', 'bool,', 'Dict[str,', 'Any]]:', 'obs', '=', 'self.observation_space.sample()', 'reward', '=', '0.5', 'if', 'np.random.rand()', '>', '0.5:', 'terminated', '=', 'True', 'else:', 'terminated', '=', 'False', 'truncated', '=', 'terminate... | 333,542 |
ashwanitanwar/nmt-transfer-learning-xlm-r | fairseq_model.py | FairseqLanguageModel.max_decoder_positions | max_decoder_positions | Maximum length supported by the decoder. | [
"Maximum",
"length",
"supported",
"by",
"the",
"decoder."
] | def max_decoder_positions(self):
return self.decoder.max_positions() | ['def', 'max_decoder_positions(self):', 'return', 'self.decoder.max_positions()'] | 734,044 |
PacktPublishing/Hands-On-Artificial--for-Banking | tag.py | TaggedJSONSerializer.tag | tag | Convert a value to a tagged representation if necessary. | [
"Convert",
"a",
"value",
"to",
"a",
"tagged",
"representation",
"if",
"necessary."
] | def tag(self, value):
for tag in self.order:
if tag.check(value):
return tag.tag(value)
return value | ['def', 'tag(self,', 'value):', 'for', 'tag', 'in', 'self.order:', 'if', 'tag.check(value):', 'return', 'tag.tag(value)', 'return', 'value'] | 234,972 |
zihuitang/medical_AI_platform | types.py | new_class | new_class | Create a class object dynamically using the appropriate metaclass. | [
"Create",
"a",
"class",
"object",
"dynamically",
"using",
"the",
"appropriate",
"metaclass."
] | def new_class(name, bases=(), kwds=None, exec_body=None):
(meta, ns, kwds) = prepare_class(name, bases, kwds)
if exec_body is not None:
exec_body(ns)
return meta(name, bases, ns, **kwds) | ['def', 'new_class(name,', 'bases=(),', 'kwds=None,', 'exec_body=None):', '(meta,', 'ns,', 'kwds)', '=', 'prepare_class(name,', 'bases,', 'kwds)', 'if', 'exec_body', 'is', 'not', 'None:', 'exec_body(ns)', 'return', 'meta(name,', 'bases,', 'ns,', '**kwds)'] | 281,778 |
rudranil723/mini-main | interface.py | Element.getName | getName | Returns the name of the object. | [
"Returns",
"the",
"name",
"of",
"the",
"object."
] | def getName(self):
return self.__name__ | ['def', 'getName(self):', 'return', 'self.__name__'] | 271,315 |
leonnnop/GMMSeg | transforms.py | RandomCrop.get_crop_bbox | get_crop_bbox | Randomly get a crop bounding box. | [
"Randomly",
"get",
"a",
"crop",
"bounding",
"box."
] | def get_crop_bbox(self, img):
margin_h = max(img.shape[0] - self.crop_size[0], 0)
margin_w = max(img.shape[1] - self.crop_size[1], 0)
offset_h = np.random.randint(0, margin_h + 1)
offset_w = np.random.randint(0, margin_w + 1)
(crop_y1, crop_y2) = (offset_h, offset_h + self.crop_size[0])
(crop_x1... | ['def', 'get_crop_bbox(self,', 'img):', 'margin_h', '=', 'max(img.shape[0]', '-', 'self.crop_size[0],', '0)', 'margin_w', '=', 'max(img.shape[1]', '-', 'self.crop_size[1],', '0)', 'offset_h', '=', 'np.random.randint(0,', 'margin_h', '+', '1)', 'offset_w', '=', 'np.random.randint(0,', 'margin_w', '+', '1)', '(crop_y1,',... | 578,388 |
aeon-toolkit/aeon | test_time_since.py | test_fit_transform_datetime_daily_idx_panel_multiple_starts_output | test_fit_transform_datetime_daily_idx_panel_multiple_starts_output | Tests that we get the expected outputs when input is panel data. | [
"Tests",
"that",
"we",
"get",
"the",
"expected",
"outputs",
"when",
"input",
"is",
"panel",
"data."
] | def test_fit_transform_datetime_daily_idx_panel_multiple_starts_output(df_datetime_daily_idx_panel):
transformer = TimeSince(start=['2000-01-01', '2000-01-02'], freq='D', to_numeric=True, keep_original_columns=False, positive_only=False)
Xt = transformer.fit_transform(df_datetime_daily_idx_panel)
expected =... | ['def', 'test_fit_transform_datetime_daily_idx_panel_multiple_starts_output(df_datetime_daily_idx_panel):', 'transformer', '=', "TimeSince(start=['2000-01-01',", "'2000-01-02'],", "freq='D',", 'to_numeric=True,', 'keep_original_columns=False,', 'positive_only=False)', 'Xt', '=', 'transformer.fit_transform(df_datetime_d... | 400,089 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | digraph_ops.py | CombineArcAndRootPotentials | CombineArcAndRootPotentials | Combines arc and root potentials into a single set of potentials. | [
"Combines",
"arc",
"and",
"root",
"potentials",
"into",
"a",
"single",
"set",
"of",
"potentials."
] | def CombineArcAndRootPotentials(arcs, roots):
check.Eq(arcs.get_shape().ndims, 3, 'arcs must be rank 3')
check.Eq(roots.get_shape().ndims, 2, 'roots must be a matrix')
dtype = arcs.dtype.base_dtype
check.Same([dtype, roots.dtype.base_dtype], 'dtype mismatch')
roots_shape = tf.shape(roots)
arcs_s... | ['def', 'CombineArcAndRootPotentials(arcs,', 'roots):', 'check.Eq(arcs.get_shape().ndims,', '3,', "'arcs", 'must', 'be', 'rank', "3')", 'check.Eq(roots.get_shape().ndims,', '2,', "'roots", 'must', 'be', 'a', "matrix')", 'dtype', '=', 'arcs.dtype.base_dtype', 'check.Same([dtype,', 'roots.dtype.base_dtype],', "'dtype", "... | 28,164 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.