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 |
|---|---|---|---|---|---|---|---|---|
enuguru/artificial_intelligence_and_machine_learning | common.py | get_single_text | get_single_text | Returns the first token from an analyzer's output. | [
"Returns",
"the",
"first",
"token",
"from",
"an",
"analyzer's",
"output."
] | def get_single_text(field, text, **kwargs):
for t in field.process_text(text, mode='query', **kwargs):
return t | ['def', 'get_single_text(field,', 'text,', '**kwargs):', 'for', 't', 'in', 'field.process_text(text,', "mode='query',", '**kwargs):', 'return', 't'] | 162,615 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | ReplaceDialog.py | ReplaceDialog.default_command | default_command | Replace and find next. | [
"Replace",
"and",
"find",
"next."
] | def default_command(self, event=None):
if self.do_find(self.ok):
if self.do_replace():
self.do_find(0) | ['def', 'default_command(self,', 'event=None):', 'if', 'self.do_find(self.ok):', 'if', 'self.do_replace():', 'self.do_find(0)'] | 430,916 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjSolverStatWrapper.nupdate | nupdate | number of Cholesky updates in line search. | [
"number",
"of",
"Cholesky",
"updates",
"in",
"line",
"search."
] | def nupdate(self):
return self._ptr.contents.nupdate | ['def', 'nupdate(self):', 'return', 'self._ptr.contents.nupdate'] | 440,516 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | logic.py | d | d | Differentiate and then simplify. | [
"Differentiate",
"and",
"then",
"simplify."
] | def d(y, x):
return simp(diff(y, x)) | ['def', 'd(y,', 'x):', 'return', 'simp(diff(y,', 'x))'] | 428,071 |
011235813/cm3 | networks.py | fc3 | fc3 | Two hidden layer, one output layer. | [
"Two",
"hidden",
"layer,",
"one",
"output",
"layer."
] | def fc3(t_input, n_hidden1=64, n_hidden2=64, n_outputs=9, nonlinearity1=tf.nn.relu, nonlinearity2=tf.nn.relu, scope='fc3'):
with tf.variable_scope(scope, initializer=tf.initializers.truncated_normal(0, 0.01)):
h1 = tf.layers.dense(inputs=t_input, units=n_hidden1, activation=nonlinearity1, use_bias=True, nam... | ['def', 'fc3(t_input,', 'n_hidden1=64,', 'n_hidden2=64,', 'n_outputs=9,', 'nonlinearity1=tf.nn.relu,', 'nonlinearity2=tf.nn.relu,', "scope='fc3'):", 'with', 'tf.variable_scope(scope,', 'initializer=tf.initializers.truncated_normal(0,', '0.01)):', 'h1', '=', 'tf.layers.dense(inputs=t_input,', 'units=n_hidden1,', 'activa... | 488,600 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | cifarnet.py | cifarnet_arg_scope | cifarnet_arg_scope | Defines the default cifarnet argument scope. | [
"Defines",
"the",
"default",
"cifarnet",
"argument",
"scope."
] | def cifarnet_arg_scope(weight_decay=0.004):
with slim.arg_scope([slim.conv2d], weights_initializer=tf.truncated_normal_initializer(stddev=0.05), activation_fn=tf.nn.relu):
with slim.arg_scope([slim.fully_connected], biases_initializer=tf.constant_initializer(0.1), weights_initializer=trunc_normal(0.04), wei... | ['def', 'cifarnet_arg_scope(weight_decay=0.004):', 'with', 'slim.arg_scope([slim.conv2d],', 'weights_initializer=tf.truncated_normal_initializer(stddev=0.05),', 'activation_fn=tf.nn.relu):', 'with', 'slim.arg_scope([slim.fully_connected],', 'biases_initializer=tf.constant_initializer(0.1),', 'weights_initializer=trunc_... | 109,854 |
calclavia/DeepJ | generate.py | MusicGeneration.end_time | end_time | Finish generation for this time step. | [
"Finish",
"generation",
"for",
"this",
"time",
"step."
] | def end_time(self, t):
if np.count_nonzero(self.next_note) == 0:
self.silent_time += 1
if self.silent_time >= NOTES_PER_BAR:
self.temperature += 0.1
else:
self.silent_time = 0
self.temperature = self.default_temp
self.notes_memory.append(self.next_note)
self.b... | ['def', 'end_time(self,', 't):', 'if', 'np.count_nonzero(self.next_note)', '==', '0:', 'self.silent_time', '+=', '1', 'if', 'self.silent_time', '>=', 'NOTES_PER_BAR:', 'self.temperature', '+=', '0.1', 'else:', 'self.silent_time', '=', '0', 'self.temperature', '=', 'self.default_temp', 'self.notes_memory.append(self.nex... | 521,253 |
suarez12138/AI-Reversi_IMP_TextDichotomy | texmanager.py | TexManager.get_rgba | get_rgba | Return latex's rendering of the tex string as an rgba array. | [
"Return",
"latex's",
"rendering",
"of",
"the",
"tex",
"string",
"as",
"an",
"rgba",
"array."
] | def get_rgba(self, tex, fontsize=None, dpi=None, rgb=(0, 0, 0)):
alpha = self.get_grey(tex, fontsize, dpi)
rgba = np.empty((*alpha.shape, 4))
rgba[..., :3] = mpl.colors.to_rgb(rgb)
rgba[..., -1] = alpha
return rgba | ['def', 'get_rgba(self,', 'tex,', 'fontsize=None,', 'dpi=None,', 'rgb=(0,', '0,', '0)):', 'alpha', '=', 'self.get_grey(tex,', 'fontsize,', 'dpi)', 'rgba', '=', 'np.empty((*alpha.shape,', '4))', 'rgba[...,', ':3]', '=', 'mpl.colors.to_rgb(rgb)', 'rgba[...,', '-1]', '=', 'alpha', 'return', 'rgba'] | 96,776 |
rifqind/Agent-Programs-3KS1 | completer.py | protect_filename | protect_filename | Escape a string to protect certain characters. | [
"Escape",
"a",
"string",
"to",
"protect",
"certain",
"characters."
] | def protect_filename(s, protectables=PROTECTABLES):
if set(s) & set(protectables):
if sys.platform == 'win32':
return '"' + s + '"'
else:
return ''.join(('\\' + c if c in protectables else c for c in s))
else:
return s | ['def', 'protect_filename(s,', 'protectables=PROTECTABLES):', 'if', 'set(s)', '&', 'set(protectables):', 'if', 'sys.platform', '==', "'win32':", 'return', '\'"\'', '+', 's', '+', '\'"\'', 'else:', 'return', "''.join(('\\\\'", '+', 'c', 'if', 'c', 'in', 'protectables', 'else', 'c', 'for', 'c', 'in', 's))', 'else:', 'ret... | 40,901 |
THU-BPM/PairSCL | data_processor.py | Preprocessor.words_to_indices | words_to_indices | Transform the words in a sentence to their corresponding integer indices. | [
"Transform",
"the",
"words",
"in",
"a",
"sentence",
"to",
"their",
"corresponding",
"integer",
"indices."
] | def words_to_indices(self, sentence):
indices = []
if self.bos:
indices.append(self.worddict['_BOS_'])
for word in sentence:
if word in self.worddict:
index = self.worddict[word]
else:
index = self.worddict['_OOV_']
indices.append(index)
if self.eo... | ['def', 'words_to_indices(self,', 'sentence):', 'indices', '=', '[]', 'if', 'self.bos:', "indices.append(self.worddict['_BOS_'])", 'for', 'word', 'in', 'sentence:', 'if', 'word', 'in', 'self.worddict:', 'index', '=', 'self.worddict[word]', 'else:', 'index', '=', "self.worddict['_OOV_']", 'indices.append(index)', 'if', ... | 277,485 |
IceClear/MW-GAN | flow_util.py | flowread | flowread | Read an optical flow map. | [
"Read",
"an",
"optical",
"flow",
"map."
] | def flowread(flow_path, quantize=False, concat_axis=0, *args, **kwargs):
if quantize:
assert concat_axis in [0, 1]
cat_flow = cv2.imread(flow_path, cv2.IMREAD_UNCHANGED)
if cat_flow.ndim != 2:
raise IOError(f'{flow_path} is not a valid quantized flow file, its dimension is {cat_f... | ['def', 'flowread(flow_path,', 'quantize=False,', 'concat_axis=0,', '*args,', '**kwargs):', 'if', 'quantize:', 'assert', 'concat_axis', 'in', '[0,', '1]', 'cat_flow', '=', 'cv2.imread(flow_path,', 'cv2.IMREAD_UNCHANGED)', 'if', 'cat_flow.ndim', '!=', '2:', 'raise', "IOError(f'{flow_path}", 'is', 'not', 'a', 'valid', 'q... | 651,511 |
weimin17/Object-Detection_HelmetDetection | inception_v4.py | inception_v4 | inception_v4 | Creates the Inception V4 model. | [
"Creates",
"the",
"Inception",
"V4",
"model."
] | def inception_v4(inputs, num_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionV4', create_aux_logits=True):
end_points = {}
with tf.variable_scope(scope, 'InceptionV4', [inputs], reuse=reuse) as scope:
with slim.arg_scope([slim.batch_norm, slim.dropout], is_training=is_... | ['def', 'inception_v4(inputs,', 'num_classes=1001,', 'is_training=True,', 'dropout_keep_prob=0.8,', 'reuse=None,', "scope='InceptionV4',", 'create_aux_logits=True):', 'end_points', '=', '{}', 'with', 'tf.variable_scope(scope,', "'InceptionV4',", '[inputs],', 'reuse=reuse)', 'as', 'scope:', 'with', 'slim.arg_scope([slim... | 752,889 |
omarmhaimdat/twitter_nlp_native_swift | utils.py | getaddresses | getaddresses | Return a list of (REALNAME, EMAIL) for each fieldvalue. | [
"Return",
"a",
"list",
"of",
"(REALNAME,",
"EMAIL)",
"for",
"each",
"fieldvalue."
] | def getaddresses(fieldvalues):
all = COMMASPACE.join(fieldvalues)
a = _AddressList(all)
return a.addresslist | ['def', 'getaddresses(fieldvalues):', 'all', '=', 'COMMASPACE.join(fieldvalues)', 'a', '=', '_AddressList(all)', 'return', 'a.addresslist'] | 953,359 |
aws/sagemaker-python-sdk | pipeline.py | Pipeline.start | start | Starts a Pipeline execution in the Workflow service. | [
"Starts",
"a",
"Pipeline",
"execution",
"in",
"the",
"Workflow",
"service."
] | def start(self, parameters: Dict[str, Union[str, bool, int, float]]=None, execution_display_name: str=None, execution_description: str=None, parallelism_config: ParallelismConfiguration=None, selective_execution_config: SelectiveExecutionConfig=None):
if selective_execution_config is not None:
if selective_... | ['def', 'start(self,', 'parameters:', 'Dict[str,', 'Union[str,', 'bool,', 'int,', 'float]]=None,', 'execution_display_name:', 'str=None,', 'execution_description:', 'str=None,', 'parallelism_config:', 'ParallelismConfiguration=None,', 'selective_execution_config:', 'SelectiveExecutionConfig=None):', 'if', 'selective_ex... | 830,637 |
flow-project/flow | util.py | ensure_dir | ensure_dir | Ensure that the directory specified exists, and if not, create it. | [
"Ensure",
"that",
"the",
"directory",
"specified",
"exists,",
"and",
"if",
"not,",
"create",
"it."
] | def ensure_dir(path):
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
return path | ['def', 'ensure_dir(path):', 'try:', 'os.makedirs(path)', 'except', 'OSError', 'as', 'exception:', 'if', 'exception.errno', '!=', 'errno.EEXIST:', 'raise', 'return', 'path'] | 212,098 |
matsu0228/nlp-jp | screen.py | screen.newline | newline | This is an alias for crlf(). | [
"This",
"is",
"an",
"alias",
"for",
"crlf()."
] | def newline(self):
self.crlf() | ['def', 'newline(self):', 'self.crlf()'] | 803,234 |
RunzheYang/MORL | SemanticBeliefTrackingManager.py | SemanticBeliefTrackingManager.restart | restart | Restarts all semantic belief trackers of all domains and resets internal variables. | [
"Restarts",
"all",
"semantic",
"belief",
"trackers",
"of",
"all",
"domains",
"and",
"resets",
"internal",
"variables."
] | def restart(self):
for dstring in self.domainSemiBelieftrackers.keys():
if self.domainSemiBelieftrackers[dstring] is not None:
self.domainSemiBelieftrackers[dstring].restart()
self.constraints = None
self.state = DialogueState()
return | ['def', 'restart(self):', 'for', 'dstring', 'in', 'self.domainSemiBelieftrackers.keys():', 'if', 'self.domainSemiBelieftrackers[dstring]', 'is', 'not', 'None:', 'self.domainSemiBelieftrackers[dstring].restart()', 'self.constraints', '=', 'None', 'self.state', '=', 'DialogueState()', 'return'] | 241,414 |
open-mmlab/mmselfsup | processing.py | check_sequence_input | check_sequence_input | Check if the input is a sequence with the required sizes. | [
"Check",
"if",
"the",
"input",
"is",
"a",
"sequence",
"with",
"the",
"required",
"sizes."
] | def check_sequence_input(x: Sequence, name: str, req_sizes: tuple) -> None:
msg = req_sizes[0] if len(req_sizes) < 2 else ' or '.join([str(s) for s in req_sizes])
if not isinstance(x, Sequence):
raise TypeError('{} should be a sequence of length {}.'.format(name, msg))
if len(x) not in req_sizes:
... | ['def', 'check_sequence_input(x:', 'Sequence,', 'name:', 'str,', 'req_sizes:', 'tuple)', '->', 'None:', 'msg', '=', 'req_sizes[0]', 'if', 'len(req_sizes)', '<', '2', 'else', "'", 'or', "'.join([str(s)", 'for', 's', 'in', 'req_sizes])', 'if', 'not', 'isinstance(x,', 'Sequence):', 'raise', "TypeError('{}", 'should', 'be'... | 240,301 |
matsu0228/nlp-jp | formatters.py | DisplayFormatter.format_types | format_types | Return the format types (MIME types) of the active formatters. | [
"Return",
"the",
"format",
"types",
"(MIME",
"types)",
"of",
"the",
"active",
"formatters."
] | def format_types(self):
return list(self.formatters.keys()) | ['def', 'format_types(self):', 'return', 'list(self.formatters.keys())'] | 786,613 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | unet.py | UNet.initialize | initialize | Initializes the network's layers. | [
"Initializes",
"the",
"network's",
"layers."
] | def initialize(self):
for module in self.modules():
if isinstance(module, nn.Conv2d):
nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
nn.init.constant_(module.bias, 0)
if isinstance(module, nn.BatchNorm2d):
nn.init.constant_(module.weight, 1)
... | ['def', 'initialize(self):', 'for', 'module', 'in', 'self.modules():', 'if', 'isinstance(module,', 'nn.Conv2d):', 'nn.init.kaiming_normal_(module.weight,', "nonlinearity='relu')", 'nn.init.constant_(module.bias,', '0)', 'if', 'isinstance(module,', 'nn.BatchNorm2d):', 'nn.init.constant_(module.weight,', '1)', 'nn.init.c... | 12,017 |
enlite-ai/maze | core_env.py | Cutting2DCoreEnvironment.get_renderer | get_renderer | Cutting 2D renderer module. | [
"Cutting",
"2D",
"renderer",
"module."
] | def get_renderer(self) -> Cutting2DRenderer:
return self.renderer | ['def', 'get_renderer(self)', '->', 'Cutting2DRenderer:', 'return', 'self.renderer'] | 647,693 |
43Carrig/recurrent_neural_networks_practice | gen_dataset_ops.py | multi_device_iterator_init | multi_device_iterator_init | Initializes the multi device iterator with the given dataset. | [
"Initializes",
"the",
"multi",
"device",
"iterator",
"with",
"the",
"given",
"dataset."
] | def multi_device_iterator_init(dataset, multi_device_iterator, max_buffer_size, name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
(_, _, _op) = _op_def_lib._apply_op_helper('MultiDeviceIteratorInit', dataset=dataset, multi_device_iterator=multi_device_iterator, ma... | ['def', 'multi_device_iterator_init(dataset,', 'multi_device_iterator,', 'max_buffer_size,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', '(_,', '_,', '_op)', '=', "_op_def_lib._apply_op_helper('MultiDeviceIteratorInit',", 'dataset=dataset,',... | 312,710 |
irdanish11/Seq2Seq-UrduChatBot | chatbot_model.py | ChatbotModel.train_batch | train_batch | Train the model on one batch, and return the training loss. | [
"Train",
"the",
"model",
"on",
"one",
"batch,",
"and",
"return",
"the",
"training",
"loss."
] | def train_batch(self, inputs, targets, input_sequence_length, target_sequence_length, learning_rate, dropout, global_step, log_summary=True):
if self.mode != tf.contrib.learn.ModeKeys.TRAIN:
raise ValueError('train_batch can only be called when the model is initialized in train mode.')
keep_probability ... | ['def', 'train_batch(self,', 'inputs,', 'targets,', 'input_sequence_length,', 'target_sequence_length,', 'learning_rate,', 'dropout,', 'global_step,', 'log_summary=True):', 'if', 'self.mode', '!=', 'tf.contrib.learn.ModeKeys.TRAIN:', 'raise', "ValueError('train_batch", 'can', 'only', 'be', 'called', 'when', 'the', 'mod... | 876,456 |
trenton3983/Programming_Computer__with_Python | sfm.py | compute_fundamental_normalized | compute_fundamental_normalized | Computes the fundamental matrix from corresponding points (x1,x2 3*n arrays) using the normalized 8 point algorithm. | [
"Computes",
"the",
"fundamental",
"matrix",
"from",
"corresponding",
"points",
"(x1,x2",
"3*n",
"arrays)",
"using",
"the",
"normalized",
"8",
"point",
"algorithm."
] | def compute_fundamental_normalized(x1, x2):
n = x1.shape[1]
if x2.shape[1] != n:
raise ValueError("Number of points don't match.")
x1 = x1 / x1[2]
mean_1 = mean(x1[:2], axis=1)
S1 = sqrt(2) / std(x1[:2])
T1 = array([[S1, 0, -S1 * mean_1[0]], [0, S1, -S1 * mean_1[1]], [0, 0, 1]])
x1 =... | ['def', 'compute_fundamental_normalized(x1,', 'x2):', 'n', '=', 'x1.shape[1]', 'if', 'x2.shape[1]', '!=', 'n:', 'raise', 'ValueError("Number', 'of', 'points', "don't", 'match.")', 'x1', '=', 'x1', '/', 'x1[2]', 'mean_1', '=', 'mean(x1[:2],', 'axis=1)', 'S1', '=', 'sqrt(2)', '/', 'std(x1[:2])', 'T1', '=', 'array([[S1,',... | 817,403 |
arshpreetsingh/quantopian-machinelearning | io.py | Tee.close | close | Close the file and restore the channel. | [
"Close",
"the",
"file",
"and",
"restore",
"the",
"channel."
] | def close(self):
self.flush()
setattr(sys, self.channel, self.ostream)
self.file.close()
self._closed = True | ['def', 'close(self):', 'self.flush()', 'setattr(sys,', 'self.channel,', 'self.ostream)', 'self.file.close()', 'self._closed', '=', 'True'] | 887,057 |
sunishsheth2009/ChatterBot | base.py | Segment.is_deleted | is_deleted | Returns True if the given document number is deleted. | [
"Returns",
"True",
"if",
"the",
"given",
"document",
"number",
"is",
"deleted."
] | def is_deleted(self, docnum):
raise NotImplementedError | ['def', 'is_deleted(self,', 'docnum):', 'raise', 'NotImplementedError'] | 526,652 |
FedML-AI/FedML | checkpoint.py | save_checkpoint | save_checkpoint | Save checkpoint to the disk. | [
"Save",
"checkpoint",
"to",
"the",
"disk."
] | def save_checkpoint(ckpt, is_best, save_dir, model_name=''):
if not osp.exists(save_dir):
os.makedirs(save_dir)
filename = osp.join(save_dir, model_name + '.pt')
torch.save(ckpt, filename)
if is_best:
best_filename = osp.join(save_dir, 'best_ckpt.pt')
shutil.copyfile(filename, be... | ['def', 'save_checkpoint(ckpt,', 'is_best,', 'save_dir,', "model_name=''):", 'if', 'not', 'osp.exists(save_dir):', 'os.makedirs(save_dir)', 'filename', '=', 'osp.join(save_dir,', 'model_name', '+', "'.pt')", 'torch.save(ckpt,', 'filename)', 'if', 'is_best:', 'best_filename', '=', 'osp.join(save_dir,', "'best_ckpt.pt')"... | 545,083 |
Ruturaj123/Flowchart-Detection | jit_test.py | JitLaunchTest.testOneConstOutput | testOneConstOutput | Test consisting of a single constant return value. | [
"Test",
"consisting",
"of",
"a",
"single",
"constant",
"return",
"value."
] | def testOneConstOutput(self):
def OneConstOutput():
return constant_op.constant([-3, 44, 99])
self._compare(OneConstOutput, [], require_kernel_launch=False) | ['def', 'testOneConstOutput(self):', 'def', 'OneConstOutput():', 'return', 'constant_op.constant([-3,', '44,', '99])', 'self._compare(OneConstOutput,', '[],', 'require_kernel_launch=False)'] | 586,768 |
ZhAnGToNG1/transfer_learning_cspt | vfnet_head.py | VFNetHead.get_fcos_targets | get_fcos_targets | Compute FCOS regression and classification targets for points in multiple images. | [
"Compute",
"FCOS",
"regression",
"and",
"classification",
"targets",
"for",
"points",
"in",
"multiple",
"images."
] | def get_fcos_targets(self, points, gt_bboxes_list, gt_labels_list):
(labels, bbox_targets) = FCOSHead.get_targets(self, points, gt_bboxes_list, gt_labels_list)
label_weights = None
bbox_weights = None
return (labels, label_weights, bbox_targets, bbox_weights) | ['def', 'get_fcos_targets(self,', 'points,', 'gt_bboxes_list,', 'gt_labels_list):', '(labels,', 'bbox_targets)', '=', 'FCOSHead.get_targets(self,', 'points,', 'gt_bboxes_list,', 'gt_labels_list)', 'label_weights', '=', 'None', 'bbox_weights', '=', 'None', 'return', '(labels,', 'label_weights,', 'bbox_targets,', 'bbox_w... | 964,090 |
filerock/FileRock-Client | multi_queue.py | MultiQueue.popleft | popleft | Get a message from the left side of any of the selected queues. | [
"Get",
"a",
"message",
"from",
"the",
"left",
"side",
"of",
"any",
"of",
"the",
"selected",
"queues."
] | def popleft(self, queues=['default'], blocking=True):
return self._pop(queues, blocking, lambda queue: queue.popleft()) | ['def', 'popleft(self,', "queues=['default'],", 'blocking=True):', 'return', 'self._pop(queues,', 'blocking,', 'lambda', 'queue:', 'queue.popleft())'] | 210,257 |
zwl-max/road_object_detection | positional_encoding.py | LearnedPositionalEncoding.forward | forward | Forward function for `LearnedPositionalEncoding`. | [
"Forward",
"function",
"for",
"`LearnedPositionalEncoding`."
] | def forward(self, mask):
(h, w) = mask.shape[-2:]
x = torch.arange(w, device=mask.device)
y = torch.arange(h, device=mask.device)
x_embed = self.col_embed(x)
y_embed = self.row_embed(y)
pos = torch.cat((x_embed.unsqueeze(0).repeat(h, 1, 1), y_embed.unsqueeze(1).repeat(1, w, 1)), dim=-1).permute(... | ['def', 'forward(self,', 'mask):', '(h,', 'w)', '=', 'mask.shape[-2:]', 'x', '=', 'torch.arange(w,', 'device=mask.device)', 'y', '=', 'torch.arange(h,', 'device=mask.device)', 'x_embed', '=', 'self.col_embed(x)', 'y_embed', '=', 'self.row_embed(y)', 'pos', '=', 'torch.cat((x_embed.unsqueeze(0).repeat(h,', '1,', '1),', ... | 825,928 |
jxhe/unify-parameter-efficient-tuning | check_repo.py | check_decorator_order | check_decorator_order | Check that in the test file `filename` the slow decorator is always last. | [
"Check",
"that",
"in",
"the",
"test",
"file",
"`filename`",
"the",
"slow",
"decorator",
"is",
"always",
"last."
] | def check_decorator_order(filename):
with open(filename, 'r', encoding='utf-8', newline='\n') as f:
lines = f.readlines()
decorator_before = None
errors = []
for (i, line) in enumerate(lines):
search = _re_decorator.search(line)
if search is not None:
decorator_name =... | ['def', 'check_decorator_order(filename):', 'with', 'open(filename,', "'r',", "encoding='utf-8',", "newline='\\n')", 'as', 'f:', 'lines', '=', 'f.readlines()', 'decorator_before', '=', 'None', 'errors', '=', '[]', 'for', '(i,', 'line)', 'in', 'enumerate(lines):', 'search', '=', '_re_decorator.search(line)', 'if', 'sear... | 949,579 |
sek788432/Waymo-2D-Object-Detection | box_ops.py | compute_diou | compute_diou | Calculates the distance intersection of union between box1 and box2. | [
"Calculates",
"the",
"distance",
"intersection",
"of",
"union",
"between",
"box1",
"and",
"box2."
] | def compute_diou(box1, box2):
with tf.name_scope('diou'):
dist = center_distance(box1[..., 0:2], box2[..., 0:2])
box1 = xcycwh_to_yxyx(box1)
box2 = xcycwh_to_yxyx(box2)
intersect_mins = tf.math.maximum(box1[..., 0:2], box2[..., 0:2])
intersect_maxes = tf.math.minimum(box1[...... | ['def', 'compute_diou(box1,', 'box2):', 'with', "tf.name_scope('diou'):", 'dist', '=', 'center_distance(box1[...,', '0:2],', 'box2[...,', '0:2])', 'box1', '=', 'xcycwh_to_yxyx(box1)', 'box2', '=', 'xcycwh_to_yxyx(box2)', 'intersect_mins', '=', 'tf.math.maximum(box1[...,', '0:2],', 'box2[...,', '0:2])', 'intersect_maxes... | 973,394 |
gunthercox/ChatterBot | test_comparisons.py | LevenshteinDistanceTestCase.test_exact_match_different_capitalization | test_exact_match_different_capitalization | Test that text capitalization is ignored. | [
"Test",
"that",
"text",
"capitalization",
"is",
"ignored."
] | def test_exact_match_different_capitalization(self):
statement = Statement(text='Hi HoW ArE yOu?')
other_statement = Statement(text='hI hOw are YoU?')
value = self.compare(statement, other_statement)
self.assertEqual(value, 1) | ['def', 'test_exact_match_different_capitalization(self):', 'statement', '=', "Statement(text='Hi", 'HoW', 'ArE', "yOu?')", 'other_statement', '=', "Statement(text='hI", 'hOw', 'are', "YoU?')", 'value', '=', 'self.compare(statement,', 'other_statement)', 'self.assertEqual(value,', '1)'] | 485,879 |
aws/sagemaker-python-sdk | client.py | RemoteExecutor.shutdown | shutdown | Prevent more function executions to be submitted to this executor. | [
"Prevent",
"more",
"function",
"executions",
"to",
"be",
"submitted",
"to",
"this",
"executor."
] | def shutdown(self):
with self._state_condition:
self._shutdown = True
self._pending_request_queue.append(None)
self._state_condition.notify_all()
if self._workers is not None:
self._workers.shutdown(wait=True) | ['def', 'shutdown(self):', 'with', 'self._state_condition:', 'self._shutdown', '=', 'True', 'self._pending_request_queue.append(None)', 'self._state_condition.notify_all()', 'if', 'self._workers', 'is', 'not', 'None:', 'self._workers.shutdown(wait=True)'] | 830,502 |
greydanus/mr_london | Image.py | Image.getprojection | getprojection | Get projection to x and y axes :returns: Two sequences, indicating where there are non-zero pixels along the X-axis and the Y-axis, respectively. | [
"Get",
"projection",
"to",
"x",
"and",
"y",
"axes",
":returns:",
"Two",
"sequences,",
"indicating",
"where",
"there",
"are",
"non-zero",
"pixels",
"along",
"the",
"X-axis",
"and",
"the",
"Y-axis,",
"respectively."
] | def getprojection(self):
self.load()
(x, y) = self.im.getprojection()
return ([i8(c) for c in x], [i8(c) for c in y]) | ['def', 'getprojection(self):', 'self.load()', '(x,', 'y)', '=', 'self.im.getprojection()', 'return', '([i8(c)', 'for', 'c', 'in', 'x],', '[i8(c)', 'for', 'c', 'in', 'y])'] | 263,156 |
dibyaghosh/gcsl | stand_test.py | DKittyStandTest.test_gym_make | test_gym_make | Accesses the sim, model, and data properties. | [
"Accesses",
"the",
"sim,",
"model,",
"and",
"data",
"properties."
] | def test_gym_make(self, env_id, env_cls):
env = gym.make(env_id)
self.assertIsInstance(env.unwrapped, env_cls) | ['def', 'test_gym_make(self,', 'env_id,', 'env_cls):', 'env', '=', 'gym.make(env_id)', 'self.assertIsInstance(env.unwrapped,', 'env_cls)'] | 201,933 |
GHOST5454/Natural-Language-Processing | firstphrases.py | FirstPhrases.candidate_weighting | candidate_weighting | Candidate weighting function using position. | [
"Candidate",
"weighting",
"function",
"using",
"position."
] | def candidate_weighting(self):
for k in self.candidates.keys():
self.weights[k] = -min(self.candidates[k].offsets) | ['def', 'candidate_weighting(self):', 'for', 'k', 'in', 'self.candidates.keys():', 'self.weights[k]', '=', '-min(self.candidates[k].offsets)'] | 661,963 |
Wuziyi616/Artificial_Intelligence_Project1 | tangram_element.py | Point.point_is_coincide_point | point_is_coincide_point | If the distance between 2 points is within an error threshold, then we say they coincide with each other. | [
"If",
"the",
"distance",
"between",
"2",
"points",
"is",
"within",
"an",
"error",
"threshold,",
"then",
"we",
"say",
"they",
"coincide",
"with",
"each",
"other."
] | def point_is_coincide_point(self, another_point, threshold):
if utils.get_distance_point_to_point(self, another_point) < threshold:
return True
return False | ['def', 'point_is_coincide_point(self,', 'another_point,', 'threshold):', 'if', 'utils.get_distance_point_to_point(self,', 'another_point)', '<', 'threshold:', 'return', 'True', 'return', 'False'] | 92,104 |
CAMeL-Lab/camel_tools | normalize.py | normalize_alef_ar | normalize_alef_ar | Normalize various Alef variations to plain a Alef character in an Arabic string. | [
"Normalize",
"various",
"Alef",
"variations",
"to",
"plain",
"a",
"Alef",
"character",
"in",
"an",
"Arabic",
"string."
] | def normalize_alef_ar(s):
return _ALEF_NORMALIZE_AR_RE.sub(u'ا', s) | ['def', 'normalize_alef_ar(s):', 'return', "_ALEF_NORMALIZE_AR_RE.sub(u'ا',", 's)'] | 411,178 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | routing.py | Map.update | update | Called before matching and building to keep the compiled rules in the correct order after things changed. | [
"Called",
"before",
"matching",
"and",
"building",
"to",
"keep",
"the",
"compiled",
"rules",
"in",
"the",
"correct",
"order",
"after",
"things",
"changed."
] | def update(self):
if not self._remap:
return
with self._remap_lock:
if not self._remap:
return
self._rules.sort(key=lambda x: x.match_compare_key())
for rules in itervalues(self._rules_by_endpoint):
rules.sort(key=lambda x: x.build_compare_key())
s... | ['def', 'update(self):', 'if', 'not', 'self._remap:', 'return', 'with', 'self._remap_lock:', 'if', 'not', 'self._remap:', 'return', 'self._rules.sort(key=lambda', 'x:', 'x.match_compare_key())', 'for', 'rules', 'in', 'itervalues(self._rules_by_endpoint):', 'rules.sort(key=lambda', 'x:', 'x.build_compare_key())', 'self.... | 84,903 |
rudranil723/mini-main | woff2.py | WOFF2GlyfTable.reconstruct | reconstruct | Decompile transformed 'glyf' data. | [
"Decompile",
"transformed",
"'glyf'",
"data."
] | def reconstruct(self, data, ttFont):
inputDataSize = len(data)
if inputDataSize < woff2GlyfTableFormatSize:
raise TTLibError("not enough 'glyf' data")
(dummy, data) = sstruct.unpack2(woff2GlyfTableFormat, data, self)
offset = woff2GlyfTableFormatSize
for stream in self.subStreams:
si... | ['def', 'reconstruct(self,', 'data,', 'ttFont):', 'inputDataSize', '=', 'len(data)', 'if', 'inputDataSize', '<', 'woff2GlyfTableFormatSize:', 'raise', 'TTLibError("not', 'enough', "'glyf'", 'data")', '(dummy,', 'data)', '=', 'sstruct.unpack2(woff2GlyfTableFormat,', 'data,', 'self)', 'offset', '=', 'woff2GlyfTableFormat... | 317,438 |
devashish-patel/webcam-motion-detector | application.py | Application.print_description | print_description | Print the application description. | [
"Print",
"the",
"application",
"description."
] | def print_description(self):
for p in wrap_paragraphs(self.description):
print(p)
print() | ['def', 'print_description(self):', 'for', 'p', 'in', 'wrap_paragraphs(self.description):', 'print(p)', 'print()'] | 985,302 |
devashish-patel/webcam-motion-detector | tarfile.py | TarFile.makeunknown | makeunknown | Make a file from a TarInfo object with an unknown type at targetpath. | [
"Make",
"a",
"file",
"from",
"a",
"TarInfo",
"object",
"with",
"an",
"unknown",
"type",
"at",
"targetpath."
] | def makeunknown(self, tarinfo, targetpath):
self.makefile(tarinfo, targetpath)
self._dbg(1, 'tarfile: Unknown file type %r, extracted as regular file.' % tarinfo.type) | ['def', 'makeunknown(self,', 'tarinfo,', 'targetpath):', 'self.makefile(tarinfo,', 'targetpath)', 'self._dbg(1,', "'tarfile:", 'Unknown', 'file', 'type', '%r,', 'extracted', 'as', 'regular', "file.'", '%', 'tarinfo.type)'] | 983,236 |
tonybeltramelli/Graphics-And-Vision | Cameras.py | Cameras.Size | Size | Set a new size to captured images. | [
"Set",
"a",
"new",
"size",
"to",
"captured",
"images."
] | def Size(self, value):
for index in self.__camera:
self.__camera[index].Size = value | ['def', 'Size(self,', 'value):', 'for', 'index', 'in', 'self.__camera:', 'self.__camera[index].Size', '=', 'value'] | 580,575 |
weimin17/Object-Detection_HelmetDetection | sgf_wrapper.py | sgf_prop | sgf_prop | Converts raw sgf library output to sensible value. | [
"Converts",
"raw",
"sgf",
"library",
"output",
"to",
"sensible",
"value."
] | def sgf_prop(value_list):
if value_list is None:
return None
if len(value_list) == 1:
return value_list[0]
else:
return value_list | ['def', 'sgf_prop(value_list):', 'if', 'value_list', 'is', 'None:', 'return', 'None', 'if', 'len(value_list)', '==', '1:', 'return', 'value_list[0]', 'else:', 'return', 'value_list'] | 763,910 |
Wuziyi616/Artificial_Intelligence_Project1 | search_algorithm.py | Mask.element_is_valid | element_is_valid | Judge whether an element is valid. | [
"Judge",
"whether",
"an",
"element",
"is",
"valid."
] | def element_is_valid(self, element):
if not self.element_is_inside_grid(element):
return False
if not self.connectivity_area_is_valid(element):
return False
return True | ['def', 'element_is_valid(self,', 'element):', 'if', 'not', 'self.element_is_inside_grid(element):', 'return', 'False', 'if', 'not', 'self.connectivity_area_is_valid(element):', 'return', 'False', 'return', 'True'] | 92,197 |
TencentYoutuResearch/SelfSupervisedLearning-DSM | reterival.py | topk_retrieval | topk_retrieval | Extract features from test split and search on train split features. | [
"Extract",
"features",
"from",
"test",
"split",
"and",
"search",
"on",
"train",
"split",
"features."
] | def topk_retrieval(feature_dir):
print('Load local .npy files. from ...', feature_dir)
train_features = np.load(os.path.join(feature_dir, 'train_features.npy'), allow_pickle=True).item()
X_train = train_features['data']
y_train = train_features['target']
val_features = np.load(os.path.join(feature_d... | ['def', 'topk_retrieval(feature_dir):', "print('Load", 'local', '.npy', 'files.', 'from', "...',", 'feature_dir)', 'train_features', '=', 'np.load(os.path.join(feature_dir,', "'train_features.npy'),", 'allow_pickle=True).item()', 'X_train', '=', "train_features['data']", 'y_train', '=', "train_features['target']", 'val... | 342,357 |
zihuitang/medical_AI_platform | tracemalloc.py | take_snapshot | take_snapshot | Take a snapshot of traces of memory blocks allocated by Python. | [
"Take",
"a",
"snapshot",
"of",
"traces",
"of",
"memory",
"blocks",
"allocated",
"by",
"Python."
] | def take_snapshot():
if not is_tracing():
raise RuntimeError('the tracemalloc module must be tracing memory allocations to take a snapshot')
traces = _get_traces()
traceback_limit = get_traceback_limit()
return Snapshot(traces, traceback_limit) | ['def', 'take_snapshot():', 'if', 'not', 'is_tracing():', 'raise', "RuntimeError('the", 'tracemalloc', 'module', 'must', 'be', 'tracing', 'memory', 'allocations', 'to', 'take', 'a', "snapshot')", 'traces', '=', '_get_traces()', 'traceback_limit', '=', 'get_traceback_limit()', 'return', 'Snapshot(traces,', 'traceback_li... | 281,673 |
dongliangcao/Unsupervised-Learning-of-Robust-Spectral-Shape-Matching | dist_util.py | init_dist | init_dist | Initialize slurm distributed training environment. | [
"Initialize",
"slurm",
"distributed",
"training",
"environment."
] | def init_dist(backend='nccl', port=29500):
if mp.get_start_method(allow_none=True) is None:
mp.set_start_method('spawn')
_init_dist_slurm(backend, port) | ['def', "init_dist(backend='nccl',", 'port=29500):', 'if', 'mp.get_start_method(allow_none=True)', 'is', 'None:', "mp.set_start_method('spawn')", '_init_dist_slurm(backend,', 'port)'] | 353,568 |
ludwig-ai/ludwig | utils.py | assert_preprocessed_dataset_shape_and_dtype_for_feature | assert_preprocessed_dataset_shape_and_dtype_for_feature | Asserts that the preprocessed dataset has the correct shape and dtype for a given feature type. | [
"Asserts",
"that",
"the",
"preprocessed",
"dataset",
"has",
"the",
"correct",
"shape",
"and",
"dtype",
"for",
"a",
"given",
"feature",
"type."
] | def assert_preprocessed_dataset_shape_and_dtype_for_feature(feature_name: str, preprocessed_dataset: 'Dataset', config_obj: 'ModelConfig', expected_dtype: np.dtype, expected_shape: Tuple):
if_configs = [if_config for if_config in config_obj.input_features if if_config.name == feature_name]
if len(if_configs) !=... | ['def', 'assert_preprocessed_dataset_shape_and_dtype_for_feature(feature_name:', 'str,', 'preprocessed_dataset:', "'Dataset',", 'config_obj:', "'ModelConfig',", 'expected_dtype:', 'np.dtype,', 'expected_shape:', 'Tuple):', 'if_configs', '=', '[if_config', 'for', 'if_config', 'in', 'config_obj.input_features', 'if', 'if... | 617,369 |
Tencent/ObjectDetection-OneStageDet | box.py | Box.serialize | serialize | abstract serializer, implement in derived classes. | [
"abstract",
"serializer,",
"implement",
"in",
"derived",
"classes."
] | def serialize(self):
raise NotImplementedError | ['def', 'serialize(self):', 'raise', 'NotImplementedError'] | 744,479 |
locationlabs/mockredis | test_pipeline.py | TestPipeline.test_watch | test_watch | Verify watch puts the pipeline in immediate execution mode. | [
"Verify",
"watch",
"puts",
"the",
"pipeline",
"in",
"immediate",
"execution",
"mode."
] | def test_watch(self):
with self.redis.pipeline() as pipeline:
pipeline.watch('key1', 'key2')
eq_(None, pipeline.get('key1'))
eq_(None, pipeline.get('key2'))
eq_(True, pipeline.set('foo', 'bar'))
eq_(b'bar', pipeline.get('foo')) | ['def', 'test_watch(self):', 'with', 'self.redis.pipeline()', 'as', 'pipeline:', "pipeline.watch('key1',", "'key2')", 'eq_(None,', "pipeline.get('key1'))", 'eq_(None,', "pipeline.get('key2'))", 'eq_(True,', "pipeline.set('foo',", "'bar'))", "eq_(b'bar',", "pipeline.get('foo'))"] | 240,659 |
nosmokingbandit/watcher | httputil.py | HeaderMap.encode | encode | Return the given header name or value, encoded for HTTP output. | [
"Return",
"the",
"given",
"header",
"name",
"or",
"value,",
"encoded",
"for",
"HTTP",
"output."
] | def encode(cls, v):
for enc in cls.encodings:
try:
return v.encode(enc)
except UnicodeEncodeError:
continue
if cls.protocol == (1, 1) and cls.use_rfc_2047:
v = b2a_base64(v.encode('utf-8'))
return ntob('=?utf-8?b?') + v.strip(ntob('\n')) + ntob('?=')
r... | ['def', 'encode(cls,', 'v):', 'for', 'enc', 'in', 'cls.encodings:', 'try:', 'return', 'v.encode(enc)', 'except', 'UnicodeEncodeError:', 'continue', 'if', 'cls.protocol', '==', '(1,', '1)', 'and', 'cls.use_rfc_2047:', 'v', '=', "b2a_base64(v.encode('utf-8'))", 'return', "ntob('=?utf-8?b?')", '+', "v.strip(ntob('\\n'))",... | 381,447 |
rudranil723/mini-main | info.py | SeriesTableBuilder.add_memory_usage_line | add_memory_usage_line | Add line containing memory usage. | [
"Add",
"line",
"containing",
"memory",
"usage."
] | def add_memory_usage_line(self) -> None:
self._lines.append(f'memory usage: {self.memory_usage_string}') | ['def', 'add_memory_usage_line(self)', '->', 'None:', "self._lines.append(f'memory", 'usage:', "{self.memory_usage_string}')"] | 267,265 |
cheng052/BRNet | primitive_head.py | PrimitiveHead.check_dist | check_dist | Whether the mean of points to plane distance is lower than thresh. | [
"Whether",
"the",
"mean",
"of",
"points",
"to",
"plane",
"distance",
"is",
"lower",
"than",
"thresh."
] | def check_dist(self, plane_equ, points):
return (points[:, 2] + plane_equ[-1]).sum() / 4.0 < self.train_cfg['lower_thresh'] | ['def', 'check_dist(self,', 'plane_equ,', 'points):', 'return', '(points[:,', '2]', '+', 'plane_equ[-1]).sum()', '/', '4.0', '<', "self.train_cfg['lower_thresh']"] | 409,966 |
tensorflow/privacy | mnist_scratch.py | cnn_model_fn | cnn_model_fn | Model function for a CNN. | [
"Model",
"function",
"for",
"a",
"CNN."
] | def cnn_model_fn(features, labels, mode):
input_layer = tf.reshape(features['x'], [-1, 28, 28, 1])
y = tf.keras.layers.Conv2D(16, 8, strides=2, padding='same', activation='relu').apply(input_layer)
y = tf.keras.layers.MaxPool2D(2, 1).apply(y)
y = tf.keras.layers.Conv2D(32, 4, strides=2, padding='valid',... | ['def', 'cnn_model_fn(features,', 'labels,', 'mode):', 'input_layer', '=', "tf.reshape(features['x'],", '[-1,', '28,', '28,', '1])', 'y', '=', 'tf.keras.layers.Conv2D(16,', '8,', 'strides=2,', "padding='same',", "activation='relu').apply(input_layer)", 'y', '=', 'tf.keras.layers.MaxPool2D(2,', '1).apply(y)', 'y', '=', ... | 824,967 |
boostcampaitech2/semantic-segmentation-level2-cv-07 | tblr_bbox_coder.py | TBLRBBoxCoder.encode | encode | Get box regression transformation deltas that can be used to transform the ``bboxes`` into the ``gt_bboxes`` in the (top, left, bottom, right) order. | [
"Get",
"box",
"regression",
"transformation",
"deltas",
"that",
"can",
"be",
"used",
"to",
"transform",
"the",
"``bboxes``",
"into",
"the",
"``gt_bboxes``",
"in",
"the",
"(top,",
"left,",
"bottom,",
"right)",
"order."
] | def encode(self, bboxes, gt_bboxes):
assert bboxes.size(0) == gt_bboxes.size(0)
assert bboxes.size(-1) == gt_bboxes.size(-1) == 4
encoded_bboxes = bboxes2tblr(bboxes, gt_bboxes, normalizer=self.normalizer)
return encoded_bboxes | ['def', 'encode(self,', 'bboxes,', 'gt_bboxes):', 'assert', 'bboxes.size(0)', '==', 'gt_bboxes.size(0)', 'assert', 'bboxes.size(-1)', '==', 'gt_bboxes.size(-1)', '==', '4', 'encoded_bboxes', '=', 'bboxes2tblr(bboxes,', 'gt_bboxes,', 'normalizer=self.normalizer)', 'return', 'encoded_bboxes'] | 856,831 |
weimin17/Object-Detection_HelmetDetection | lexnet_model.py | LexNETModel.load_pairs | load_pairs | Loads the word pairs for these instances. | [
"Loads",
"the",
"word",
"pairs",
"for",
"these",
"instances."
] | def load_pairs(self, session, instances):
word_pairs = session.run(self.pairs_to_load, feed_dict={self.instances_to_load: instances})
return [pair[0].split('::') for pair in word_pairs] | ['def', 'load_pairs(self,', 'session,', 'instances):', 'word_pairs', '=', 'session.run(self.pairs_to_load,', 'feed_dict={self.instances_to_load:', 'instances})', 'return', "[pair[0].split('::')", 'for', 'pair', 'in', 'word_pairs]'] | 763,442 |
mj-will/nessai | test_flowsampler.py | test_save_result_no_extension | test_save_result_no_extension | Assert an error is raised if a file extension is not given or included in the filename. | [
"Assert",
"an",
"error",
"is",
"raised",
"if",
"a",
"file",
"extension",
"is",
"not",
"given",
"or",
"included",
"in",
"the",
"filename."
] | def test_save_result_no_extension(flow_sampler, posterior_samples):
d = dict(a=1)
ns = MagicMock()
ns.get_result_dictionary = MagicMock(return_value=d)
flow_sampler.ns = ns
flow_sampler.posterior_samples = posterior_samples
with pytest.raises(RuntimeError, match='Must specify file extension if n... | ['def', 'test_save_result_no_extension(flow_sampler,', 'posterior_samples):', 'd', '=', 'dict(a=1)', 'ns', '=', 'MagicMock()', 'ns.get_result_dictionary', '=', 'MagicMock(return_value=d)', 'flow_sampler.ns', '=', 'ns', 'flow_sampler.posterior_samples', '=', 'posterior_samples', 'with', 'pytest.raises(RuntimeError,', "m... | 292,240 |
SvenGronauer/phoenix-drone-simulation | mpi_tools.py | mpi_min | mpi_min | Determine global minimum of scalar or numpy array over MPI processes. | [
"Determine",
"global",
"minimum",
"of",
"scalar",
"or",
"numpy",
"array",
"over",
"MPI",
"processes."
] | def mpi_min(x):
return mpi_op(x, MPI.MIN) | ['def', 'mpi_min(x):', 'return', 'mpi_op(x,', 'MPI.MIN)'] | 769,207 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_fitpack2.py | TestUnivariateSpline.test_resize_regression | test_resize_regression | Regression test for #1375. | [
"Regression",
"test",
"for",
"#1375."
] | def test_resize_regression(self):
x = [-1.0, -0.65016502, -0.58856235, -0.26903553, -0.17370892, -0.10011001, 0.0, 0.10011001, 0.17370892, 0.26903553, 0.58856235, 0.65016502, 1.0]
y = [1.0, 0.62928599, 0.5797223, 0.39965815, 0.36322694, 0.3508061, 0.35214793, 0.3508061, 0.36322694, 0.39965815, 0.5797223, 0.6292... | ['def', 'test_resize_regression(self):', 'x', '=', '[-1.0,', '-0.65016502,', '-0.58856235,', '-0.26903553,', '-0.17370892,', '-0.10011001,', '0.0,', '0.10011001,', '0.17370892,', '0.26903553,', '0.58856235,', '0.65016502,', '1.0]', 'y', '=', '[1.0,', '0.62928599,', '0.5797223,', '0.39965815,', '0.36322694,', '0.3508061... | 99,469 |
sunishsheth2009/ChatterBot | testing.py | HTMLTreeBuilderSmokeTest.test_multipart_strings | test_multipart_strings | Mostly to prevent a recurrence of a bug in the html5lib treebuilder. | [
"Mostly",
"to",
"prevent",
"a",
"recurrence",
"of",
"a",
"bug",
"in",
"the",
"html5lib",
"treebuilder."
] | def test_multipart_strings(self):
soup = self.soup('<html><h2>\nfoo</h2><p></p></html>')
self.assertEqual('p', soup.h2.string.next_element.name)
self.assertEqual('p', soup.p.name) | ['def', 'test_multipart_strings(self):', 'soup', '=', "self.soup('<html><h2>\\nfoo</h2><p></p></html>')", "self.assertEqual('p',", 'soup.h2.string.next_element.name)', "self.assertEqual('p',", 'soup.p.name)'] | 528,800 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data.py | ToSentences | ToSentences | Takes tokens of a paragraph and returns list of sentences. | [
"Takes",
"tokens",
"of",
"a",
"paragraph",
"and",
"returns",
"list",
"of",
"sentences."
] | def ToSentences(paragraph, include_token=True):
s_gen = SnippetGen(paragraph, SENTENCE_START, SENTENCE_END, include_token)
return [s for s in s_gen] | ['def', 'ToSentences(paragraph,', 'include_token=True):', 's_gen', '=', 'SnippetGen(paragraph,', 'SENTENCE_START,', 'SENTENCE_END,', 'include_token)', 'return', '[s', 'for', 's', 'in', 's_gen]'] | 112,712 |
FRC4903/Computer-Vision | visualization_utils.py | draw_keypoints_on_image | draw_keypoints_on_image | Draws keypoints on an image. | [
"Draws",
"keypoints",
"on",
"an",
"image."
] | def draw_keypoints_on_image(image, keypoints, color='red', radius=2, use_normalized_coordinates=True):
draw = ImageDraw.Draw(image)
(im_width, im_height) = image.size
keypoints_x = [k[1] for k in keypoints]
keypoints_y = [k[0] for k in keypoints]
if use_normalized_coordinates:
keypoints_x = ... | ['def', 'draw_keypoints_on_image(image,', 'keypoints,', "color='red',", 'radius=2,', 'use_normalized_coordinates=True):', 'draw', '=', 'ImageDraw.Draw(image)', '(im_width,', 'im_height)', '=', 'image.size', 'keypoints_x', '=', '[k[1]', 'for', 'k', 'in', 'keypoints]', 'keypoints_y', '=', '[k[0]', 'for', 'k', 'in', 'keyp... | 459,299 |
rifqind/Agent-Programs-3KS1 | compat.py | BaseConfigurator.as_tuple | as_tuple | Utility function which converts lists to tuples. | [
"Utility",
"function",
"which",
"converts",
"lists",
"to",
"tuples."
] | def as_tuple(self, value):
if isinstance(value, list):
value = tuple(value)
return value | ['def', 'as_tuple(self,', 'value):', 'if', 'isinstance(value,', 'list):', 'value', '=', 'tuple(value)', 'return', 'value'] | 44,520 |
dwaiter/django-bcrypt | models.py | bcrypt_set_password | bcrypt_set_password | Sets the user's password to *raw_password*, hashed with bcrypt. | [
"Sets",
"the",
"user's",
"password",
"to",
"*raw_password*,",
"hashed",
"with",
"bcrypt."
] | def bcrypt_set_password(self, raw_password):
if not is_enabled() or raw_password is None:
_set_password(self, raw_password)
else:
salt = bcrypt.gensalt(get_rounds())
self.password = 'bc$' + bcrypt.hashpw(smart_str(raw_password), salt) | ['def', 'bcrypt_set_password(self,', 'raw_password):', 'if', 'not', 'is_enabled()', 'or', 'raw_password', 'is', 'None:', '_set_password(self,', 'raw_password)', 'else:', 'salt', '=', 'bcrypt.gensalt(get_rounds())', 'self.password', '=', "'bc$'", '+', 'bcrypt.hashpw(smart_str(raw_password),', 'salt)'] | 189,549 |
intel/neural-compressor | model.py | Model.supports_profiling | supports_profiling | Check if profiling is supported for the model. | [
"Check",
"if",
"profiling",
"is",
"supported",
"for",
"the",
"model."
] | def supports_profiling(self) -> bool:
return False | ['def', 'supports_profiling(self)', '->', 'bool:', 'return', 'False'] | 721,561 |
rtlee9/recipe-summarization | prep_data.py | load_recipes | load_recipes | Load all recipe collections from disk and combine into single dataset. | [
"Load",
"all",
"recipe",
"collections",
"from",
"disk",
"and",
"combine",
"into",
"single",
"dataset."
] | def load_recipes():
recipes = {}
for filename in glob(path.join(config.path_recipe_box_data, 'recipes_raw*.json')):
recipes.update(load_recipe(filename))
print('Loaded {:,} recipes in total'.format(len(recipes)))
return clean_recipe_keys(recipes) | ['def', 'load_recipes():', 'recipes', '=', '{}', 'for', 'filename', 'in', 'glob(path.join(config.path_recipe_box_data,', "'recipes_raw*.json')):", 'recipes.update(load_recipe(filename))', "print('Loaded", '{:,}', 'recipes', 'in', "total'.format(len(recipes)))", 'return', 'clean_recipe_keys(recipes)'] | 309,063 |
dwf/convolupy | tests.py | fd_grad | fd_grad | Approximates the gradient of f with finite differences, moving half of tol in either direction on each axis. | [
"Approximates",
"the",
"gradient",
"of",
"f",
"with",
"finite",
"differences,",
"moving",
"half",
"of",
"tol",
"in",
"either",
"direction",
"on",
"each",
"axis."
] | def fd_grad(func, x_in, tol=1e-05):
num = len(x_in)
grad = np.zeros(num)
for i in xrange(num):
aaa = x_in.copy()
bbb = x_in.copy()
aaa[i] = aaa[i] - tol / 2.0
bbb[i] = bbb[i] + tol / 2.0
grad[i] = (func(bbb) - func(aaa)) / (bbb[i] - aaa[i])
return grad | ['def', 'fd_grad(func,', 'x_in,', 'tol=1e-05):', 'num', '=', 'len(x_in)', 'grad', '=', 'np.zeros(num)', 'for', 'i', 'in', 'xrange(num):', 'aaa', '=', 'x_in.copy()', 'bbb', '=', 'x_in.copy()', 'aaa[i]', '=', 'aaa[i]', '-', 'tol', '/', '2.0', 'bbb[i]', '=', 'bbb[i]', '+', 'tol', '/', '2.0', 'grad[i]', '=', '(func(bbb)', ... | 136,982 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_pgf.py | PdfPages.close | close | Finalize this object, running LaTeX in a temporary directory and moving the final pdf file to *filename*. | [
"Finalize",
"this",
"object,",
"running",
"LaTeX",
"in",
"a",
"temporary",
"directory",
"and",
"moving",
"the",
"final",
"pdf",
"file",
"to",
"*filename*."
] | def close(self):
self._file.write(b'\\end{document}\\n')
self._file.close()
if self._n_figures > 0:
try:
self._run_latex()
finally:
try:
shutil.rmtree(self._tmpdir)
except:
TmpDirCleaner.add(self._tmpdir)
elif self.keep_... | ['def', 'close(self):', "self._file.write(b'\\\\end{document}\\\\n')", 'self._file.close()', 'if', 'self._n_figures', '>', '0:', 'try:', 'self._run_latex()', 'finally:', 'try:', 'shutil.rmtree(self._tmpdir)', 'except:', 'TmpDirCleaner.add(self._tmpdir)', 'elif', 'self.keep_empty:', 'open(self._outputfile,', "'wb').clos... | 257,675 |
sunishsheth2009/ChatterBot | wikipedia.py | WikipediaPage.content | content | Plain text content of the page, excluding images, tables, and other data. | [
"Plain",
"text",
"content",
"of",
"the",
"page,",
"excluding",
"images,",
"tables,",
"and",
"other",
"data."
] | def content(self):
if not getattr(self, '_content', False):
query_params = {'prop': 'extracts', 'explaintext': '', 'titles': self.title}
request = _wiki_request(**query_params)
self._content = request['query']['pages'][self.pageid]['extract']
return self._content | ['def', 'content(self):', 'if', 'not', 'getattr(self,', "'_content',", 'False):', 'query_params', '=', "{'prop':", "'extracts',", "'explaintext':", "'',", "'titles':", 'self.title}', 'request', '=', '_wiki_request(**query_params)', 'self._content', '=', "request['query']['pages'][self.pageid]['extract']", 'return', 'se... | 484,849 |
zihuitang/medical_AI_platform | re.py | fullmatch | fullmatch | Try to apply the pattern to all of the string, returning a match object, or None if no match was found. | [
"Try",
"to",
"apply",
"the",
"pattern",
"to",
"all",
"of",
"the",
"string,",
"returning",
"a",
"match",
"object,",
"or",
"None",
"if",
"no",
"match",
"was",
"found."
] | def fullmatch(pattern, string, flags=0):
return _compile(pattern, flags).fullmatch(string) | ['def', 'fullmatch(pattern,', 'string,', 'flags=0):', 'return', '_compile(pattern,', 'flags).fullmatch(string)'] | 281,285 |
weimin17/Object-Detection_HelmetDetection | memory.py | Memory.query | query | Queries memory for nearest neighbor. | [
"Queries",
"memory",
"for",
"nearest",
"neighbor."
] | def query(self, query_vec, intended_output, use_recent_idx=True):
batch_size = tf.shape(query_vec)[0]
output_given = intended_output is not None
query_vec = tf.matmul(query_vec, self.query_proj)
normalized_query = tf.nn.l2_normalize(query_vec, dim=1)
hint_pool_idxs = self.get_hint_pool_idxs(normaliz... | ['def', 'query(self,', 'query_vec,', 'intended_output,', 'use_recent_idx=True):', 'batch_size', '=', 'tf.shape(query_vec)[0]', 'output_given', '=', 'intended_output', 'is', 'not', 'None', 'query_vec', '=', 'tf.matmul(query_vec,', 'self.query_proj)', 'normalized_query', '=', 'tf.nn.l2_normalize(query_vec,', 'dim=1)', 'h... | 750,408 |
devashish-patel/webcam-motion-detector | document.py | Document.get_cursor_right_position | get_cursor_right_position | Relative position for cursor_right. | [
"Relative",
"position",
"for",
"cursor_right."
] | def get_cursor_right_position(self, count=1):
if count < 0:
return self.get_cursor_left_position(-count)
return min(count, len(self.current_line_after_cursor)) | ['def', 'get_cursor_right_position(self,', 'count=1):', 'if', 'count', '<', '0:', 'return', 'self.get_cursor_left_position(-count)', 'return', 'min(count,', 'len(self.current_line_after_cursor))'] | 983,732 |
triaquae/triaquae | geometries.py | OGRGeometry.envelope | envelope | Returns the envelope for this Geometry. | [
"Returns",
"the",
"envelope",
"for",
"this",
"Geometry."
] | def envelope(self):
return Envelope(capi.get_envelope(self.ptr, byref(OGREnvelope()))) | ['def', 'envelope(self):', 'return', 'Envelope(capi.get_envelope(self.ptr,', 'byref(OGREnvelope())))'] | 357,573 |
suarez12138/AI-Reversi_IMP_TextDichotomy | streamplot.py | DomainMap.grid2mask | grid2mask | Return nearest space in mask-coords from given grid-coords. | [
"Return",
"nearest",
"space",
"in",
"mask-coords",
"from",
"given",
"grid-coords."
] | def grid2mask(self, xi, yi):
return (int(xi * self.x_grid2mask + 0.5), int(yi * self.y_grid2mask + 0.5)) | ['def', 'grid2mask(self,', 'xi,', 'yi):', 'return', '(int(xi', '*', 'self.x_grid2mask', '+', '0.5),', 'int(yi', '*', 'self.y_grid2mask', '+', '0.5))'] | 96,765 |
onnx/onnx | model_inference_test.py | TestModelInference.test_mi_function_attr | test_mi_function_attr | Test use of functions with attribute parameters. | [
"Test",
"use",
"of",
"functions",
"with",
"attribute",
"parameters."
] | def test_mi_function_attr(self):
model = '\n <\n ir_version: 7,\n opset_import: [ "" : 17, "local" : 1]\n >\n agraph (float[N] x) => (y)\n {\n y = local.cast<target=6>(x)\n }\n <\n opset_imp... | ['def', 'test_mi_function_attr(self):', 'model', '=', "'\\n", '<\\n', 'ir_version:', '7,\\n', 'opset_import:', '[', '""', ':', '17,', '"local"', ':', '1]\\n', '>\\n', 'agraph', '(float[N]', 'x)', '=>', '(y)\\n', '{\\n', 'y', '=', 'local.cast<target=6>(x)\\n', '}\\n', '<\\n', 'opset_import:', '[', '""', ':', '17', '],\\... | 756,575 |
ifwe/digsby | default_ui.py | title_for_service | title_for_service | The title for the dialog. | [
"The",
"title",
"for",
"the",
"dialog."
] | def title_for_service(sp, sp_info):
if sp is None:
title = unicode(sp_info.name)
else:
title = _(u'{account_name:s} - {service_name:s} Settings').format(account_name=sp.name, service_name=sp_info.name)
return title | ['def', 'title_for_service(sp,', 'sp_info):', 'if', 'sp', 'is', 'None:', 'title', '=', 'unicode(sp_info.name)', 'else:', 'title', '=', "_(u'{account_name:s}", '-', '{service_name:s}', "Settings').format(account_name=sp.name,", 'service_name=sp_info.name)', 'return', 'title'] | 185,970 |
myothida/Supervised-Machine-Learning | glifLib.py | Glyph.drawPoints | drawPoints | Draw this glyph onto a PointPen. | [
"Draw",
"this",
"glyph",
"onto",
"a",
"PointPen."
] | def drawPoints(self, pointPen):
self.glyphSet.readGlyph(self.glyphName, self, pointPen) | ['def', 'drawPoints(self,', 'pointPen):', 'self.glyphSet.readGlyph(self.glyphName,', 'self,', 'pointPen)'] | 361,262 |
zackmcnulty/CSE_446-Machine_Learning | backend_pdf.py | pdfRepr | pdfRepr | Map Python objects to PDF syntax. | [
"Map",
"Python",
"objects",
"to",
"PDF",
"syntax."
] | def pdfRepr(obj):
if hasattr(obj, 'pdfRepr'):
return obj.pdfRepr()
elif isinstance(obj, (float, np.floating)):
if not np.isfinite(obj):
raise ValueError('Can only output finite numbers in PDF')
r = b'%.10f' % obj
return r.rstrip(b'0').rstrip(b'.')
elif isinstance(... | ['def', 'pdfRepr(obj):', 'if', 'hasattr(obj,', "'pdfRepr'):", 'return', 'obj.pdfRepr()', 'elif', 'isinstance(obj,', '(float,', 'np.floating)):', 'if', 'not', 'np.isfinite(obj):', 'raise', "ValueError('Can", 'only', 'output', 'finite', 'numbers', 'in', "PDF')", 'r', '=', "b'%.10f'", '%', 'obj', 'return', "r.rstrip(b'0')... | 194,977 |
openvinotoolkit/datumaro | dataset_base.py | IDataset.is_stream | is_stream | Boolean indicating whether the dataset is a stream If the dataset is a stream, the dataset item is generated on demand from its iterator. | [
"Boolean",
"indicating",
"whether",
"the",
"dataset",
"is",
"a",
"stream",
"If",
"the",
"dataset",
"is",
"a",
"stream,",
"the",
"dataset",
"item",
"is",
"generated",
"on",
"demand",
"from",
"its",
"iterator."
] | def is_stream(self) -> bool:
return False | ['def', 'is_stream(self)', '->', 'bool:', 'return', 'False'] | 498,079 |
scotthuang1989/object_detection_with_tensorflow | dsn.py | add_reconstruction_loss | add_reconstruction_loss | Adds a reconstruction loss. | [
"Adds",
"a",
"reconstruction",
"loss."
] | def add_reconstruction_loss(recon_loss_name, images, recons, weight, domain):
if recon_loss_name == 'sum_of_pairwise_squares':
loss_fn = tf.contrib.losses.mean_pairwise_squared_error
elif recon_loss_name == 'sum_of_squares':
loss_fn = tf.contrib.losses.mean_squared_error
else:
raise ... | ['def', 'add_reconstruction_loss(recon_loss_name,', 'images,', 'recons,', 'weight,', 'domain):', 'if', 'recon_loss_name', '==', "'sum_of_pairwise_squares':", 'loss_fn', '=', 'tf.contrib.losses.mean_pairwise_squared_error', 'elif', 'recon_loss_name', '==', "'sum_of_squares':", 'loss_fn', '=', 'tf.contrib.losses.mean_squ... | 797,014 |
Katja-M/Python_NaturalLanguageProcessing | hole.py | HoleSemantics.formula_tree | formula_tree | Return the first-order logic formula tree for this underspecified representation using the plugging given. | [
"Return",
"the",
"first-order",
"logic",
"formula",
"tree",
"for",
"this",
"underspecified",
"representation",
"using",
"the",
"plugging",
"given."
] | def formula_tree(self, plugging):
return self._formula_tree(plugging, self.top_hole) | ['def', 'formula_tree(self,', 'plugging):', 'return', 'self._formula_tree(plugging,', 'self.top_hole)'] | 866,838 |
tensorflow/agents | eager_utils.py | add_variables_summaries | add_variables_summaries | Add summaries for variables. | [
"Add",
"summaries",
"for",
"variables."
] | def add_variables_summaries(grads_and_vars, step):
with tf.name_scope('summarize_vars'):
for (_, var) in grads_and_vars:
if isinstance(var, tf.IndexedSlices):
var_values = var.values
else:
var_values = var
var_name = var.name.replace(':', '... | ['def', 'add_variables_summaries(grads_and_vars,', 'step):', 'with', "tf.name_scope('summarize_vars'):", 'for', '(_,', 'var)', 'in', 'grads_and_vars:', 'if', 'isinstance(var,', 'tf.IndexedSlices):', 'var_values', '=', 'var.values', 'else:', 'var_values', '=', 'var', 'var_name', '=', "var.name.replace(':',", "'_')", 'tf... | 23,827 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | ttk.py | Treeview.parent | parent | Returns the ID of the parent of item, or '' if item is at the top level of the hierarchy. | [
"Returns",
"the",
"ID",
"of",
"the",
"parent",
"of",
"item,",
"or",
"''",
"if",
"item",
"is",
"at",
"the",
"top",
"level",
"of",
"the",
"hierarchy."
] | def parent(self, item):
return self.tk.call(self._w, 'parent', item) | ['def', 'parent(self,', 'item):', 'return', 'self.tk.call(self._w,', "'parent',", 'item)'] | 376,725 |
kubeflow/pipelines | private_text_comparison_importer.py | PrivateTextComparisonImporter | PrivateTextComparisonImporter | Import a text dataset. | [
"Import",
"a",
"text",
"dataset."
] | def PrivateTextComparisonImporter(project: str, location: str, input_text: str, inputs_field_name: str, comma_separated_candidates_field_names: str, choice_field_name: str, split: str, large_model_reference: str, image_uri: str, output_dataset_path: kfp.dsl.OutputPath(str), gcp_resources: kfp.dsl.OutputPath(str), machi... | ['def', 'PrivateTextComparisonImporter(project:', 'str,', 'location:', 'str,', 'input_text:', 'str,', 'inputs_field_name:', 'str,', 'comma_separated_candidates_field_names:', 'str,', 'choice_field_name:', 'str,', 'split:', 'str,', 'large_model_reference:', 'str,', 'image_uri:', 'str,', 'output_dataset_path:', 'kfp.dsl.... | 779,570 |
yuanhangsu/ELSTM-DBRNN | model_utils.py | sequence_loss | sequence_loss | Weighted cross-entropy loss for a sequence of logits, batch-collapsed. | [
"Weighted",
"cross-entropy",
"loss",
"for",
"a",
"sequence",
"of",
"logits,",
"batch-collapsed."
] | def sequence_loss(logits, targets, weights, average_across_timesteps=True, average_across_batch=True, softmax_loss_function=None, name=None):
with ops.name_scope(name, 'sequence_loss', logits + targets + weights):
cost = math_ops.reduce_sum(sequence_loss_by_example(logits, targets, weights, average_across_t... | ['def', 'sequence_loss(logits,', 'targets,', 'weights,', 'average_across_timesteps=True,', 'average_across_batch=True,', 'softmax_loss_function=None,', 'name=None):', 'with', 'ops.name_scope(name,', "'sequence_loss',", 'logits', '+', 'targets', '+', 'weights):', 'cost', '=', 'math_ops.reduce_sum(sequence_loss_by_exampl... | 176,042 |
arshpreetsingh/quantopian-machinelearning | formatting.py | HelpFormatter.getvalue | getvalue | Returns the buffer contents. | [
"Returns",
"the",
"buffer",
"contents."
] | def getvalue(self):
return ''.join(self.buffer) | ['def', 'getvalue(self):', 'return', "''.join(self.buffer)"] | 816,654 |
MegEngine/Transfer-Learning-Library | ibn.py | resnet101_ibn_a | resnet101_ibn_a | Constructs a ResNet-101-IBN-a model. | [
"Constructs",
"a",
"ResNet-101-IBN-a",
"model."
] | def resnet101_ibn_a(pretrained=False):
model = IBNNet(block=Bottleneck, layers=[3, 4, 23, 3], ibn_cfg=('a', 'a', 'a', None))
if pretrained:
model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet101_ibn_a']), strict=False)
return model | ['def', 'resnet101_ibn_a(pretrained=False):', 'model', '=', 'IBNNet(block=Bottleneck,', 'layers=[3,', '4,', '23,', '3],', "ibn_cfg=('a',", "'a',", "'a',", 'None))', 'if', 'pretrained:', "model.load_state_dict(torch.hub.load_state_dict_from_url(model_urls['resnet101_ibn_a']),", 'strict=False)', 'return', 'model'] | 921,171 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | streams.py | CommonTokenStream.get | get | Return absolute token i; ignore which channel the tokens are on; that is, count all tokens not just on-channel tokens. | [
"Return",
"absolute",
"token",
"i;",
"ignore",
"which",
"channel",
"the",
"tokens",
"are",
"on;",
"that",
"is,",
"count",
"all",
"tokens",
"not",
"just",
"on-channel",
"tokens."
] | def get(self, i):
return self.tokens[i] | ['def', 'get(self,', 'i):', 'return', 'self.tokens[i]'] | 16,001 |
rudranil723/mini-main | bidi.py | BackgroundConsumer.start | start | Start the background thread and begin consuming the thread. | [
"Start",
"the",
"background",
"thread",
"and",
"begin",
"consuming",
"the",
"thread."
] | def start(self):
with self._operational_lock:
ready = threading.Event()
thread = threading.Thread(name=_BIDIRECTIONAL_CONSUMER_NAME, target=self._thread_main, args=(ready,))
thread.daemon = True
thread.start()
ready.wait()
self._thread = thread
_LOGGER.debug('... | ['def', 'start(self):', 'with', 'self._operational_lock:', 'ready', '=', 'threading.Event()', 'thread', '=', 'threading.Thread(name=_BIDIRECTIONAL_CONSUMER_NAME,', 'target=self._thread_main,', 'args=(ready,))', 'thread.daemon', '=', 'True', 'thread.start()', 'ready.wait()', 'self._thread', '=', 'thread', "_LOGGER.debug... | 317,597 |
wandb/wandb | test_spec.py | test_3_2_3_1 | test_3_2_3_1 | The second argument to 'then' must be called when a promise is rejected. | [
"The",
"second",
"argument",
"to",
"'then'",
"must",
"be",
"called",
"when",
"a",
"promise",
"is",
"rejected."
] | def test_3_2_3_1():
c = Counter()
def check(r, c):
assert_exception(r, Exception, 'Error')
c.tick()
p1 = Promise.reject(Exception('Error'))
p2 = p1.then(None, lambda r: check(r, c))
p2._wait()
assert 1 == c.value() | ['def', 'test_3_2_3_1():', 'c', '=', 'Counter()', 'def', 'check(r,', 'c):', 'assert_exception(r,', 'Exception,', "'Error')", 'c.tick()', 'p1', '=', "Promise.reject(Exception('Error'))", 'p2', '=', 'p1.then(None,', 'lambda', 'r:', 'check(r,', 'c))', 'p2._wait()', 'assert', '1', '==', 'c.value()'] | 941,975 |
rlpy/rlpy | OMPTD.py | OMPTD.showBag | showBag | Displays the non-active features that OMP-TD can select from to add to its representation. | [
"Displays",
"the",
"non-active",
"features",
"that",
"OMP-TD",
"can",
"select",
"from",
"to",
"add",
"to",
"its",
"representation."
] | def showBag(self):
print('Remaining Items in the feature bag:')
for f in self.remainingFeatures:
print('%d: %s' % (f, str(sorted(list(self.iFDD.getFeature(f).f_set))))) | ['def', 'showBag(self):', "print('Remaining", 'Items', 'in', 'the', 'feature', "bag:')", 'for', 'f', 'in', 'self.remainingFeatures:', "print('%d:", "%s'", '%', '(f,', 'str(sorted(list(self.iFDD.getFeature(f).f_set)))))'] | 334,244 |
propublica/Capitol-Words | text_utils.py | get_named_entities | get_named_entities | Given a spacy doc, extract named entities and remove unwanted trailing tokens. | [
"Given",
"a",
"spacy",
"doc,",
"extract",
"named",
"entities",
"and",
"remove",
"unwanted",
"trailing",
"tokens."
] | def get_named_entities(doc, exclude_types=NUMERIC_NE_TYPES, drop_determiners=True):
named_entities = list(textacy.extract.named_entities(doc, exclude_types=exclude_types, drop_determiners=drop_determiners))
named_entities = [remove_trailing_tokens(ent) for ent in named_entities]
named_entities = [ne for ne ... | ['def', 'get_named_entities(doc,', 'exclude_types=NUMERIC_NE_TYPES,', 'drop_determiners=True):', 'named_entities', '=', 'list(textacy.extract.named_entities(doc,', 'exclude_types=exclude_types,', 'drop_determiners=drop_determiners))', 'named_entities', '=', '[remove_trailing_tokens(ent)', 'for', 'ent', 'in', 'named_ent... | 109,038 |
myothida/Supervised-Machine-Learning | loggingTools.py | Timer.reset | reset | Reset timer to 'start_time' or the current time. | [
"Reset",
"timer",
"to",
"'start_time'",
"or",
"the",
"current",
"time."
] | def reset(self, start=None):
if start is None:
self.start = self._time()
else:
self.start = start
self.last = self.start
self.elapsed = 0.0 | ['def', 'reset(self,', 'start=None):', 'if', 'start', 'is', 'None:', 'self.start', '=', 'self._time()', 'else:', 'self.start', '=', 'start', 'self.last', '=', 'self.start', 'self.elapsed', '=', '0.0'] | 360,979 |
Trusted-AI/AIF360 | classification_metric.py | ClassificationMetric.theil_index | theil_index | The Theil index is the :meth:`generalized_entropy_index` with :math:`\alpha = 1`. | [
"The",
"Theil",
"index",
"is",
"the",
":meth:`generalized_entropy_index`",
"with",
":math:`\\alpha",
"=",
"1`."
] | def theil_index(self):
return self.generalized_entropy_index(alpha=1) | ['def', 'theil_index(self):', 'return', 'self.generalized_entropy_index(alpha=1)'] | 412,354 |
weimin17/Object-Detection_HelmetDetection | data_sampler.py | sample_stock_data | sample_stock_data | Samples linear bandit game from stock prices dataset. | [
"Samples",
"linear",
"bandit",
"game",
"from",
"stock",
"prices",
"dataset."
] | def sample_stock_data(file_name, context_dim, num_actions, num_contexts, sigma, shuffle_rows=True):
with tf.gfile.Open(file_name, 'r') as f:
contexts = np.loadtxt(f, skiprows=1)
if shuffle_rows:
np.random.shuffle(contexts)
contexts = contexts[:num_contexts, :]
betas = np.random.uniform(-... | ['def', 'sample_stock_data(file_name,', 'context_dim,', 'num_actions,', 'num_contexts,', 'sigma,', 'shuffle_rows=True):', 'with', 'tf.gfile.Open(file_name,', "'r')", 'as', 'f:', 'contexts', '=', 'np.loadtxt(f,', 'skiprows=1)', 'if', 'shuffle_rows:', 'np.random.shuffle(contexts)', 'contexts', '=', 'contexts[:num_context... | 762,362 |
weimin17/Object-Detection_HelmetDetection | hooks_helper.py | get_logging_tensor_hook | get_logging_tensor_hook | Function to get LoggingTensorHook. | [
"Function",
"to",
"get",
"LoggingTensorHook."
] | def get_logging_tensor_hook(every_n_iter=100, tensors_to_log=None, **kwargs):
if tensors_to_log is None:
tensors_to_log = _TENSORS_TO_LOG
return tf.train.LoggingTensorHook(tensors=tensors_to_log, every_n_iter=every_n_iter) | ['def', 'get_logging_tensor_hook(every_n_iter=100,', 'tensors_to_log=None,', '**kwargs):', 'if', 'tensors_to_log', 'is', 'None:', 'tensors_to_log', '=', '_TENSORS_TO_LOG', 'return', 'tf.train.LoggingTensorHook(tensors=tensors_to_log,', 'every_n_iter=every_n_iter)'] | 761,307 |
PJLab-ADG/LoGoNet | test_assigner.py | test_max_iou_assigner_with_empty_boxes_and_gt | test_max_iou_assigner_with_empty_boxes_and_gt | Test corner case where a network might predict no boxes and no gt. | [
"Test",
"corner",
"case",
"where",
"a",
"network",
"might",
"predict",
"no",
"boxes",
"and",
"no",
"gt."
] | def test_max_iou_assigner_with_empty_boxes_and_gt():
self = MaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5)
bboxes = torch.empty((0, 4))
gt_bboxes = torch.empty((0, 4))
assign_result = self.assign(bboxes, gt_bboxes)
assert len(assign_result.gt_inds) == 0 | ['def', 'test_max_iou_assigner_with_empty_boxes_and_gt():', 'self', '=', 'MaxIoUAssigner(pos_iou_thr=0.5,', 'neg_iou_thr=0.5)', 'bboxes', '=', 'torch.empty((0,', '4))', 'gt_bboxes', '=', 'torch.empty((0,', '4))', 'assign_result', '=', 'self.assign(bboxes,', 'gt_bboxes)', 'assert', 'len(assign_result.gt_inds)', '==', '0... | 615,492 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.