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 |
|---|---|---|---|---|---|---|---|---|
arshpreetsingh/quantopian-machinelearning | dimension.py | Dimension.is_zero | is_zero | True if this `Dimension` represents a zero size. | [
"True",
"if",
"this",
"`Dimension`",
"represents",
"a",
"zero",
"size."
] | def is_zero(self):
return self.preferred == 0 or self.max == 0 | ['def', 'is_zero(self):', 'return', 'self.preferred', '==', '0', 'or', 'self.max', '==', '0'] | 892,439 |
suarez12138/AI-Reversi_IMP_TextDichotomy | setup_common.py | long_double_representation | long_double_representation | Given a binary dump as given by GNU od -b, look for long double representation. | [
"Given",
"a",
"binary",
"dump",
"as",
"given",
"by",
"GNU",
"od",
"-b,",
"look",
"for",
"long",
"double",
"representation."
] | def long_double_representation(lines):
read = [''] * 32
saw = None
for line in lines:
for w in line.split()[1:]:
read.pop(0)
read.append(w)
if read[-8:] == _AFTER_SEQ:
saw = copy.copy(read)
if read[:12] == _BEFORE_SEQ[4:]:
... | ['def', 'long_double_representation(lines):', 'read', '=', "['']", '*', '32', 'saw', '=', 'None', 'for', 'line', 'in', 'lines:', 'for', 'w', 'in', 'line.split()[1:]:', 'read.pop(0)', 'read.append(w)', 'if', 'read[-8:]', '==', '_AFTER_SEQ:', 'saw', '=', 'copy.copy(read)', 'if', 'read[:12]', '==', '_BEFORE_SEQ[4:]:', 'if... | 97,661 |
rudranil723/mini-main | request.py | HttpRequest.get_host | get_host | Return the HTTP host using the environment or request headers. | [
"Return",
"the",
"HTTP",
"host",
"using",
"the",
"environment",
"or",
"request",
"headers."
] | def get_host(self):
host = self._get_raw_host()
allowed_hosts = settings.ALLOWED_HOSTS
if settings.DEBUG and (not allowed_hosts):
allowed_hosts = ['localhost', '127.0.0.1', '[::1]']
(domain, port) = split_domain_port(host)
if domain and validate_host(domain, allowed_hosts):
return ho... | ['def', 'get_host(self):', 'host', '=', 'self._get_raw_host()', 'allowed_hosts', '=', 'settings.ALLOWED_HOSTS', 'if', 'settings.DEBUG', 'and', '(not', 'allowed_hosts):', 'allowed_hosts', '=', "['localhost',", "'127.0.0.1',", "'[::1]']", '(domain,', 'port)', '=', 'split_domain_port(host)', 'if', 'domain', 'and', 'valida... | 316,331 |
Yang-Bob/PMMs | functional.py | vflip | vflip | Vertically flip the given PIL Image. | [
"Vertically",
"flip",
"the",
"given",
"PIL",
"Image."
] | def vflip(img):
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
return img.transpose(Image.FLIP_TOP_BOTTOM) | ['def', 'vflip(img):', 'if', 'not', '_is_pil_image(img):', 'raise', "TypeError('img", 'should', 'be', 'PIL', 'Image.', 'Got', "{}'.format(type(img)))", 'return', 'img.transpose(Image.FLIP_TOP_BOTTOM)'] | 780,793 |
PaddlePaddle/PaddleSpeech | utils.py | repeatedly | repeatedly | Repeatedly yield samples from an iterator. | [
"Repeatedly",
"yield",
"samples",
"from",
"an",
"iterator."
] | def repeatedly(source: Iterator, nepochs: int=None, nbatches: int=None, nsamples: int=None, batchsize: Callable[..., int]=guess_batchsize):
epoch = 0
batch = 0
total = 0
while True:
for sample in source:
yield sample
batch += 1
if nbatches is not None and batc... | ['def', 'repeatedly(source:', 'Iterator,', 'nepochs:', 'int=None,', 'nbatches:', 'int=None,', 'nsamples:', 'int=None,', 'batchsize:', 'Callable[...,', 'int]=guess_batchsize):', 'epoch', '=', '0', 'batch', '=', '0', 'total', '=', '0', 'while', 'True:', 'for', 'sample', 'in', 'source:', 'yield', 'sample', 'batch', '+=', ... | 276,486 |
open-mmlab/mmrotate | utils.py | rotated_anchor_inside_flags | rotated_anchor_inside_flags | Check whether the rotated anchors are inside the border. | [
"Check",
"whether",
"the",
"rotated",
"anchors",
"are",
"inside",
"the",
"border."
] | def rotated_anchor_inside_flags(flat_anchors, valid_flags, img_shape, allowed_border=0):
(img_h, img_w) = img_shape[:2]
if allowed_border >= 0:
(cx, cy) = (flat_anchors[:, i] for i in range(2))
inside_flags = valid_flags & (cx >= -allowed_border) & (cy >= -allowed_border) & (cx < img_w + allowed... | ['def', 'rotated_anchor_inside_flags(flat_anchors,', 'valid_flags,', 'img_shape,', 'allowed_border=0):', '(img_h,', 'img_w)', '=', 'img_shape[:2]', 'if', 'allowed_border', '>=', '0:', '(cx,', 'cy)', '=', '(flat_anchors[:,', 'i]', 'for', 'i', 'in', 'range(2))', 'inside_flags', '=', 'valid_flags', '&', '(cx', '>=', '-all... | 624,976 |
AdroitAnandAI/Computer-Vision-Math-Magic-vs-AI | searchImgObject.py | getShapePoints | getShapePoints | Get 'n' random points which describes the shape inside image. | [
"Get",
"'n'",
"random",
"points",
"which",
"describes",
"the",
"shape",
"inside",
"image."
] | def getShapePoints(sc, path):
descs = []
img = cv2.imread(path, 0)
edges = cv2.Canny(img, 100, 200)
(min_x, min_y, max_x, max_y) = get_contour_bounding_rectangles(edges)
r = (min_x, min_y, max_x, max_y)
points = sc.get_points_from_img(img[r[1]:r[3], r[0]:r[2]], 1000)
return np.array(points) | ['def', 'getShapePoints(sc,', 'path):', 'descs', '=', '[]', 'img', '=', 'cv2.imread(path,', '0)', 'edges', '=', 'cv2.Canny(img,', '100,', '200)', '(min_x,', 'min_y,', 'max_x,', 'max_y)', '=', 'get_contour_bounding_rectangles(edges)', 'r', '=', '(min_x,', 'min_y,', 'max_x,', 'max_y)', 'points', '=', 'sc.get_points_from_... | 470,301 |
jdogcoderarchives/AI | busters.py | GameState.getResult | getResult | Returns the state after the specified agent takes the action. | [
"Returns",
"the",
"state",
"after",
"the",
"specified",
"agent",
"takes",
"the",
"action."
] | def getResult(self, agentIndex, action):
if self.isWin() or self.isLose():
raise Exception("Can't generate a result of a terminal state.")
state = GameState(self)
if agentIndex == 0:
state.data._eaten = [False for i in range(state.getNumAgents())]
PacmanRules.applyAction(state, actio... | ['def', 'getResult(self,', 'agentIndex,', 'action):', 'if', 'self.isWin()', 'or', 'self.isLose():', 'raise', 'Exception("Can\'t', 'generate', 'a', 'result', 'of', 'a', 'terminal', 'state.")', 'state', '=', 'GameState(self)', 'if', 'agentIndex', '==', '0:', 'state.data._eaten', '=', '[False', 'for', 'i', 'in', 'range(st... | 66,599 |
rifqind/Agent-Programs-3KS1 | iptest.py | ExclusionPlugin.wantDirectory | wantDirectory | Return whether the given directory should be scanned for tests. | [
"Return",
"whether",
"the",
"given",
"directory",
"should",
"be",
"scanned",
"for",
"tests."
] | def wantDirectory(self, directory):
if any((pat in directory for pat in self.exclude_patterns)):
return False
return None | ['def', 'wantDirectory(self,', 'directory):', 'if', 'any((pat', 'in', 'directory', 'for', 'pat', 'in', 'self.exclude_patterns)):', 'return', 'False', 'return', 'None'] | 41,761 |
weimin17/Object-Detection_HelmetDetection | parameter_noise_sampling.py | ParameterNoiseSampling.update_noise | update_noise | Increase noise if distance btw original and corrupted distrib small. | [
"Increase",
"noise",
"if",
"distance",
"btw",
"original",
"and",
"corrupted",
"distrib",
"small."
] | def update_noise(self):
kl = self.compute_distance()
delta = -np.log1p(-self.eps + self.eps / self.hparams.num_actions)
if kl < delta:
self.noise_std *= 1.01
else:
self.noise_std /= 1.01
self.eps *= 0.99
if self.verbose:
print('Update eps={} | kl={} | std={} | delta={} | ... | ['def', 'update_noise(self):', 'kl', '=', 'self.compute_distance()', 'delta', '=', '-np.log1p(-self.eps', '+', 'self.eps', '/', 'self.hparams.num_actions)', 'if', 'kl', '<', 'delta:', 'self.noise_std', '*=', '1.01', 'else:', 'self.noise_std', '/=', '1.01', 'self.eps', '*=', '0.99', 'if', 'self.verbose:', "print('Update... | 762,294 |
zhang614/MicroGrid | download.py | user_agent | user_agent | Return a string representing the user agent. | [
"Return",
"a",
"string",
"representing",
"the",
"user",
"agent."
] | def user_agent():
data = {'installer': {'name': 'pip', 'version': pip.__version__}, 'python': platform.python_version(), 'implementation': {'name': platform.python_implementation()}}
if data['implementation']['name'] == 'CPython':
data['implementation']['version'] = platform.python_version()
elif da... | ['def', 'user_agent():', 'data', '=', "{'installer':", "{'name':", "'pip',", "'version':", 'pip.__version__},', "'python':", 'platform.python_version(),', "'implementation':", "{'name':", 'platform.python_implementation()}}', 'if', "data['implementation']['name']", '==', "'CPython':", "data['implementation']['version']... | 667,761 |
Xianpeng919/MonoCon | base_box3d.py | BaseInstance3DBoxes.translate | translate | Translate boxes with the given translation vector. | [
"Translate",
"boxes",
"with",
"the",
"given",
"translation",
"vector."
] | def translate(self, trans_vector):
if not isinstance(trans_vector, torch.Tensor):
trans_vector = self.tensor.new_tensor(trans_vector)
self.tensor[:, :3] += trans_vector | ['def', 'translate(self,', 'trans_vector):', 'if', 'not', 'isinstance(trans_vector,', 'torch.Tensor):', 'trans_vector', '=', 'self.tensor.new_tensor(trans_vector)', 'self.tensor[:,', ':3]', '+=', 'trans_vector'] | 654,280 |
43Carrig/recurrent_neural_networks_practice | resource_variable_ops.py | ResourceVariable.graph | graph | The `Graph` of this variable. | [
"The",
"`Graph`",
"of",
"this",
"variable."
] | def graph(self):
return self._handle.graph | ['def', 'graph(self):', 'return', 'self._handle.graph'] | 338,911 |
kianak2002/Sentiment-Emotion-Analysis-project | dirtools.py | dir_to_zipfile | dir_to_zipfile | Construct an in-memory zip file for a directory. | [
"Construct",
"an",
"in-memory",
"zip",
"file",
"for",
"a",
"directory."
] | def dir_to_zipfile(root):
buffer = io.BytesIO()
zip_file = zipfile.ZipFile(buffer, 'w')
for (root, dirs, files) in os.walk(root):
for path in dirs:
fs_path = os.path.join(root, path)
rel_path = os.path.relpath(fs_path, root)
zip_file.writestr(rel_path + '/', '')
... | ['def', 'dir_to_zipfile(root):', 'buffer', '=', 'io.BytesIO()', 'zip_file', '=', 'zipfile.ZipFile(buffer,', "'w')", 'for', '(root,', 'dirs,', 'files)', 'in', 'os.walk(root):', 'for', 'path', 'in', 'dirs:', 'fs_path', '=', 'os.path.join(root,', 'path)', 'rel_path', '=', 'os.path.relpath(fs_path,', 'root)', 'zip_file.wri... | 875,148 |
dguo98/DiffPruning | modeling_bert.py | load_tf_weights_in_bert | load_tf_weights_in_bert | Load tf checkpoints in a pytorch model. | [
"Load",
"tf",
"checkpoints",
"in",
"a",
"pytorch",
"model."
] | def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
try:
import re
import numpy as np
import tensorflow as tf
except ImportError:
logger.error('Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see https://www.tensorflow.org/install/ f... | ['def', 'load_tf_weights_in_bert(model,', 'config,', 'tf_checkpoint_path):', 'try:', 'import', 're', 'import', 'numpy', 'as', 'np', 'import', 'tensorflow', 'as', 'tf', 'except', 'ImportError:', "logger.error('Loading", 'a', 'TensorFlow', 'model', 'in', 'PyTorch,', 'requires', 'TensorFlow', 'to', 'be', 'installed.', 'Pl... | 550,549 |
danamyu/hedgehog_detector | rebar.py | SBN.get_dynamic_rebar_gradient | get_dynamic_rebar_gradient | Get the dynamic rebar gradient (t, eta optimized). | [
"Get",
"the",
"dynamic",
"rebar",
"gradient",
"(t,",
"eta",
"optimized)."
] | def get_dynamic_rebar_gradient(self):
tiled_pre_temperature = tf.tile([self.pre_temperature_variable], [self.batch_size])
temperature = tf.exp(tiled_pre_temperature)
(hardELBO, nvil_gradient, logQHard) = self._create_hard_elbo()
if self.hparams.quadratic:
(gumbel_cv, extra) = self._create_gumbel... | ['def', 'get_dynamic_rebar_gradient(self):', 'tiled_pre_temperature', '=', 'tf.tile([self.pre_temperature_variable],', '[self.batch_size])', 'temperature', '=', 'tf.exp(tiled_pre_temperature)', '(hardELBO,', 'nvil_gradient,', 'logQHard)', '=', 'self._create_hard_elbo()', 'if', 'self.hparams.quadratic:', '(gumbel_cv,', ... | 590,330 |
zhang614/MicroGrid | _constraints.py | new_constraint_to_old | new_constraint_to_old | Converts new-style constraint objects to old-style constraint dictionaries. | [
"Converts",
"new-style",
"constraint",
"objects",
"to",
"old-style",
"constraint",
"dictionaries."
] | def new_constraint_to_old(con, x0):
if isinstance(con, NonlinearConstraint):
if con.finite_diff_jac_sparsity is not None or con.finite_diff_rel_step is not None or (not isinstance(con.hess, BFGS)) or con.keep_feasible:
warn('Constraint options `finite_diff_jac_sparsity`, `finite_diff_rel_step`, ... | ['def', 'new_constraint_to_old(con,', 'x0):', 'if', 'isinstance(con,', 'NonlinearConstraint):', 'if', 'con.finite_diff_jac_sparsity', 'is', 'not', 'None', 'or', 'con.finite_diff_rel_step', 'is', 'not', 'None', 'or', '(not', 'isinstance(con.hess,', 'BFGS))', 'or', 'con.keep_feasible:', "warn('Constraint", 'options', '`f... | 669,384 |
VoraHarsh/iit-cs480-Introduction-to-- | games.py | StochasticGame.probability | probability | Return the probability of occurence of a chance. | [
"Return",
"the",
"probability",
"of",
"occurence",
"of",
"a",
"chance."
] | def probability(self, chance):
raise NotImplementedError | ['def', 'probability(self,', 'chance):', 'raise', 'NotImplementedError'] | 229,096 |
tensorflow/agents | utils.py | create_bandit_policy_type_tensor_spec | create_bandit_policy_type_tensor_spec | Create tensor spec for bandit policy type. | [
"Create",
"tensor",
"spec",
"for",
"bandit",
"policy",
"type."
] | def create_bandit_policy_type_tensor_spec(shape: types.Shape) -> types.BoundedTensorSpec:
return tensor_spec.BoundedTensorSpec(shape=shape, dtype=tf.int32, minimum=BanditPolicyType.UNKNOWN, maximum=BanditPolicyType.FALCON) | ['def', 'create_bandit_policy_type_tensor_spec(shape:', 'types.Shape)', '->', 'types.BoundedTensorSpec:', 'return', 'tensor_spec.BoundedTensorSpec(shape=shape,', 'dtype=tf.int32,', 'minimum=BanditPolicyType.UNKNOWN,', 'maximum=BanditPolicyType.FALCON)'] | 22,876 |
Layman0527/Parallel-Swin-Transformer-for-- | inference.py | show_result_pyplot | show_result_pyplot | Visualize the segmentation results on the image. | [
"Visualize",
"the",
"segmentation",
"results",
"on",
"the",
"image."
] | def show_result_pyplot(model, img, result, palette=None, fig_size=(15, 10), opacity=0.5, title='', block=True):
if hasattr(model, 'module'):
model = model.module
img = model.show_result(img, result, palette=palette, show=False, opacity=opacity)
plt.figure(figsize=fig_size)
plt.imshow(mmcv.bgr2rg... | ['def', 'show_result_pyplot(model,', 'img,', 'result,', 'palette=None,', 'fig_size=(15,', '10),', 'opacity=0.5,', "title='',", 'block=True):', 'if', 'hasattr(model,', "'module'):", 'model', '=', 'model.module', 'img', '=', 'model.show_result(img,', 'result,', 'palette=palette,', 'show=False,', 'opacity=opacity)', 'plt.... | 764,198 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | locale.py | atoi | atoi | Converts a string to an integer according to the locale settings. | [
"Converts",
"a",
"string",
"to",
"an",
"integer",
"according",
"to",
"the",
"locale",
"settings."
] | def atoi(string):
return int(delocalize(string)) | ['def', 'atoi(string):', 'return', 'int(delocalize(string))'] | 801,512 |
myothida/Supervised-Machine-Learning | disk.py | mkdirp | mkdirp | Ensure directory d exists (like mkdir -p on Unix) No guarantee that the directory is writable. | [
"Ensure",
"directory",
"d",
"exists",
"(like",
"mkdir",
"-p",
"on",
"Unix)",
"No",
"guarantee",
"that",
"the",
"directory",
"is",
"writable."
] | def mkdirp(d):
try:
os.makedirs(d)
except OSError as e:
if e.errno != errno.EEXIST:
raise | ['def', 'mkdirp(d):', 'try:', 'os.makedirs(d)', 'except', 'OSError', 'as', 'e:', 'if', 'e.errno', '!=', 'errno.EEXIST:', 'raise'] | 361,432 |
matsu0228/nlp-jp | lexer.py | TokenStream.push | push | Push a token back to the stream. | [
"Push",
"a",
"token",
"back",
"to",
"the",
"stream."
] | def push(self, token):
self._pushed.append(token) | ['def', 'push(self,', 'token):', 'self._pushed.append(token)'] | 787,897 |
jxhe/unify-parameter-efficient-tuning | retrieval_rag.py | Index.is_initialized | is_initialized | Returns :obj:`True` if index is already initialized. | [
"Returns",
":obj:`True`",
"if",
"index",
"is",
"already",
"initialized."
] | def is_initialized(self):
raise NotImplementedError | ['def', 'is_initialized(self):', 'raise', 'NotImplementedError'] | 949,161 |
prouast/deep-intake-detection | oreba_main.py | oreba_model_fn | oreba_model_fn | Select the appropriate model_fn and model to run on OREBA. | [
"Select",
"the",
"appropriate",
"model_fn",
"and",
"model",
"to",
"run",
"on",
"OREBA."
] | def oreba_model_fn(features, labels, mode, params):
model_params = tf.contrib.training.HParams(batch_norm=True, data_format=FLAGS.data_format, dropout=0.5, dtype=get_tf_dtype(FLAGS.dtype), frame_size=FRAME_SIZE, num_channels=NUM_CHANNELS, num_classes=get_num_classes(FLAGS.label_category), num_dense=1024, oreba_kern... | ['def', 'oreba_model_fn(features,', 'labels,', 'mode,', 'params):', 'model_params', '=', 'tf.contrib.training.HParams(batch_norm=True,', 'data_format=FLAGS.data_format,', 'dropout=0.5,', 'dtype=get_tf_dtype(FLAGS.dtype),', 'frame_size=FRAME_SIZE,', 'num_channels=NUM_CHANNELS,', 'num_classes=get_num_classes(FLAGS.label_... | 517,231 |
IBM/mi-prometheus | mae_interface.py | MAEInterface.freeze | freeze | Freezes the trainable weigths. | [
"Freezes",
"the",
"trainable",
"weigths."
] | def freeze(self):
for param in self.hidden2write_params.parameters():
param.requires_grad = False | ['def', 'freeze(self):', 'for', 'param', 'in', 'self.hidden2write_params.parameters():', 'param.requires_grad', '=', 'False'] | 635,491 |
victordibia/data2vis | decoder.py | dynamic_decode | dynamic_decode | Perform dynamic decoding with `decoder`. | [
"Perform",
"dynamic",
"decoding",
"with",
"`decoder`."
] | def dynamic_decode(decoder, output_time_major=False, impute_finished=False, maximum_iterations=None, parallel_iterations=32, swap_memory=False, scope=None):
if not isinstance(decoder, Decoder):
raise TypeError('Expected decoder to be type Decoder, but saw: %s' % type(decoder))
with variable_scope.variab... | ['def', 'dynamic_decode(decoder,', 'output_time_major=False,', 'impute_finished=False,', 'maximum_iterations=None,', 'parallel_iterations=32,', 'swap_memory=False,', 'scope=None):', 'if', 'not', 'isinstance(decoder,', 'Decoder):', 'raise', "TypeError('Expected", 'decoder', 'to', 'be', 'type', 'Decoder,', 'but', 'saw:',... | 126,817 |
open-mmlab/mmrotate | test_rtransforms.py | check_result_same | check_result_same | Check whether the `pipeline_results` is the same with the predefined `results`. | [
"Check",
"whether",
"the",
"`pipeline_results`",
"is",
"the",
"same",
"with",
"the",
"predefined",
"`results`."
] | def check_result_same(results, pipeline_results):
_check_fields(results, pipeline_results, results.get('img_fields', ['img']))
_check_fields(results, pipeline_results, results.get('bbox_fields', []))
if 'gt_labels' in results:
assert np.equal(results['gt_labels'], pipeline_results['gt_labels']).all(... | ['def', 'check_result_same(results,', 'pipeline_results):', '_check_fields(results,', 'pipeline_results,', "results.get('img_fields',", "['img']))", '_check_fields(results,', 'pipeline_results,', "results.get('bbox_fields',", '[]))', 'if', "'gt_labels'", 'in', 'results:', 'assert', "np.equal(results['gt_labels'],", "pi... | 625,250 |
p-venkatesh/NaturalLanguageProcessing | run_squad.py | write_predictions | write_predictions | Write final predictions to the json file and log-odds of null if needed. | [
"Write",
"final",
"predictions",
"to",
"the",
"json",
"file",
"and",
"log-odds",
"of",
"null",
"if",
"needed."
] | def write_predictions(all_examples, all_features, all_results, n_best_size, max_answer_length, do_lower_case, output_prediction_file, output_nbest_file, output_null_log_odds_file):
tf.logging.info('Writing predictions to: %s' % output_prediction_file)
tf.logging.info('Writing nbest to: %s' % output_nbest_file)
... | ['def', 'write_predictions(all_examples,', 'all_features,', 'all_results,', 'n_best_size,', 'max_answer_length,', 'do_lower_case,', 'output_prediction_file,', 'output_nbest_file,', 'output_null_log_odds_file):', "tf.logging.info('Writing", 'predictions', 'to:', "%s'", '%', 'output_prediction_file)', "tf.logging.info('W... | 799,508 |
acrosson/nlp | dureader_eval.py | compute_bleu_rouge | compute_bleu_rouge | Compute bleu and rouge scores. | [
"Compute",
"bleu",
"and",
"rouge",
"scores."
] | def compute_bleu_rouge(pred_dict, ref_dict, bleu_order=4):
assert set(pred_dict.keys()) == set(ref_dict.keys()), 'missing keys: {}'.format(set(ref_dict.keys()) - set(pred_dict.keys()))
scores = {}
(bleu_scores, _) = Bleu(bleu_order).compute_score(ref_dict, pred_dict)
for (i, bleu_score) in enumerate(ble... | ['def', 'compute_bleu_rouge(pred_dict,', 'ref_dict,', 'bleu_order=4):', 'assert', 'set(pred_dict.keys())', '==', 'set(ref_dict.keys()),', "'missing", 'keys:', "{}'.format(set(ref_dict.keys())", '-', 'set(pred_dict.keys()))', 'scores', '=', '{}', '(bleu_scores,', '_)', '=', 'Bleu(bleu_order).compute_score(ref_dict,', 'p... | 808,792 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | test_zmq_shell.py | CounterSession.send | send | A trivial override to just augment the existing call with an increment to the send counter. | [
"A",
"trivial",
"override",
"to",
"just",
"augment",
"the",
"existing",
"call",
"with",
"an",
"increment",
"to",
"the",
"send",
"counter."
] | def send(self, *args, **kwargs):
self.send_count += 1
super(CounterSession, self).send(*args, **kwargs) | ['def', 'send(self,', '*args,', '**kwargs):', 'self.send_count', '+=', '1', 'super(CounterSession,', 'self).send(*args,', '**kwargs)'] | 447,942 |
Eric3911/OpenAGI | utils.py | lookup_sym | lookup_sym | Look up a symbol in a list of modules. | [
"Look",
"up",
"a",
"symbol",
"in",
"a",
"list",
"of",
"modules."
] | def lookup_sym(sym: str, modules: list):
for mname in modules:
module = importlib.import_module(mname, package='webdataset')
result = getattr(module, sym, None)
if result is not None:
return result
return None | ['def', 'lookup_sym(sym:', 'str,', 'modules:', 'list):', 'for', 'mname', 'in', 'modules:', 'module', '=', 'importlib.import_module(mname,', "package='webdataset')", 'result', '=', 'getattr(module,', 'sym,', 'None)', 'if', 'result', 'is', 'not', 'None:', 'return', 'result', 'return', 'None'] | 251,079 |
matsu0228/nlp-jp | test_message.py | await_gc | await_gc | wait for refcount on an object to drop to an expected value Necessary because of the zero-copy gc thread, which can take some time to receive its DECREF message. | [
"wait",
"for",
"refcount",
"on",
"an",
"object",
"to",
"drop",
"to",
"an",
"expected",
"value",
"Necessary",
"because",
"of",
"the",
"zero-copy",
"gc",
"thread,",
"which",
"can",
"take",
"some",
"time",
"to",
"receive",
"its",
"DECREF",
"message."
] | def await_gc(obj, rc):
for i in range(50):
if grc(obj) <= rc + 2:
return
time.sleep(0.05) | ['def', 'await_gc(obj,', 'rc):', 'for', 'i', 'in', 'range(50):', 'if', 'grc(obj)', '<=', 'rc', '+', '2:', 'return', 'time.sleep(0.05)'] | 807,923 |
quelibrio/NaturalLanguageProcessing | tokenization.py | BasicTokenizer.tokenize | tokenize | Tokenizes a piece of text. | [
"Tokenizes",
"a",
"piece",
"of",
"text."
] | def tokenize(self, text):
text = convert_to_unicode(text)
text = self._clean_text(text)
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
token... | ['def', 'tokenize(self,', 'text):', 'text', '=', 'convert_to_unicode(text)', 'text', '=', 'self._clean_text(text)', 'text', '=', 'self._tokenize_chinese_chars(text)', 'orig_tokens', '=', 'whitespace_tokenize(text)', 'split_tokens', '=', '[]', 'for', 'token', 'in', 'orig_tokens:', 'if', 'self.do_lower_case:', 'token', '... | 800,227 |
tobegit3hub/deep_image_model | tensor_forest.py | RandomTreeGraphs.training_graph | training_graph | Constructs a TF graph for training a random tree. | [
"Constructs",
"a",
"TF",
"graph",
"for",
"training",
"a",
"random",
"tree."
] | def training_graph(self, input_data, input_labels, random_seed, data_spec, epoch=None, input_weights=None):
epoch = [0] if epoch is None else epoch
if input_weights is None:
input_weights = []
sparse_indices = []
sparse_values = []
sparse_shape = []
if isinstance(input_data, sparse_tenso... | ['def', 'training_graph(self,', 'input_data,', 'input_labels,', 'random_seed,', 'data_spec,', 'epoch=None,', 'input_weights=None):', 'epoch', '=', '[0]', 'if', 'epoch', 'is', 'None', 'else', 'epoch', 'if', 'input_weights', 'is', 'None:', 'input_weights', '=', '[]', 'sparse_indices', '=', '[]', 'sparse_values', '=', '[]... | 182,113 |
rifqind/Agent-Programs-3KS1 | compiler.py | CodeGenerator.push_assign_tracking | push_assign_tracking | Pushes a new layer for assignment tracking. | [
"Pushes",
"a",
"new",
"layer",
"for",
"assignment",
"tracking."
] | def push_assign_tracking(self):
self._assign_stack.append(set()) | ['def', 'push_assign_tracking(self):', 'self._assign_stack.append(set())'] | 42,180 |
voxel51/fiftyone | fields.py | validate_type_constraints | validate_type_constraints | Validates the given type constraints. | [
"Validates",
"the",
"given",
"type",
"constraints."
] | def validate_type_constraints(ftype=None, embedded_doc_type=None):
if ftype is not None:
if etau.is_container(ftype):
ftype = tuple(ftype)
else:
ftype = (ftype,)
for _ftype in ftype:
if not issubclass(_ftype, Field):
raise ValueError('Field... | ['def', 'validate_type_constraints(ftype=None,', 'embedded_doc_type=None):', 'if', 'ftype', 'is', 'not', 'None:', 'if', 'etau.is_container(ftype):', 'ftype', '=', 'tuple(ftype)', 'else:', 'ftype', '=', '(ftype,)', 'for', '_ftype', 'in', 'ftype:', 'if', 'not', 'issubclass(_ftype,', 'Field):', 'raise', "ValueError('Field... | 583,098 |
googleapis/python-aiplatform | e2e_base.py | TestEndToEnd.prepare_staging_bucket | prepare_staging_bucket | Create a staging bucket and store bucket resource object in shared state. | [
"Create",
"a",
"staging",
"bucket",
"and",
"store",
"bucket",
"resource",
"object",
"in",
"shared",
"state."
] | def prepare_staging_bucket(self, shared_state: Dict[str, Any]) -> Generator[storage.bucket.Bucket, None, None]:
staging_bucket_name = f'{self._temp_prefix.lower()}-{uuid.uuid4()}'[:63]
shared_state['staging_bucket_name'] = staging_bucket_name
storage_client = storage.Client(project=_PROJECT)
shared_stat... | ['def', 'prepare_staging_bucket(self,', 'shared_state:', 'Dict[str,', 'Any])', '->', 'Generator[storage.bucket.Bucket,', 'None,', 'None]:', 'staging_bucket_name', '=', "f'{self._temp_prefix.lower()}-{uuid.uuid4()}'[:63]", "shared_state['staging_bucket_name']", '=', 'staging_bucket_name', 'storage_client', '=', 'storage... | 862,942 |
nicknochnack/RealTimeSignLanguageTFJS | runner.py | convert_frozen_graph_def_to_tflite | convert_frozen_graph_def_to_tflite | Converts a TensorFlow GraphDef into a serialized TFLite Flatbuffer. | [
"Converts",
"a",
"TensorFlow",
"GraphDef",
"into",
"a",
"serialized",
"TFLite",
"Flatbuffer."
] | def convert_frozen_graph_def_to_tflite(graph_def: tf.compat.v1.GraphDef, model_config: Dict[str, Any], input_tensors: Sequence[tf.Tensor], output_tensors: Sequence[tf.Tensor]) -> bytes:
converter = tf.lite.TFLiteConverter(graph_def, input_tensors, output_tensors)
if model_config['quantize']:
converter.i... | ['def', 'convert_frozen_graph_def_to_tflite(graph_def:', 'tf.compat.v1.GraphDef,', 'model_config:', 'Dict[str,', 'Any],', 'input_tensors:', 'Sequence[tf.Tensor],', 'output_tensors:', 'Sequence[tf.Tensor])', '->', 'bytes:', 'converter', '=', 'tf.lite.TFLiteConverter(graph_def,', 'input_tensors,', 'output_tensors)', 'if'... | 831,176 |
ADLab3Ds/TiG-BEV | parta2_bbox_head.py | PartA2BboxHead.get_corner_loss_lidar | get_corner_loss_lidar | Calculate corner loss of given boxes. | [
"Calculate",
"corner",
"loss",
"of",
"given",
"boxes."
] | def get_corner_loss_lidar(self, pred_bbox3d, gt_bbox3d, delta=1):
assert pred_bbox3d.shape[0] == gt_bbox3d.shape[0]
gt_boxes_structure = LiDARInstance3DBoxes(gt_bbox3d)
pred_box_corners = LiDARInstance3DBoxes(pred_bbox3d).corners
gt_box_corners = gt_boxes_structure.corners
gt_bbox3d_flip = gt_boxes_... | ['def', 'get_corner_loss_lidar(self,', 'pred_bbox3d,', 'gt_bbox3d,', 'delta=1):', 'assert', 'pred_bbox3d.shape[0]', '==', 'gt_bbox3d.shape[0]', 'gt_boxes_structure', '=', 'LiDARInstance3DBoxes(gt_bbox3d)', 'pred_box_corners', '=', 'LiDARInstance3DBoxes(pred_bbox3d).corners', 'gt_box_corners', '=', 'gt_boxes_structure.c... | 917,111 |
RE-OWOD/RE-OWOD | box_regression.py | Box2BoxTransform.apply_deltas | apply_deltas | Apply transformation `deltas` (dx, dy, dw, dh) to `boxes`. | [
"Apply",
"transformation",
"`deltas`",
"(dx,",
"dy,",
"dw,",
"dh)",
"to",
"`boxes`."
] | def apply_deltas(self, deltas, boxes):
boxes = boxes.to(deltas.dtype)
widths = boxes[:, 2] - boxes[:, 0]
heights = boxes[:, 3] - boxes[:, 1]
ctr_x = boxes[:, 0] + 0.5 * widths
ctr_y = boxes[:, 1] + 0.5 * heights
(wx, wy, ww, wh) = self.weights
dx = deltas[:, 0::4] / wx
dy = deltas[:, 1::... | ['def', 'apply_deltas(self,', 'deltas,', 'boxes):', 'boxes', '=', 'boxes.to(deltas.dtype)', 'widths', '=', 'boxes[:,', '2]', '-', 'boxes[:,', '0]', 'heights', '=', 'boxes[:,', '3]', '-', 'boxes[:,', '1]', 'ctr_x', '=', 'boxes[:,', '0]', '+', '0.5', '*', 'widths', 'ctr_y', '=', 'boxes[:,', '1]', '+', '0.5', '*', 'height... | 848,993 |
KleinYuan/tf-segmentation | network.py | PSPNetwork.get_output | get_output | Returns the current network output. | [
"Returns",
"the",
"current",
"network",
"output."
] | def get_output(self):
return self.terminals[-1] | ['def', 'get_output(self):', 'return', 'self.terminals[-1]'] | 915,624 |
tobegit3hub/deep_image_model | loss_ops_test.py | SparseSoftmaxCrossEntropyLossTest.testInconsistentWeightSizeRaisesException | testInconsistentWeightSizeRaisesException | The weight tensor has incorrect number of elements. | [
"The",
"weight",
"tensor",
"has",
"incorrect",
"number",
"of",
"elements."
] | def testInconsistentWeightSizeRaisesException(self):
with self.test_session():
logits = tf.constant([[100.0, -100.0, -100.0], [-100.0, 100.0, -100.0], [-100.0, -100.0, 100.0]])
labels = tf.constant([[0], [1], [2]])
weights = tf.constant([1.2, 3.4, 5.6, 7.8])
with self.assertRaises(Va... | ['def', 'testInconsistentWeightSizeRaisesException(self):', 'with', 'self.test_session():', 'logits', '=', 'tf.constant([[100.0,', '-100.0,', '-100.0],', '[-100.0,', '100.0,', '-100.0],', '[-100.0,', '-100.0,', '100.0]])', 'labels', '=', 'tf.constant([[0],', '[1],', '[2]])', 'weights', '=', 'tf.constant([1.2,', '3.4,',... | 181,931 |
Shubham-786/Natural-Language-Processing | RNN_machine_translation.py | translate | translate | Translate a single text-string. | [
"Translate",
"a",
"single",
"text-string."
] | def translate(input_text, true_output_text=None):
input_tokens = tokenizer_src.text_to_tokens(text=input_text, reverse=True, padding=True)
initial_state = model_encoder.predict(input_tokens)
max_tokens = tokenizer_dest.max_tokens
shape = (1, max_tokens)
decoder_input_data = np.zeros(shape=shape, dty... | ['def', 'translate(input_text,', 'true_output_text=None):', 'input_tokens', '=', 'tokenizer_src.text_to_tokens(text=input_text,', 'reverse=True,', 'padding=True)', 'initial_state', '=', 'model_encoder.predict(input_tokens)', 'max_tokens', '=', 'tokenizer_dest.max_tokens', 'shape', '=', '(1,', 'max_tokens)', 'decoder_in... | 709,207 |
2arian3/Artificial-Intelligence | search.py | uniformCostSearch | uniformCostSearch | Search the node of least total cost first. | [
"Search",
"the",
"node",
"of",
"least",
"total",
"cost",
"first."
] | def uniformCostSearch(problem):
from util import PriorityQueue
pq = PriorityQueue()
visited = set()
path = []
node = problem.getStartState()
pq.push([node, path], problem.getCostOfActions(path))
while True:
if pq.isEmpty():
return []
(node, path) = pq.pop()
... | ['def', 'uniformCostSearch(problem):', 'from', 'util', 'import', 'PriorityQueue', 'pq', '=', 'PriorityQueue()', 'visited', '=', 'set()', 'path', '=', '[]', 'node', '=', 'problem.getStartState()', 'pq.push([node,', 'path],', 'problem.getCostOfActions(path))', 'while', 'True:', 'if', 'pq.isEmpty():', 'return', '[]', '(no... | 113,674 |
neokarn/computer_vision | config_util_test.py | ConfigUtilTest.testRMSPropWithNewLearingRate | testRMSPropWithNewLearingRate | Tests new learning rates for RMSProp Optimizer. | [
"Tests",
"new",
"learning",
"rates",
"for",
"RMSProp",
"Optimizer."
] | def testRMSPropWithNewLearingRate(self):
self._assertOptimizerWithNewLearningRate('rms_prop_optimizer') | ['def', 'testRMSPropWithNewLearingRate(self):', "self._assertOptimizerWithNewLearningRate('rms_prop_optimizer')"] | 512,195 |
wandb/wandb | timed_input.py | timed_input | timed_input | Behaves like builtin `input()` but adds timeout. | [
"Behaves",
"like",
"builtin",
"`input()`",
"but",
"adds",
"timeout."
] | def timed_input(prompt: str, timeout: float, show_timeout: bool=True, jupyter: bool=False) -> str:
if show_timeout:
prompt = f'{prompt}({timeout:.0f} second timeout) '
if jupyter:
return _jupyter_timed_input(prompt=prompt, timeout=timeout)
return _timed_input(prompt=prompt, timeout=timeout) | ['def', 'timed_input(prompt:', 'str,', 'timeout:', 'float,', 'show_timeout:', 'bool=True,', 'jupyter:', 'bool=False)', '->', 'str:', 'if', 'show_timeout:', 'prompt', '=', "f'{prompt}({timeout:.0f}", 'second', 'timeout)', "'", 'if', 'jupyter:', 'return', '_jupyter_timed_input(prompt=prompt,', 'timeout=timeout)', 'return... | 941,923 |
Kvatsx/Artificial-Intelligence-Assignments | ltisys.py | TransferFunction.den | den | Denominator of the `TransferFunction` system. | [
"Denominator",
"of",
"the",
"`TransferFunction`",
"system."
] | def den(self):
return self._den | ['def', 'den(self):', 'return', 'self._den'] | 77,862 |
ramkiranvenkat/Natural-Language-Processing | api.py | SupervisedLoadFile.classify_candidates | classify_candidates | Classify the candidates as keyphrase or not keyphrase. | [
"Classify",
"the",
"candidates",
"as",
"keyphrase",
"or",
"not",
"keyphrase."
] | def classify_candidates(self, model=None):
if model is None:
instance = self.__class__.__name__
if six.PY2:
model = os.path.join(self._models, instance + '-semeval2010.py2.pickle')
else:
model = os.path.join(self._models, instance + '-semeval2010.py3.pickle')
clf ... | ['def', 'classify_candidates(self,', 'model=None):', 'if', 'model', 'is', 'None:', 'instance', '=', 'self.__class__.__name__', 'if', 'six.PY2:', 'model', '=', 'os.path.join(self._models,', 'instance', '+', "'-semeval2010.py2.pickle')", 'else:', 'model', '=', 'os.path.join(self._models,', 'instance', '+', "'-semeval2010... | 658,237 |
amartya-k/vision | common_extended_utils.py | quant_conv_flop | quant_conv_flop | Count flops for quantized convolution. | [
"Count",
"flops",
"for",
"quantized",
"convolution."
] | def quant_conv_flop(inputs: List[Any], outputs: List[Any]):
(x, w) = inputs[:2]
(x_shape, w_shape, out_shape) = (get_shape(x), get_shape(w), get_shape(outputs[0]))
return conv_flop_count(x_shape, w_shape, out_shape, transposed=False) | ['def', 'quant_conv_flop(inputs:', 'List[Any],', 'outputs:', 'List[Any]):', '(x,', 'w)', '=', 'inputs[:2]', '(x_shape,', 'w_shape,', 'out_shape)', '=', '(get_shape(x),', 'get_shape(w),', 'get_shape(outputs[0]))', 'return', 'conv_flop_count(x_shape,', 'w_shape,', 'out_shape,', 'transposed=False)'] | 957,827 |
jwwangchn/NWD | cascade_roi_head.py | CascadeRoIHead.init_bbox_head | init_bbox_head | Initialize box head and box roi extractor. | [
"Initialize",
"box",
"head",
"and",
"box",
"roi",
"extractor."
] | def init_bbox_head(self, bbox_roi_extractor, bbox_head):
self.bbox_roi_extractor = ModuleList()
self.bbox_head = ModuleList()
if not isinstance(bbox_roi_extractor, list):
bbox_roi_extractor = [bbox_roi_extractor for _ in range(self.num_stages)]
if not isinstance(bbox_head, list):
bbox_he... | ['def', 'init_bbox_head(self,', 'bbox_roi_extractor,', 'bbox_head):', 'self.bbox_roi_extractor', '=', 'ModuleList()', 'self.bbox_head', '=', 'ModuleList()', 'if', 'not', 'isinstance(bbox_roi_extractor,', 'list):', 'bbox_roi_extractor', '=', '[bbox_roi_extractor', 'for', '_', 'in', 'range(self.num_stages)]', 'if', 'not'... | 724,984 |
Kvatsx/Artificial-Intelligence-Assignments | pyparsing.py | ParseResults.haskeys | haskeys | Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names. | [
"Since",
"keys()",
"returns",
"an",
"iterator,",
"this",
"method",
"is",
"helpful",
"in",
"bypassing",
"code",
"that",
"looks",
"for",
"the",
"existence",
"of",
"any",
"defined",
"results",
"names."
] | def haskeys(self):
return bool(self.__tokdict) | ['def', 'haskeys(self):', 'return', 'bool(self.__tokdict)'] | 75,432 |
openvinotoolkit/training_extensions | summarize_test_results.py | summarize_non_anomaly_data | summarize_non_anomaly_data | Make DataFrame by gathering all results. | [
"Make",
"DataFrame",
"by",
"gathering",
"all",
"results."
] | def summarize_non_anomaly_data(task: str, task_key: str, json_data: dict, result_data: dict) -> dict:
for label_type in LABEL_TYPES:
for train_type in TRAIN_TYPES:
task_data = json_data[task_key][label_type][train_type]
train_data = task_data.get('train')
if train_data is... | ['def', 'summarize_non_anomaly_data(task:', 'str,', 'task_key:', 'str,', 'json_data:', 'dict,', 'result_data:', 'dict)', '->', 'dict:', 'for', 'label_type', 'in', 'LABEL_TYPES:', 'for', 'train_type', 'in', 'TRAIN_TYPES:', 'task_data', '=', 'json_data[task_key][label_type][train_type]', 'train_data', '=', "task_data.get... | 919,188 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | axis.py | XAxis.contains | contains | Test whether the mouse event occurred in the x axis. | [
"Test",
"whether",
"the",
"mouse",
"event",
"occurred",
"in",
"the",
"x",
"axis."
] | def contains(self, mouseevent):
(inside, info) = self._default_contains(mouseevent)
if inside is not None:
return (inside, info)
(x, y) = (mouseevent.x, mouseevent.y)
try:
trans = self.axes.transAxes.inverted()
(xaxes, yaxes) = trans.transform((x, y))
except ValueError:
... | ['def', 'contains(self,', 'mouseevent):', '(inside,', 'info)', '=', 'self._default_contains(mouseevent)', 'if', 'inside', 'is', 'not', 'None:', 'return', '(inside,', 'info)', '(x,', 'y)', '=', '(mouseevent.x,', 'mouseevent.y)', 'try:', 'trans', '=', 'self.axes.transAxes.inverted()', '(xaxes,', 'yaxes)', '=', 'trans.tra... | 450,074 |
prof-fabriciogmc/artificial_intelligence | models.py | PreparedRequest.prepare_headers | prepare_headers | Prepares the given HTTP headers. | [
"Prepares",
"the",
"given",
"HTTP",
"headers."
] | def prepare_headers(self, headers):
self.headers = CaseInsensitiveDict()
if headers:
for header in headers.items():
check_header_validity(header)
(name, value) = header
self.headers[to_native_string(name)] = value | ['def', 'prepare_headers(self,', 'headers):', 'self.headers', '=', 'CaseInsensitiveDict()', 'if', 'headers:', 'for', 'header', 'in', 'headers.items():', 'check_header_validity(header)', '(name,', 'value)', '=', 'header', 'self.headers[to_native_string(name)]', '=', 'value'] | 145,473 |
yuantn/MI-AOD | structures.py | polygon_to_bitmap | polygon_to_bitmap | Convert masks from the form of polygons to bitmaps. | [
"Convert",
"masks",
"from",
"the",
"form",
"of",
"polygons",
"to",
"bitmaps."
] | def polygon_to_bitmap(polygons, height, width):
rles = maskUtils.frPyObjects(polygons, height, width)
rle = maskUtils.merge(rles)
bitmap_mask = maskUtils.decode(rle).astype(np.bool)
return bitmap_mask | ['def', 'polygon_to_bitmap(polygons,', 'height,', 'width):', 'rles', '=', 'maskUtils.frPyObjects(polygons,', 'height,', 'width)', 'rle', '=', 'maskUtils.merge(rles)', 'bitmap_mask', '=', 'maskUtils.decode(rle).astype(np.bool)', 'return', 'bitmap_mask'] | 635,054 |
XinyuSun/MME | video.py | random_crop | random_crop | Perform random spatial crop on the given images and corresponding boxes. | [
"Perform",
"random",
"spatial",
"crop",
"on",
"the",
"given",
"images",
"and",
"corresponding",
"boxes."
] | def random_crop(images, size, boxes=None):
if images.shape[2] == size and images.shape[3] == size:
return images
height = images.shape[2]
width = images.shape[3]
y_offset = 0
if height > size:
y_offset = int(np.random.randint(0, height - size))
x_offset = 0
if width > size:
... | ['def', 'random_crop(images,', 'size,', 'boxes=None):', 'if', 'images.shape[2]', '==', 'size', 'and', 'images.shape[3]', '==', 'size:', 'return', 'images', 'height', '=', 'images.shape[2]', 'width', '=', 'images.shape[3]', 'y_offset', '=', '0', 'if', 'height', '>', 'size:', 'y_offset', '=', 'int(np.random.randint(0,', ... | 240,268 |
cheind/gcsl | robot_env_test.py | RobotEnvTest.test_get_obs_subset | test_get_obs_subset | Tests `_get_obs` flattening a subset of keys. | [
"Tests",
"`_get_obs`",
"flattening",
"a",
"subset",
"of",
"keys."
] | def test_get_obs_subset(self):
test = TestEnv(observation_keys=['b', 'd'])
test.get_obs_dict = mock.Mock(return_value={'a': [0], 'b': [1, 2], 'c': [3, 4], 'd': [5]})
np.testing.assert_array_equal(test._get_obs(), [1, 2, 5]) | ['def', 'test_get_obs_subset(self):', 'test', '=', "TestEnv(observation_keys=['b',", "'d'])", 'test.get_obs_dict', '=', "mock.Mock(return_value={'a':", '[0],', "'b':", '[1,', '2],', "'c':", '[3,', '4],', "'d':", '[5]})', 'np.testing.assert_array_equal(test._get_obs(),', '[1,', '2,', '5])'] | 201,646 |
shaoshengsong/quarkdet | efficientnet.py | BlockDecoder.encode | encode | Encode a list of BlockArgs to a list of strings. | [
"Encode",
"a",
"list",
"of",
"BlockArgs",
"to",
"a",
"list",
"of",
"strings."
] | def encode(blocks_args):
block_strings = []
for block in blocks_args:
block_strings.append(BlockDecoder._encode_block_string(block))
return block_strings | ['def', 'encode(blocks_args):', 'block_strings', '=', '[]', 'for', 'block', 'in', 'blocks_args:', 'block_strings.append(BlockDecoder._encode_block_string(block))', 'return', 'block_strings'] | 835,567 |
pytorch/rl | writers.py | Writer.extend | extend | Inserts a series of data points at appropriate indices, and returns a tensor containing the indices. | [
"Inserts",
"a",
"series",
"of",
"data",
"points",
"at",
"appropriate",
"indices,",
"and",
"returns",
"a",
"tensor",
"containing",
"the",
"indices."
] | def extend(self, data: Sequence) -> torch.Tensor:
... | ['def', 'extend(self,', 'data:', 'Sequence)', '->', 'torch.Tensor:', '...'] | 858,815 |
neokarn/computer_vision | tf_record_creation_util.py | open_sharded_output_tfrecords | open_sharded_output_tfrecords | Opens all TFRecord shards for writing and adds them to an exit stack. | [
"Opens",
"all",
"TFRecord",
"shards",
"for",
"writing",
"and",
"adds",
"them",
"to",
"an",
"exit",
"stack."
] | def open_sharded_output_tfrecords(exit_stack, base_path, num_shards):
tf_record_output_filenames = ['{}-{:05d}-of-{:05d}'.format(base_path, idx, num_shards) for idx in range(num_shards)]
tfrecords = [exit_stack.enter_context(tf.python_io.TFRecordWriter(file_name)) for file_name in tf_record_output_filenames]
... | ['def', 'open_sharded_output_tfrecords(exit_stack,', 'base_path,', 'num_shards):', 'tf_record_output_filenames', '=', "['{}-{:05d}-of-{:05d}'.format(base_path,", 'idx,', 'num_shards)', 'for', 'idx', 'in', 'range(num_shards)]', 'tfrecords', '=', '[exit_stack.enter_context(tf.python_io.TFRecordWriter(file_name))', 'for',... | 506,032 |
deep-learning-indaba/Baobab | tests.py | RegistrationTest.test_offer_with_tag_not_accepted | test_offer_with_tag_not_accepted | Test that an offer with an unaccepted tag sees the correct sections. | [
"Test",
"that",
"an",
"offer",
"with",
"an",
"unaccepted",
"tag",
"sees",
"the",
"correct",
"sections."
] | def test_offer_with_tag_not_accepted(self):
self._seed_static_data()
db.session.query(OfferTag).filter(OfferTag.id == self.offer_tag_id).update({'accepted': False})
db.session.commit()
params = {'offer_id': self.offer_with_tag_id, 'event_id': self.event_id}
response = self.app.get('/api/v1/registrat... | ['def', 'test_offer_with_tag_not_accepted(self):', 'self._seed_static_data()', 'db.session.query(OfferTag).filter(OfferTag.id', '==', "self.offer_tag_id).update({'accepted':", 'False})', 'db.session.commit()', 'params', '=', "{'offer_id':", 'self.offer_with_tag_id,', "'event_id':", 'self.event_id}', 'response', '=', "s... | 94,185 |
PacktPublishing/Hands-On-Artificial--for-Banking | utils.py | LazyFile.close | close | Closes the underlying file, no matter what. | [
"Closes",
"the",
"underlying",
"file,",
"no",
"matter",
"what."
] | def close(self):
if self._f is not None:
self._f.close() | ['def', 'close(self):', 'if', 'self._f', 'is', 'not', 'None:', 'self._f.close()'] | 234,807 |
Minakshee25/Natural-Language-Processing | utils.py | load_document_as_bos | load_document_as_bos | Load a document as a bag of words/stems/lemmas. | [
"Load",
"a",
"document",
"as",
"a",
"bag",
"of",
"words/stems/lemmas."
] | def load_document_as_bos(input_file, language='en', normalization='stemming', stoplist=None, encoding=None):
if stoplist is None:
stoplist = []
doc = LoadFile()
doc.load_document(input=input_file, language=language, normalization=normalization, encoding=encoding)
vector = defaultdict(int)
fo... | ['def', 'load_document_as_bos(input_file,', "language='en',", "normalization='stemming',", 'stoplist=None,', 'encoding=None):', 'if', 'stoplist', 'is', 'None:', 'stoplist', '=', '[]', 'doc', '=', 'LoadFile()', 'doc.load_document(input=input_file,', 'language=language,', 'normalization=normalization,', 'encoding=encodin... | 638,577 |
SajalGoel/Natural-Language-Processing | collabrank.py | CollabRank.candidate_weighting | candidate_weighting | Candidate ranking using random walk. | [
"Candidate",
"ranking",
"using",
"random",
"walk."
] | def candidate_weighting(self, window=10, pos=None, collab_documents=None, normalized=False):
if pos is None:
pos = {'NOUN', 'PROPN', 'ADJ'}
if collab_documents is None:
collab_documents = []
logging.warning('No cluster documents provided for CollabRank.')
self.build_word_graph(window... | ['def', 'candidate_weighting(self,', 'window=10,', 'pos=None,', 'collab_documents=None,', 'normalized=False):', 'if', 'pos', 'is', 'None:', 'pos', '=', "{'NOUN',", "'PROPN',", "'ADJ'}", 'if', 'collab_documents', 'is', 'None:', 'collab_documents', '=', '[]', "logging.warning('No", 'cluster', 'documents', 'provided', 'fo... | 659,720 |
jdogcoderarchives/AI | heuristic_search.py | Grid.get_successor_states | get_successor_states | Computes and returns the list of successor states. | [
"Computes",
"and",
"returns",
"the",
"list",
"of",
"successor",
"states."
] | def get_successor_states(self, state):
result = []
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0 or i * j != 0:
continue
succ = State(self, state.x + i, state.y + j, set(state.coins_collected))
if self.is_within_boundaries(succ.x, ... | ['def', 'get_successor_states(self,', 'state):', 'result', '=', '[]', 'for', 'i', 'in', 'range(-1,', '2):', 'for', 'j', 'in', 'range(-1,', '2):', 'if', 'i', '==', '0', 'and', 'j', '==', '0', 'or', 'i', '*', 'j', '!=', '0:', 'continue', 'succ', '=', 'State(self,', 'state.x', '+', 'i,', 'state.y', '+', 'j,', 'set(state.c... | 69,835 |
PBarde/NaturalLanguageProcessing | modeling.py | layer_norm | layer_norm | Run layer normalization on the last dimension of the tensor. | [
"Run",
"layer",
"normalization",
"on",
"the",
"last",
"dimension",
"of",
"the",
"tensor."
] | def layer_norm(input_tensor, name=None):
return tf.contrib.layers.layer_norm(inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name) | ['def', 'layer_norm(input_tensor,', 'name=None):', 'return', 'tf.contrib.layers.layer_norm(inputs=input_tensor,', 'begin_norm_axis=-1,', 'begin_params_axis=-1,', 'scope=name)'] | 711,269 |
deepmind/dm_control | cartpole.py | Physics.pole_angle_cosine | pole_angle_cosine | Returns the cosine of the pole angle. | [
"Returns",
"the",
"cosine",
"of",
"the",
"pole",
"angle."
] | def pole_angle_cosine(self):
return self.named.data.xmat[2:, 'zz'] | ['def', 'pole_angle_cosine(self):', 'return', 'self.named.data.xmat[2:,', "'zz']"] | 166,293 |
Ruturaj123/Flowchart-Detection | fully_connected_reader.py | run_training | run_training | Train MNIST for a number of steps. | [
"Train",
"MNIST",
"for",
"a",
"number",
"of",
"steps."
] | def run_training():
with tf.Graph().as_default():
(images, labels) = inputs(train=True, batch_size=FLAGS.batch_size, num_epochs=FLAGS.num_epochs)
logits = mnist.inference(images, FLAGS.hidden1, FLAGS.hidden2)
loss = mnist.loss(logits, labels)
train_op = mnist.training(loss, FLAGS.lea... | ['def', 'run_training():', 'with', 'tf.Graph().as_default():', '(images,', 'labels)', '=', 'inputs(train=True,', 'batch_size=FLAGS.batch_size,', 'num_epochs=FLAGS.num_epochs)', 'logits', '=', 'mnist.inference(images,', 'FLAGS.hidden1,', 'FLAGS.hidden2)', 'loss', '=', 'mnist.loss(logits,', 'labels)', 'train_op', '=', 'm... | 604,855 |
FortiLeiZhang/model_zoo | inception_resnet_v1.py | block8 | block8 | Builds the 8x8 resnet block. | [
"Builds",
"the",
"8x8",
"resnet",
"block."
] | def block8(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
with tf.variable_scope(scope, 'Block8', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
tower_c... | ['def', 'block8(net,', 'scale=1.0,', 'activation_fn=tf.nn.relu,', 'scope=None,', 'reuse=None):', 'with', 'tf.variable_scope(scope,', "'Block8',", '[net],', 'reuse=reuse):', 'with', "tf.variable_scope('Branch_0'):", 'tower_conv', '=', 'slim.conv2d(net,', '192,', '1,', "scope='Conv2d_1x1')", 'with', "tf.variable_scope('B... | 653,458 |
rudranil723/mini-main | figure.py | Figure.get_figheight | get_figheight | Return the figure height in inches. | [
"Return",
"the",
"figure",
"height",
"in",
"inches."
] | def get_figheight(self):
return self.bbox_inches.height | ['def', 'get_figheight(self):', 'return', 'self.bbox_inches.height'] | 319,411 |
f-dangel/cockpit | alpha.py | Alpha.is_end | is_end | Return whether current iteration is end point. | [
"Return",
"whether",
"current",
"iteration",
"is",
"end",
"point."
] | def is_end(self, global_step):
return self._track_schedule(global_step - self.SAVE_SHIFT) | ['def', 'is_end(self,', 'global_step):', 'return', 'self._track_schedule(global_step', '-', 'self.SAVE_SHIFT)'] | 492,564 |
sunishsheth2009/ChatterBot | certs.py | where | where | Return the preferred certificate bundle. | [
"Return",
"the",
"preferred",
"certificate",
"bundle."
] | def where():
return os.path.join(os.path.dirname(__file__), 'cacert.pem') | ['def', 'where():', 'return', 'os.path.join(os.path.dirname(__file__),', "'cacert.pem')"] | 533,855 |
ludwig-ai/ludwig | time_utils.py | Timer.tic | tic | Like Matlab tic/toc for wall time and processor time. | [
"Like",
"Matlab",
"tic/toc",
"for",
"wall",
"time",
"and",
"processor",
"time."
] | def tic(self):
self.reset() | ['def', 'tic(self):', 'self.reset()'] | 617,165 |
arshpreetsingh/quantopian-machinelearning | iostream.py | _StreamBuffer.advance | advance | Advance the current buffer position by ``size`` bytes. | [
"Advance",
"the",
"current",
"buffer",
"position",
"by",
"``size``",
"bytes."
] | def advance(self, size: int) -> None:
assert 0 < size <= self._size
self._size -= size
pos = self._first_pos
buffers = self._buffers
while buffers and size > 0:
(is_large, b) = buffers[0]
b_remain = len(b) - size - pos
if b_remain <= 0:
buffers.popleft()
... | ['def', 'advance(self,', 'size:', 'int)', '->', 'None:', 'assert', '0', '<', 'size', '<=', 'self._size', 'self._size', '-=', 'size', 'pos', '=', 'self._first_pos', 'buffers', '=', 'self._buffers', 'while', 'buffers', 'and', 'size', '>', '0:', '(is_large,', 'b)', '=', 'buffers[0]', 'b_remain', '=', 'len(b)', '-', 'size'... | 893,493 |
cheng052/BRNet | open3d_vis.py | show_pts_boxes | show_pts_boxes | Draw bbox and points on visualizer. | [
"Draw",
"bbox",
"and",
"points",
"on",
"visualizer."
] | def show_pts_boxes(points, bbox3d=None, show=True, save_path=None, points_size=2, point_color=(0.5, 0.5, 0.5), bbox_color=(0, 1, 0), points_in_box_color=(1, 0, 0), rot_axis=2, center_mode='lidar_bottom', mode='xyz'):
assert 0 <= rot_axis <= 2
vis = o3d.visualization.Visualizer()
vis.create_window()
mesh... | ['def', 'show_pts_boxes(points,', 'bbox3d=None,', 'show=True,', 'save_path=None,', 'points_size=2,', 'point_color=(0.5,', '0.5,', '0.5),', 'bbox_color=(0,', '1,', '0),', 'points_in_box_color=(1,', '0,', '0),', 'rot_axis=2,', "center_mode='lidar_bottom',", "mode='xyz'):", 'assert', '0', '<=', 'rot_axis', '<=', '2', 'vis... | 409,780 |
mikhaildubov/AST-text-analysis | easa.py | EnhancedAnnotatedSuffixArray.traverse_breadth_first | traverse_breadth_first | Visits the internal "nodes" of the enhanced suffix array in breadth-first order. | [
"Visits",
"the",
"internal",
"\"nodes\"",
"of",
"the",
"enhanced",
"suffix",
"array",
"in",
"breadth-first",
"order."
] | def traverse_breadth_first(self, callback):
raise NotImplementedError | ['def', 'traverse_breadth_first(self,', 'callback):', 'raise', 'NotImplementedError'] | 402,546 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | base.py | LocalTree.colorText | colorText | Returns a colorized string from the given token type and text. | [
"Returns",
"a",
"colorized",
"string",
"from",
"the",
"given",
"token",
"type",
"and",
"text."
] | def colorText(self, tokenType, tokenText):
return self.colorTypeMap.get(tokenType, colors.white)(tokenText) | ['def', 'colorText(self,', 'tokenType,', 'tokenText):', 'return', 'self.colorTypeMap.get(tokenType,', 'colors.white)(tokenText)'] | 11,341 |
jesolem/PCV | hcluster.py | ClusterNode.extract_clusters | extract_clusters | Extract list of sub-tree clusters from hcluster tree with distance<dist. | [
"Extract",
"list",
"of",
"sub-tree",
"clusters",
"from",
"hcluster",
"tree",
"with",
"distance<dist."
] | def extract_clusters(self, dist):
if self.distance < dist:
return [self]
return self.left.extract_clusters(dist) + self.right.extract_clusters(dist) | ['def', 'extract_clusters(self,', 'dist):', 'if', 'self.distance', '<', 'dist:', 'return', '[self]', 'return', 'self.left.extract_clusters(dist)', '+', 'self.right.extract_clusters(dist)'] | 765,670 |
95616ARG/PRDNN | test_ddnn.py | test_serialization | test_serialization | Tests that it correctly (de)serializes. | [
"Tests",
"that",
"it",
"correctly",
"(de)serializes."
] | def test_serialization():
activation_layers = [FullyConnectedLayer(np.eye(2), np.ones(shape=(2,))), ReluLayer(), FullyConnectedLayer(2.0 * np.eye(2), np.zeros(shape=(2,))), ReluLayer()]
value_layers = activation_layers[:2] + [FullyConnectedLayer(3.0 * np.eye(2), np.zeros(shape=(2,))), ReluLayer()]
network =... | ['def', 'test_serialization():', 'activation_layers', '=', '[FullyConnectedLayer(np.eye(2),', 'np.ones(shape=(2,))),', 'ReluLayer(),', 'FullyConnectedLayer(2.0', '*', 'np.eye(2),', 'np.zeros(shape=(2,))),', 'ReluLayer()]', 'value_layers', '=', 'activation_layers[:2]', '+', '[FullyConnectedLayer(3.0', '*', 'np.eye(2),',... | 822,215 |
shengchen-liu/Computer-Vision | label_map_util.py | create_category_index | create_category_index | Creates dictionary of COCO compatible categories keyed by category id. | [
"Creates",
"dictionary",
"of",
"COCO",
"compatible",
"categories",
"keyed",
"by",
"category",
"id."
] | def create_category_index(categories):
category_index = {}
for cat in categories:
category_index[cat['id']] = cat
return category_index | ['def', 'create_category_index(categories):', 'category_index', '=', '{}', 'for', 'cat', 'in', 'categories:', "category_index[cat['id']]", '=', 'cat', 'return', 'category_index'] | 458,471 |
43Carrig/recurrent_neural_networks_practice | script_ops.py | FuncRegistry.insert | insert | Registers `func` and returns a unique token for this entry. | [
"Registers",
"`func`",
"and",
"returns",
"a",
"unique",
"token",
"for",
"this",
"entry."
] | def insert(self, func):
token = self._next_unique_token()
self._funcs[token] = func
return token | ['def', 'insert(self,', 'func):', 'token', '=', 'self._next_unique_token()', 'self._funcs[token]', '=', 'func', 'return', 'token'] | 338,949 |
EducationalTestingService/skll | test_custom_metrics.py | TestCustomMetrics.test_reregister_same_metric_same_session | test_reregister_same_metric_same_session | Test loading custom metric again in same session. | [
"Test",
"loading",
"custom",
"metric",
"again",
"in",
"same",
"session."
] | def test_reregister_same_metric_same_session(self):
custom_metrics_file = other_dir / 'custom_metrics.py'
register_custom_metric(custom_metrics_file, 'f075_macro')
with self.assertRaises(NameError):
register_custom_metric(custom_metrics_file, 'f075_macro') | ['def', 'test_reregister_same_metric_same_session(self):', 'custom_metrics_file', '=', 'other_dir', '/', "'custom_metrics.py'", 'register_custom_metric(custom_metrics_file,', "'f075_macro')", 'with', 'self.assertRaises(NameError):', 'register_custom_metric(custom_metrics_file,', "'f075_macro')"] | 885,086 |
QData/deepWordBug | math2html.py | Link.setmutualdestination | setmutualdestination | Set another link as destination, and set its destination to this one. | [
"Set",
"another",
"link",
"as",
"destination,",
"and",
"set",
"its",
"destination",
"to",
"this",
"one."
] | def setmutualdestination(self, destination):
self.destination = destination
destination.destination = self | ['def', 'setmutualdestination(self,', 'destination):', 'self.destination', '=', 'destination', 'destination.destination', '=', 'self'] | 542,551 |
dawdleryang/object_detection | shape_utils.py | assert_box_normalized | assert_box_normalized | Asserts the input box tensor is normalized. | [
"Asserts",
"the",
"input",
"box",
"tensor",
"is",
"normalized."
] | def assert_box_normalized(boxes, maximum_normalized_coordinate=1.1):
box_minimum = tf.reduce_min(boxes)
box_maximum = tf.reduce_max(boxes)
return tf.Assert(tf.logical_and(tf.less_equal(box_maximum, maximum_normalized_coordinate), tf.greater_equal(box_minimum, 0)), [boxes]) | ['def', 'assert_box_normalized(boxes,', 'maximum_normalized_coordinate=1.1):', 'box_minimum', '=', 'tf.reduce_min(boxes)', 'box_maximum', '=', 'tf.reduce_max(boxes)', 'return', 'tf.Assert(tf.logical_and(tf.less_equal(box_maximum,', 'maximum_normalized_coordinate),', 'tf.greater_equal(box_minimum,', '0)),', '[boxes])'] | 793,832 |
TuSimple/centerformer | misc.py | get_paddings_indicator | get_paddings_indicator | Create boolean mask by actually number of a padded tensor. | [
"Create",
"boolean",
"mask",
"by",
"actually",
"number",
"of",
"a",
"padded",
"tensor."
] | def get_paddings_indicator(actual_num, max_num, axis=0):
actual_num = torch.unsqueeze(actual_num, axis + 1)
max_num_shape = [1] * len(actual_num.shape)
max_num_shape[axis + 1] = -1
max_num = torch.arange(max_num, dtype=torch.int, device=actual_num.device).view(max_num_shape)
paddings_indicator = act... | ['def', 'get_paddings_indicator(actual_num,', 'max_num,', 'axis=0):', 'actual_num', '=', 'torch.unsqueeze(actual_num,', 'axis', '+', '1)', 'max_num_shape', '=', '[1]', '*', 'len(actual_num.shape)', 'max_num_shape[axis', '+', '1]', '=', '-1', 'max_num', '=', 'torch.arange(max_num,', 'dtype=torch.int,', 'device=actual_nu... | 457,499 |
chenbinghui1/DSL | test_gfl_head.py | test_gfl_head_loss | test_gfl_head_loss | Tests gfl head loss when truth is empty and non-empty. | [
"Tests",
"gfl",
"head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_gfl_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]
train_cfg = mmcv.Config(dict(assigner=dict(type='ATSSAssigner', topk=9), allowed_border=-1, pos_weight=-1, debug=False))
self = GFLHead(num_classes=4, in_channels=1, train_cfg=train_cfg, a... | ['def', 'test_gfl_head_loss():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3)}]', 'train_cfg', '=', "mmcv.Config(dict(assigner=dict(type='ATSSAssigner',", 'topk=9),', 'allowed_border=-1,', 'pos_weight=-1,', 'debug=False))', 'self', '=... | 167,999 |
kaka-lin/object-detection | config_util.py | get_optimizer_type | get_optimizer_type | Returns the optimizer type for training. | [
"Returns",
"the",
"optimizer",
"type",
"for",
"training."
] | def get_optimizer_type(train_config):
return train_config.optimizer.WhichOneof('optimizer') | ['def', 'get_optimizer_type(train_config):', 'return', "train_config.optimizer.WhichOneof('optimizer')"] | 746,931 |
Trusted-AI/AIF360 | reweighing.py | Reweighing.transform | transform | Transform the dataset to a new dataset based on the estimated transformation. | [
"Transform",
"the",
"dataset",
"to",
"a",
"new",
"dataset",
"based",
"on",
"the",
"estimated",
"transformation."
] | def transform(self, dataset):
dataset_transformed = dataset.copy(deepcopy=True)
(_, _, _, _, cond_p_fav, cond_p_unfav, cond_up_fav, cond_up_unfav) = self._obtain_conditionings(dataset)
dataset_transformed.instance_weights[cond_p_fav] *= self.w_p_fav
dataset_transformed.instance_weights[cond_p_unfav] *= ... | ['def', 'transform(self,', 'dataset):', 'dataset_transformed', '=', 'dataset.copy(deepcopy=True)', '(_,', '_,', '_,', '_,', 'cond_p_fav,', 'cond_p_unfav,', 'cond_up_fav,', 'cond_up_unfav)', '=', 'self._obtain_conditionings(dataset)', 'dataset_transformed.instance_weights[cond_p_fav]', '*=', 'self.w_p_fav', 'dataset_tra... | 412,246 |
inseq-team/inseq | gradient_attribution.py | GradientAttributionRegistry.unhook | unhook | Unhook the attribution method by restoring the model's original embeddings. | [
"Unhook",
"the",
"attribution",
"method",
"by",
"restoring",
"the",
"model's",
"original",
"embeddings."
] | def unhook(self, **kwargs):
super().hook(**kwargs)
if self.attribute_batch_ids and (not self.forward_batch_embeds):
self.target_layer = None
else:
self.attribution_model.remove_interpretable_embeddings() | ['def', 'unhook(self,', '**kwargs):', 'super().hook(**kwargs)', 'if', 'self.attribute_batch_ids', 'and', '(not', 'self.forward_batch_embeds):', 'self.target_layer', '=', 'None', 'else:', 'self.attribution_model.remove_interpretable_embeddings()'] | 613,919 |
HCIILAB/DeRPN | cpp_lint.py | _CppLintState.SetCountingStyle | SetCountingStyle | Sets the module's counting options. | [
"Sets",
"the",
"module's",
"counting",
"options."
] | def SetCountingStyle(self, counting_style):
self.counting = counting_style | ['def', 'SetCountingStyle(self,', 'counting_style):', 'self.counting', '=', 'counting_style'] | 184,128 |
tencent-ailab/TriNet | trainer.py | Trainer.get_num_updates | get_num_updates | Get the number of parameters updates. | [
"Get",
"the",
"number",
"of",
"parameters",
"updates."
] | def get_num_updates(self):
return self._num_updates | ['def', 'get_num_updates(self):', 'return', 'self._num_updates'] | 425,050 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | registry.py | display_list_by_prefix | display_list_by_prefix | Creates a help string for names_list grouped by prefix. | [
"Creates",
"a",
"help",
"string",
"for",
"names_list",
"grouped",
"by",
"prefix."
] | def display_list_by_prefix(names_list, starting_spaces=0):
(cur_prefix, result_lines) = (None, [])
space = ' ' * starting_spaces
for name in sorted(names_list):
split = name.split('_', 1)
prefix = split[0]
if cur_prefix != prefix:
result_lines.append(space + prefix + ':')... | ['def', 'display_list_by_prefix(names_list,', 'starting_spaces=0):', '(cur_prefix,', 'result_lines)', '=', '(None,', '[])', 'space', '=', "'", "'", '*', 'starting_spaces', 'for', 'name', 'in', 'sorted(names_list):', 'split', '=', "name.split('_',", '1)', 'prefix', '=', 'split[0]', 'if', 'cur_prefix', '!=', 'prefix:', '... | 966,195 |
microsoft/MASS | utils.py | restore_segmentation | restore_segmentation | Take a file segmented with BPE and restore it to its original segmentation. | [
"Take",
"a",
"file",
"segmented",
"with",
"BPE",
"and",
"restore",
"it",
"to",
"its",
"original",
"segmentation."
] | def restore_segmentation(path):
assert os.path.isfile(path)
restore_cmd = "sed -i -r 's/(@@ )|(@@ ?$)//g' %s"
subprocess.Popen(restore_cmd % path, shell=True).wait() | ['def', 'restore_segmentation(path):', 'assert', 'os.path.isfile(path)', 'restore_cmd', '=', '"sed', '-i', '-r', "'s/(@@", ')|(@@', "?$)//g'", '%s"', 'subprocess.Popen(restore_cmd', '%', 'path,', 'shell=True).wait()'] | 645,996 |
iitis/AutoencoderTestingEnvironment | original.py | Autoencoder.get_params_grid | get_params_grid | Returns parameters designed for this architecture for Grid Search. | [
"Returns",
"parameters",
"designed",
"for",
"this",
"architecture",
"for",
"Grid",
"Search."
] | def get_params_grid(self):
return self.params_grid | ['def', 'get_params_grid(self):', 'return', 'self.params_grid'] | 419,616 |
jfzhuang/IFR | colorspace.py | bgr2gray | bgr2gray | Convert a BGR image to grayscale image. | [
"Convert",
"a",
"BGR",
"image",
"to",
"grayscale",
"image."
] | def bgr2gray(img, keepdim=False):
out_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if keepdim:
out_img = out_img[..., None]
return out_img | ['def', 'bgr2gray(img,', 'keepdim=False):', 'out_img', '=', 'cv2.cvtColor(img,', 'cv2.COLOR_BGR2GRAY)', 'if', 'keepdim:', 'out_img', '=', 'out_img[...,', 'None]', 'return', 'out_img'] | 597,267 |
Kvatsx/Artificial-Intelligence-Assignments | ultratb.py | VerboseTB.structured_traceback | structured_traceback | Return a nice text document describing the traceback. | [
"Return",
"a",
"nice",
"text",
"document",
"describing",
"the",
"traceback."
] | def structured_traceback(self, etype, evalue, etb, tb_offset=None, number_of_lines_of_context=5):
formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, tb_offset)
colors = self.Colors
colorsnormal = colors.Normal
head = '%s%s%s' % (colors.topline, '-' * m... | ['def', 'structured_traceback(self,', 'etype,', 'evalue,', 'etb,', 'tb_offset=None,', 'number_of_lines_of_context=5):', 'formatted_exception', '=', 'self.format_exception_as_a_whole(etype,', 'evalue,', 'etb,', 'number_of_lines_of_context,', 'tb_offset)', 'colors', '=', 'self.Colors', 'colorsnormal', '=', 'colors.Normal... | 38,262 |
gunthercox/ChatterBot | fst.py | BaseCursor.next_arc | next_arc | Moves to the next outgoing arc from the previous node. | [
"Moves",
"to",
"the",
"next",
"outgoing",
"arc",
"from",
"the",
"previous",
"node."
] | def next_arc(self):
raise NotImplementedError | ['def', 'next_arc(self):', 'raise', 'NotImplementedError'] | 526,630 |
Kvatsx/Artificial-Intelligence-Assignments | test.py | test.with_project_on_sys_path | with_project_on_sys_path | Backward compatibility for project_on_sys_path context. | [
"Backward",
"compatibility",
"for",
"project_on_sys_path",
"context."
] | def with_project_on_sys_path(self, func):
with self.project_on_sys_path():
func() | ['def', 'with_project_on_sys_path(self,', 'func):', 'with', 'self.project_on_sys_path():', 'func()'] | 78,383 |
Eric3911/OpenAGI | flamingo_lm.py | FlamingoLayer.is_conditioned | is_conditioned | Check whether the layer is conditioned. | [
"Check",
"whether",
"the",
"layer",
"is",
"conditioned."
] | def is_conditioned(self) -> bool:
return self.vis_x is not None | ['def', 'is_conditioned(self)', '->', 'bool:', 'return', 'self.vis_x', 'is', 'not', 'None'] | 272,117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.