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 |
|---|---|---|---|---|---|---|---|---|
Xianpeng919/MonoCon | test_pisa_head.py | test_pisa_ssd_head_loss | test_pisa_ssd_head_loss | Tests pisa ssd head loss when truth is empty and non-empty. | [
"Tests",
"pisa",
"ssd",
"head",
"loss",
"when",
"truth",
"is",
"empty",
"and",
"non-empty."
] | def test_pisa_ssd_head_loss():
s = 256
img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}]
cfg = mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.0, ignore_iof_thr=-1, gt_max_assign_all=False), isr=dict(k=2.0, bias=0.0), carl... | ['def', 'test_pisa_ssd_head_loss():', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3)}]', 'cfg', '=', "mmcv.Config(dict(assigner=dict(type='MaxIoUAssigner',", 'pos_iou_thr=0.5,', 'neg_iou_thr=0.5,', 'min_pos_iou=0.0,', 'ignore_iof_thr=-1... | 654,158 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | timeseries.py | TimeseriesToyProblem.num_eval_shards | num_eval_shards | Number of eval shards. | [
"Number",
"of",
"eval",
"shards."
] | def num_eval_shards(self):
return 1 | ['def', 'num_eval_shards(self):', 'return', '1'] | 965,039 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | __init__.py | Menu.type | type | Return the type of the menu item at INDEX. | [
"Return",
"the",
"type",
"of",
"the",
"menu",
"item",
"at",
"INDEX."
] | def type(self, index):
return self.tk.call(self._w, 'type', index) | ['def', 'type(self,', 'index):', 'return', 'self.tk.call(self._w,', "'type',", 'index)'] | 377,027 |
softwarearchitect817/Efficient-Geometry-aware-3D | util.py | construct_class_by_name | construct_class_by_name | Finds the python class with the given name and constructs it with the given arguments. | [
"Finds",
"the",
"python",
"class",
"with",
"the",
"given",
"name",
"and",
"constructs",
"it",
"with",
"the",
"given",
"arguments."
] | def construct_class_by_name(*args, class_name: str=None, **kwargs) -> Any:
return call_func_by_name(*args, func_name=class_name, **kwargs) | ['def', 'construct_class_by_name(*args,', 'class_name:', 'str=None,', '**kwargs)', '->', 'Any:', 'return', 'call_func_by_name(*args,', 'func_name=class_name,', '**kwargs)'] | 548,613 |
jiewwantan/StarTrader | compare.py | Data_ScaleSplit.get_prediction | get_prediction | Get the model prediction, inverse transform scaling to get back to original price and reassemble the full XY dataframe. | [
"Get",
"the",
"model",
"prediction,",
"inverse",
"transform",
"scaling",
"to",
"get",
"back",
"to",
"original",
"price",
"and",
"reassemble",
"the",
"full",
"XY",
"dataframe."
] | def get_prediction(self, model_lstm):
predicted_y_lstm = model_lstm.predict(self.test_X, batch_size=None, verbose=0, steps=None)
trained_y_lstm = model_lstm.predict(self.train_X, batch_size=None, verbose=0, steps=None)
y_lstm = pd.DataFrame(data=np.vstack((trained_y_lstm, predicted_y_lstm)), columns=[c + '_... | ['def', 'get_prediction(self,', 'model_lstm):', 'predicted_y_lstm', '=', 'model_lstm.predict(self.test_X,', 'batch_size=None,', 'verbose=0,', 'steps=None)', 'trained_y_lstm', '=', 'model_lstm.predict(self.train_X,', 'batch_size=None,', 'verbose=0,', 'steps=None)', 'y_lstm', '=', 'pd.DataFrame(data=np.vstack((trained_y_... | 873,568 |
sek788432/Waymo-2D-Object-Detection | agent.py | action_embed_net | action_embed_net | Creates a simple feed forward net for embedding actions. | [
"Creates",
"a",
"simple",
"feed",
"forward",
"net",
"for",
"embedding",
"actions."
] | def action_embed_net(actions, states=None, num_output_dims=2, hidden_layers=(400, 300), normalizer_fn=None, activation_fn=tf.nn.relu, zero_time=True, images=False):
with slim.arg_scope([slim.fully_connected], activation_fn=activation_fn, normalizer_fn=normalizer_fn, weights_initializer=slim.variance_scaling_initial... | ['def', 'action_embed_net(actions,', 'states=None,', 'num_output_dims=2,', 'hidden_layers=(400,', '300),', 'normalizer_fn=None,', 'activation_fn=tf.nn.relu,', 'zero_time=True,', 'images=False):', 'with', 'slim.arg_scope([slim.fully_connected],', 'activation_fn=activation_fn,', 'normalizer_fn=normalizer_fn,', 'weights_i... | 974,307 |
mit-han-lab/hardware-aware-transformers | fairseq_optimizer.py | FairseqOptimizer.params | params | Return an iterable of the parameters held by the optimizer. | [
"Return",
"an",
"iterable",
"of",
"the",
"parameters",
"held",
"by",
"the",
"optimizer."
] | def params(self):
for param_group in self.optimizer.param_groups:
for p in param_group['params']:
yield p | ['def', 'params(self):', 'for', 'param_group', 'in', 'self.optimizer.param_groups:', 'for', 'p', 'in', "param_group['params']:", 'yield', 'p'] | 588,852 |
SamsungLabs/fcaf3d | base_points.py | BasePoints.color | color | Set the color of each point. | [
"Set",
"the",
"color",
"of",
"each",
"point."
] | def color(self, tensor):
try:
tensor = tensor.reshape(self.shape[0], 3)
except (RuntimeError, ValueError):
raise ValueError(f'got unexpected shape {tensor.shape}')
if tensor.max() >= 256 or tensor.min() < 0:
warnings.warn('point got color value beyond [0, 255]')
if not isinstance... | ['def', 'color(self,', 'tensor):', 'try:', 'tensor', '=', 'tensor.reshape(self.shape[0],', '3)', 'except', '(RuntimeError,', 'ValueError):', 'raise', "ValueError(f'got", 'unexpected', 'shape', "{tensor.shape}')", 'if', 'tensor.max()', '>=', '256', 'or', 'tensor.min()', '<', '0:', "warnings.warn('point", 'got', 'color',... | 560,248 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nb_007a.py | TextDataset.check_toks | check_toks | Checks if a new tokenization is needed. | [
"Checks",
"if",
"a",
"new",
"tokenization",
"is",
"needed."
] | def check_toks(self) -> bool:
if self.create_mtd >= TextMtd.TOK:
return True
if not self.general_check([self.csv_file], self.tok_files):
return False
with open(self.tok_files[1]) as f:
if repr(self.tokenizer) != f.read():
return False
return True | ['def', 'check_toks(self)', '->', 'bool:', 'if', 'self.create_mtd', '>=', 'TextMtd.TOK:', 'return', 'True', 'if', 'not', 'self.general_check([self.csv_file],', 'self.tok_files):', 'return', 'False', 'with', 'open(self.tok_files[1])', 'as', 'f:', 'if', 'repr(self.tokenizer)', '!=', 'f.read():', 'return', 'False', 'retur... | 81,584 |
sktime/sktime | test_mlflow_sktime_model_export.py | test_pyfunc_raises_invalid_dict_key | test_pyfunc_raises_invalid_dict_key | Test pyfunc raises exception with invalid dict key. | [
"Test",
"pyfunc",
"raises",
"exception",
"with",
"invalid",
"dict",
"key."
] | def test_pyfunc_raises_invalid_dict_key(auto_arima_model, model_path):
from mlflow.exceptions import MlflowException
from sktime.utils import mlflow_sktime
auto_arima_model.pyfunc_predict_conf = {'prediction_method': ['predict']}
mlflow_sktime.save_model(sktime_model=auto_arima_model, path=model_path)
... | ['def', 'test_pyfunc_raises_invalid_dict_key(auto_arima_model,', 'model_path):', 'from', 'mlflow.exceptions', 'import', 'MlflowException', 'from', 'sktime.utils', 'import', 'mlflow_sktime', 'auto_arima_model.pyfunc_predict_conf', '=', "{'prediction_method':", "['predict']}", 'mlflow_sktime.save_model(sktime_model=auto_... | 878,066 |
google-research/bleurt | downloaders.py | Importer1516.get_full_folder_path | get_full_folder_path | Returns path of directory with all the extracted files. | [
"Returns",
"path",
"of",
"directory",
"with",
"all",
"the",
"extracted",
"files."
] | def get_full_folder_path(self):
file_type = 'eval_data'
(folder_name, _, _) = self.location_info[file_type]
folder = os.path.join(self.temp_directory, folder_name)
return folder | ['def', 'get_full_folder_path(self):', 'file_type', '=', "'eval_data'", '(folder_name,', '_,', '_)', '=', 'self.location_info[file_type]', 'folder', '=', 'os.path.join(self.temp_directory,', 'folder_name)', 'return', 'folder'] | 461,749 |
alteryx/compose | plots.py | LabelPlots.distribution | distribution | Plots the label distribution. | [
"Plots",
"the",
"label",
"distribution."
] | def distribution(self, **kwargs):
self._label_times._assert_single_target()
target_column = self._label_times.target_columns[0]
dist = self._label_times[target_column]
is_discrete = self._label_times.is_discrete[target_column]
if is_discrete:
ax = sns.countplot(x=dist, palette=COLOR, **kwarg... | ['def', 'distribution(self,', '**kwargs):', 'self._label_times._assert_single_target()', 'target_column', '=', 'self._label_times.target_columns[0]', 'dist', '=', 'self._label_times[target_column]', 'is_discrete', '=', 'self._label_times.is_discrete[target_column]', 'if', 'is_discrete:', 'ax', '=', 'sns.countplot(x=dis... | 136,060 |
senarvi/theanolm | gpu.py | log_free_mem | log_free_mem | Writes the available GPU memory to the debug log. | [
"Writes",
"the",
"available",
"GPU",
"memory",
"to",
"the",
"debug",
"log."
] | def log_free_mem():
for name in theano.gpuarray.type.list_contexts():
context = theano.gpuarray.type.get_context(name)
free_mbytes = context.free_gmem / (1024 * 1024)
logging.debug('Available memory on GPU %s: %.0f MB', name, free_mbytes) | ['def', 'log_free_mem():', 'for', 'name', 'in', 'theano.gpuarray.type.list_contexts():', 'context', '=', 'theano.gpuarray.type.get_context(name)', 'free_mbytes', '=', 'context.free_gmem', '/', '(1024', '*', '1024)', "logging.debug('Available", 'memory', 'on', 'GPU', '%s:', '%.0f', "MB',", 'name,', 'free_mbytes)'] | 354,481 |
PKU-Alignment/safe-rlhf | chatbot.py | SpecialCommand.command | command | Get the command string. | [
"Get",
"the",
"command",
"string."
] | def command(self) -> str:
return self.value.partition(':')[0] | ['def', 'command(self)', '->', 'str:', 'return', "self.value.partition(':')[0]"] | 829,169 |
intra2net/guibot | test_fileresolver.py | FileResolverTest.test_search_type | test_search_type | Test that searching file names without extension works. | [
"Test",
"that",
"searching",
"file",
"names",
"without",
"extension",
"works."
] | def test_search_type(self):
self.resolver.add_path('images')
self.assertEqual(os.path.join('images', 'shape_black_box.png'), self.resolver.search('shape_black_box'))
self.assertEqual(os.path.join('images', 'mouse down.txt'), self.resolver.search('mouse down'))
self.assertEqual(os.path.join('images', 'ci... | ['def', 'test_search_type(self):', "self.resolver.add_path('images')", "self.assertEqual(os.path.join('images',", "'shape_black_box.png'),", "self.resolver.search('shape_black_box'))", "self.assertEqual(os.path.join('images',", "'mouse", "down.txt'),", "self.resolver.search('mouse", "down'))", "self.assertEqual(os.path... | 572,626 |
zcablii/LSKNet | test_misc.py | test_find_latest_checkpoint | test_find_latest_checkpoint | Test find latest checkpoint. | [
"Test",
"find",
"latest",
"checkpoint."
] | def test_find_latest_checkpoint():
with tempfile.TemporaryDirectory() as tmpdir:
path = tmpdir
latest = find_latest_checkpoint(path)
assert latest is None
path = tmpdir + '/none'
latest = find_latest_checkpoint(path)
assert latest is None | ['def', 'test_find_latest_checkpoint():', 'with', 'tempfile.TemporaryDirectory()', 'as', 'tmpdir:', 'path', '=', 'tmpdir', 'latest', '=', 'find_latest_checkpoint(path)', 'assert', 'latest', 'is', 'None', 'path', '=', 'tmpdir', '+', "'/none'", 'latest', '=', 'find_latest_checkpoint(path)', 'assert', 'latest', 'is', 'Non... | 616,271 |
ifwe/digsby | buddyliststore.py | display_copy | display_copy | Turns Groups into DGroups. | [
"Turns",
"Groups",
"into",
"DGroups."
] | def display_copy(group):
elems = []
for elem in group:
if isinstance(elem, Group):
elems.append(display_copy(elem))
else:
elems.append(elem)
return DGroup(group.name, [group.protocol], [group.id], elems) | ['def', 'display_copy(group):', 'elems', '=', '[]', 'for', 'elem', 'in', 'group:', 'if', 'isinstance(elem,', 'Group):', 'elems.append(display_copy(elem))', 'else:', 'elems.append(elem)', 'return', 'DGroup(group.name,', '[group.protocol],', '[group.id],', 'elems)'] | 185,193 |
aws/sagemaker-python-sdk | entities.py | _LocalTrainingJob.start | start | Starts a local training job. | [
"Starts",
"a",
"local",
"training",
"job."
] | def start(self, input_data_config, output_data_config, hyperparameters, environment, job_name):
for channel in input_data_config:
if channel['DataSource'] and 'S3DataSource' in channel['DataSource']:
data_distribution = channel['DataSource']['S3DataSource']['S3DataDistributionType']
... | ['def', 'start(self,', 'input_data_config,', 'output_data_config,', 'hyperparameters,', 'environment,', 'job_name):', 'for', 'channel', 'in', 'input_data_config:', 'if', "channel['DataSource']", 'and', "'S3DataSource'", 'in', "channel['DataSource']:", 'data_distribution', '=', "channel['DataSource']['S3DataSource']['S3... | 830,308 |
jimtin/Stock_Comparison | kernelbase.py | Kernel.getpass | getpass | Forward getpass to frontends Raises ------ StdinNotImplentedError if active frontend doesn't support stdin. | [
"Forward",
"getpass",
"to",
"frontends",
"Raises",
"------",
"StdinNotImplentedError",
"if",
"active",
"frontend",
"doesn't",
"support",
"stdin."
] | def getpass(self, prompt=''):
if not self._allow_stdin:
raise StdinNotImplementedError('getpass was called, but this frontend does not support input requests.')
return self._input_request(prompt, self._parent_ident, self._parent_header, password=True) | ['def', 'getpass(self,', "prompt=''):", 'if', 'not', 'self._allow_stdin:', 'raise', "StdinNotImplementedError('getpass", 'was', 'called,', 'but', 'this', 'frontend', 'does', 'not', 'support', 'input', "requests.')", 'return', 'self._input_request(prompt,', 'self._parent_ident,', 'self._parent_header,', 'password=True)'... | 384,453 |
alibaba-mmai-research/Masked-Action-Recognition | logging.py | get_logger | get_logger | Retrieve the logger with the specified name or, if name is None, return a logger which is the root logger of the hierarchy. | [
"Retrieve",
"the",
"logger",
"with",
"the",
"specified",
"name",
"or,",
"if",
"name",
"is",
"None,",
"return",
"a",
"logger",
"which",
"is",
"the",
"root",
"logger",
"of",
"the",
"hierarchy."
] | def get_logger(name):
return logging.getLogger(name) | ['def', 'get_logger(name):', 'return', 'logging.getLogger(name)'] | 629,026 |
befelix/safe_learning | functions.py | _Triangulation.parameters | parameters | Return the vertex values. | [
"Return",
"the",
"vertex",
"values."
] | def parameters(self):
return self._parameters | ['def', 'parameters(self):', 'return', 'self._parameters'] | 328,172 |
astooke/rlpyt | affinity.py | make_affinity | make_affinity | Input same kwargs as ``encode_affinity()``, returns the AttrDict form. | [
"Input",
"same",
"kwargs",
"as",
"``encode_affinity()``,",
"returns",
"the",
"AttrDict",
"form."
] | def make_affinity(run_slot=0, **kwargs):
return affinity_from_code(encode_affinity(run_slot=run_slot, **kwargs)) | ['def', 'make_affinity(run_slot=0,', '**kwargs):', 'return', 'affinity_from_code(encode_affinity(run_slot=run_slot,', '**kwargs))'] | 334,811 |
accel-brain/accel-brain-code | lstm_networks.py | LSTMNetworks.output_forward_propagate | output_forward_propagate | Forward propagation in output layer. | [
"Forward",
"propagation",
"in",
"output",
"layer."
] | def output_forward_propagate(self, pred_arr):
if self.__output_layer_flag is False:
return pred_arr
batch_size = pred_arr.shape[0]
seq_len = pred_arr.shape[1]
pred_arr = self.output_fc(torch.reshape(pred_arr, (batch_size, -1)))
if self.__output_activation == 'identity_adjusted':
pred... | ['def', 'output_forward_propagate(self,', 'pred_arr):', 'if', 'self.__output_layer_flag', 'is', 'False:', 'return', 'pred_arr', 'batch_size', '=', 'pred_arr.shape[0]', 'seq_len', '=', 'pred_arr.shape[1]', 'pred_arr', '=', 'self.output_fc(torch.reshape(pred_arr,', '(batch_size,', '-1)))', 'if', 'self.__output_activation... | 6,904 |
airbus/scikit-decide | scheduling_domains.py | SchedulingDomain.update_conditional_tasks_uncertain | update_conditional_tasks_uncertain | Update remaining tasks by checking conditions and potentially adding conditional tasks. | [
"Update",
"remaining",
"tasks",
"by",
"checking",
"conditions",
"and",
"potentially",
"adding",
"conditional",
"tasks."
] | def update_conditional_tasks_uncertain(self, states: DiscreteDistribution[State], action: SchedulingAction):
next_states = DiscreteDistribution([(state, prob) for (state, prob) in states.get_values()])
if action.time_progress:
for (next_state, _) in next_states.get_values():
all_available_ta... | ['def', 'update_conditional_tasks_uncertain(self,', 'states:', 'DiscreteDistribution[State],', 'action:', 'SchedulingAction):', 'next_states', '=', 'DiscreteDistribution([(state,', 'prob)', 'for', '(state,', 'prob)', 'in', 'states.get_values()])', 'if', 'action.time_progress:', 'for', '(next_state,', '_)', 'in', 'next_... | 847,880 |
dawdleryang/object_detection | FPN.py | add_fpn_rpn_outputs | add_fpn_rpn_outputs | Add RPN on FPN specific outputs. | [
"Add",
"RPN",
"on",
"FPN",
"specific",
"outputs."
] | def add_fpn_rpn_outputs(model, blobs_in, dim_in, spatial_scales):
num_anchors = len(cfg.FPN.RPN_ASPECT_RATIOS)
dim_out = dim_in
k_max = cfg.FPN.RPN_MAX_LEVEL
k_min = cfg.FPN.RPN_MIN_LEVEL
assert len(blobs_in) == k_max - k_min + 1
for lvl in range(k_min, k_max + 1):
bl_in = blobs_in[k_max... | ['def', 'add_fpn_rpn_outputs(model,', 'blobs_in,', 'dim_in,', 'spatial_scales):', 'num_anchors', '=', 'len(cfg.FPN.RPN_ASPECT_RATIOS)', 'dim_out', '=', 'dim_in', 'k_max', '=', 'cfg.FPN.RPN_MAX_LEVEL', 'k_min', '=', 'cfg.FPN.RPN_MIN_LEVEL', 'assert', 'len(blobs_in)', '==', 'k_max', '-', 'k_min', '+', '1', 'for', 'lvl', ... | 772,677 |
openvinotoolkit/training_extensions | coordinate.py | Coordinate.as_int_tuple | as_int_tuple | Convert the coordinates to a pair of integer coordinates (x,y). | [
"Convert",
"the",
"coordinates",
"to",
"a",
"pair",
"of",
"integer",
"coordinates",
"(x,y)."
] | def as_int_tuple(self) -> Tuple[int, int]:
return (int(self.x), int(self.y)) | ['def', 'as_int_tuple(self)', '->', 'Tuple[int,', 'int]:', 'return', '(int(self.x),', 'int(self.y))'] | 918,488 |
facebookresearch/CompilerGym | gcc_env.py | GccEnv.asm_size | asm_size | Get the assembly code size in bytes. | [
"Get",
"the",
"assembly",
"code",
"size",
"in",
"bytes."
] | def asm_size(self) -> int:
return self.observation['asm_size'] | ['def', 'asm_size(self)', '->', 'int:', 'return', "self.observation['asm_size']"] | 126,166 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | generate_videos.py | SmoothEmbeddings | SmoothEmbeddings | Temporally smoothes a sequence of embeddings. | [
"Temporally",
"smoothes",
"a",
"sequence",
"of",
"embeddings."
] | def SmoothEmbeddings(embs):
new_embs = []
window = int(FLAGS.smoothing_window)
for i in range(len(embs)):
min_i = max(i - window, 0)
max_i = min(i + window, len(embs))
new_embs.append(np.mean(embs[min_i:max_i, :], axis=0))
return np.array(new_embs) | ['def', 'SmoothEmbeddings(embs):', 'new_embs', '=', '[]', 'window', '=', 'int(FLAGS.smoothing_window)', 'for', 'i', 'in', 'range(len(embs)):', 'min_i', '=', 'max(i', '-', 'window,', '0)', 'max_i', '=', 'min(i', '+', 'window,', 'len(embs))', 'new_embs.append(np.mean(embs[min_i:max_i,', ':],', 'axis=0))', 'return', 'np.a... | 29,250 |
Katja-M/Python_NaturalLanguageProcessing | bezier.py | get_normal_points | get_normal_points | For a line passing through (*cx*, *cy*) and having an angle *t*, return locations of the two points located along its perpendicular line at the distance of *length*. | [
"For",
"a",
"line",
"passing",
"through",
"(*cx*,",
"*cy*)",
"and",
"having",
"an",
"angle",
"*t*,",
"return",
"locations",
"of",
"the",
"two",
"points",
"located",
"along",
"its",
"perpendicular",
"line",
"at",
"the",
"distance",
"of",
"*length*."
] | def get_normal_points(cx, cy, cos_t, sin_t, length):
if length == 0.0:
return (cx, cy, cx, cy)
(cos_t1, sin_t1) = (sin_t, -cos_t)
(cos_t2, sin_t2) = (-sin_t, cos_t)
(x1, y1) = (length * cos_t1 + cx, length * sin_t1 + cy)
(x2, y2) = (length * cos_t2 + cx, length * sin_t2 + cy)
return (x1,... | ['def', 'get_normal_points(cx,', 'cy,', 'cos_t,', 'sin_t,', 'length):', 'if', 'length', '==', '0.0:', 'return', '(cx,', 'cy,', 'cx,', 'cy)', '(cos_t1,', 'sin_t1)', '=', '(sin_t,', '-cos_t)', '(cos_t2,', 'sin_t2)', '=', '(-sin_t,', 'cos_t)', '(x1,', 'y1)', '=', '(length', '*', 'cos_t1', '+', 'cx,', 'length', '*', 'sin_t... | 864,363 |
zihuitang/medical_AI_platform | __init__.py | Canvas.create_rectangle | create_rectangle | Create rectangle with coordinates x1,y1,x2,y2. | [
"Create",
"rectangle",
"with",
"coordinates",
"x1,y1,x2,y2."
] | def create_rectangle(self, *args, **kw):
return self._create('rectangle', args, kw) | ['def', 'create_rectangle(self,', '*args,', '**kw):', 'return', "self._create('rectangle',", 'args,', 'kw)'] | 284,220 |
Caojunxu/AC-FPN | io.py | assert_cache_file_is_ok | assert_cache_file_is_ok | Check that cache file has the correct hash. | [
"Check",
"that",
"cache",
"file",
"has",
"the",
"correct",
"hash."
] | def assert_cache_file_is_ok(url, file_path):
cache_file_md5sum = _get_file_md5sum(file_path)
ref_md5sum = _get_reference_md5sum(url)
assert cache_file_md5sum == ref_md5sum, 'Target URL {} appears to be downloaded to the local cache file {}, but the md5 hash of the local file does not match the reference (ac... | ['def', 'assert_cache_file_is_ok(url,', 'file_path):', 'cache_file_md5sum', '=', '_get_file_md5sum(file_path)', 'ref_md5sum', '=', '_get_reference_md5sum(url)', 'assert', 'cache_file_md5sum', '==', 'ref_md5sum,', "'Target", 'URL', '{}', 'appears', 'to', 'be', 'downloaded', 'to', 'the', 'local', 'cache', 'file', '{},', ... | 406,563 |
cbokpark/Pytorch-Relational-Recurrent-- | data.py | Vocabulary.decode | decode | Convert a list of ids to a sentence, with space inserted. | [
"Convert",
"a",
"list",
"of",
"ids",
"to",
"a",
"sentence,",
"with",
"space",
"inserted."
] | def decode(self, cur_ids):
return ' '.join([self.id_to_word(cur_id) for cur_id in cur_ids]) | ['def', 'decode(self,', 'cur_ids):', 'return', "'", "'.join([self.id_to_word(cur_id)", 'for', 'cur_id', 'in', 'cur_ids])'] | 301,929 |
saymedia/remoteobjects | http.py | omit_nulls | omit_nulls | Strips `None` values from a dictionary or `RemoteObject` instance. | [
"Strips",
"`None`",
"values",
"from",
"a",
"dictionary",
"or",
"`RemoteObject`",
"instance."
] | def omit_nulls(data):
if not isinstance(data, dict):
if not hasattr(data, '__dict__'):
return str(data)
data = dict(data.__dict__)
for key in data.keys():
if data[key] is None:
del data[key]
return data | ['def', 'omit_nulls(data):', 'if', 'not', 'isinstance(data,', 'dict):', 'if', 'not', 'hasattr(data,', "'__dict__'):", 'return', 'str(data)', 'data', '=', 'dict(data.__dict__)', 'for', 'key', 'in', 'data.keys():', 'if', 'data[key]', 'is', 'None:', 'del', 'data[key]', 'return', 'data'] | 346,032 |
dibyaghosh/gcsl | group_config.py | TrackerGroupConfig.get_rot | get_rot | Returns the (3x3) rotation matrix of the element. | [
"Returns",
"the",
"(3x3)",
"rotation",
"matrix",
"of",
"the",
"element."
] | def get_rot(self, sim_scene: SimScene) -> np.ndarray:
if self.qpos_indices is not None:
qpos = sim_scene.data.qpos[self.qpos_indices[3:]]
if self._is_euler:
return euler2mat(*qpos, axes='rxyz')
return quat2mat(qpos)
return self.element_attr(sim_scene.data, 'xmat')[self.elemen... | ['def', 'get_rot(self,', 'sim_scene:', 'SimScene)', '->', 'np.ndarray:', 'if', 'self.qpos_indices', 'is', 'not', 'None:', 'qpos', '=', 'sim_scene.data.qpos[self.qpos_indices[3:]]', 'if', 'self._is_euler:', 'return', 'euler2mat(*qpos,', "axes='rxyz')", 'return', 'quat2mat(qpos)', 'return', 'self.element_attr(sim_scene.d... | 201,790 |
RomanoLab/comptox_ai | ARCHIVE.py | GraphDeprecated.to_aop_subgraph | to_aop_subgraph | Algorithm for finding an AOP and building an induced subgraph of `self` that corresponds to the AOP's local network of concepts. | [
"Algorithm",
"for",
"finding",
"an",
"AOP",
"and",
"building",
"an",
"induced",
"subgraph",
"of",
"`self`",
"that",
"corresponds",
"to",
"the",
"AOP's",
"local",
"network",
"of",
"concepts."
] | def to_aop_subgraph(self, aop_name, interactive_search=False):
allowed_rel_types = ['ns0__aopContainsKE', 'ns0__aopHasMIE', 'ns0__aopCausesAO', 'ns0__altersBiologicalState', 'ns0__keyEventTriggers']
ensure_nx_available(self)
if interactive_search:
raise NotImplementedError
else:
self.tem... | ['def', 'to_aop_subgraph(self,', 'aop_name,', 'interactive_search=False):', 'allowed_rel_types', '=', "['ns0__aopContainsKE',", "'ns0__aopHasMIE',", "'ns0__aopCausesAO',", "'ns0__altersBiologicalState',", "'ns0__keyEventTriggers']", 'ensure_nx_available(self)', 'if', 'interactive_search:', 'raise', 'NotImplementedError... | 136,119 |
RasaHQ/rasa | server.py | requires_auth | requires_auth | Wraps a request handler with token authentication. | [
"Wraps",
"a",
"request",
"handler",
"with",
"token",
"authentication."
] | def requires_auth(app: Sanic, token: Optional[Text]=None) -> Callable[['SanicView'], 'SanicView']:
def decorator(f: 'SanicView') -> 'SanicView':
def conversation_id_from_args(args: Any, kwargs: Any) -> Optional[Text]:
argnames = rasa.shared.utils.common.arguments_of(f)
try:
... | ['def', 'requires_auth(app:', 'Sanic,', 'token:', 'Optional[Text]=None)', '->', "Callable[['SanicView'],", "'SanicView']:", 'def', 'decorator(f:', "'SanicView')", '->', "'SanicView':", 'def', 'conversation_id_from_args(args:', 'Any,', 'kwargs:', 'Any)', '->', 'Optional[Text]:', 'argnames', '=', 'rasa.shared.utils.commo... | 836,542 |
Kvatsx/Artificial-Intelligence-Assignments | transform_test.py | TransformModuleTest.test_threshold_set_behavior0 | test_threshold_set_behavior0 | raises an error when set_behavior=1 and set_color is not None, and dest_surf is not None. | [
"raises",
"an",
"error",
"when",
"set_behavior=1",
"and",
"set_color",
"is",
"not",
"None,",
"and",
"dest_surf",
"is",
"not",
"None."
] | def test_threshold_set_behavior0(self):
from pygame.transform import threshold
s1 = pygame.Surface((32, 32), SRCALPHA, 32)
s2 = pygame.Surface((32, 32), SRCALPHA, 32)
THRESHOLD_BEHAVIOR_COUNT = 0
self.assertRaises(TypeError, threshold, dest_surf=None, surf=s2, search_color=(30, 30, 30), threshold=(1... | ['def', 'test_threshold_set_behavior0(self):', 'from', 'pygame.transform', 'import', 'threshold', 's1', '=', 'pygame.Surface((32,', '32),', 'SRCALPHA,', '32)', 's2', '=', 'pygame.Surface((32,', '32),', 'SRCALPHA,', '32)', 'THRESHOLD_BEHAVIOR_COUNT', '=', '0', 'self.assertRaises(TypeError,', 'threshold,', 'dest_surf=Non... | 76,475 |
liber145/rlpack | base.py | Base.load_model | load_model | Load model from `save_path` if there exists. | [
"Load",
"model",
"from",
"`save_path`",
"if",
"there",
"exists."
] | def load_model(self):
latest_checkpoint = tf.train.latest_checkpoint(os.path.join(self.save_path, 'model'))
if latest_checkpoint:
print('## Loading model checkpoint {} ...'.format(latest_checkpoint))
self.saver.restore(self.sess, latest_checkpoint)
else:
print('## New start!') | ['def', 'load_model(self):', 'latest_checkpoint', '=', 'tf.train.latest_checkpoint(os.path.join(self.save_path,', "'model'))", 'if', 'latest_checkpoint:', "print('##", 'Loading', 'model', 'checkpoint', '{}', "...'.format(latest_checkpoint))", 'self.saver.restore(self.sess,', 'latest_checkpoint)', 'else:', "print('##", ... | 825,069 |
PacktPublishing/Hands-On-Artificial--for-Banking | test.py | Client.put | put | Like open but method is enforced to PUT. | [
"Like",
"open",
"but",
"method",
"is",
"enforced",
"to",
"PUT."
] | def put(self, *args, **kw):
kw['method'] = 'PUT'
return self.open(*args, **kw) | ['def', 'put(self,', '*args,', '**kw):', "kw['method']", '=', "'PUT'", 'return', 'self.open(*args,', '**kw)'] | 204,948 |
myothida/Supervised-Machine-Learning | fancy_getopt.py | FancyGetopt.generate_help | generate_help | Generate help text (a list of strings, one per suggested line of output) from the option table for this FancyGetopt object. | [
"Generate",
"help",
"text",
"(a",
"list",
"of",
"strings,",
"one",
"per",
"suggested",
"line",
"of",
"output)",
"from",
"the",
"option",
"table",
"for",
"this",
"FancyGetopt",
"object."
] | def generate_help(self, header=None):
max_opt = 0
for option in self.option_table:
long = option[0]
short = option[1]
l = len(long)
if long[-1] == '=':
l = l - 1
if short is not None:
l = l + 5
if l > max_opt:
max_opt = l
op... | ['def', 'generate_help(self,', 'header=None):', 'max_opt', '=', '0', 'for', 'option', 'in', 'self.option_table:', 'long', '=', 'option[0]', 'short', '=', 'option[1]', 'l', '=', 'len(long)', 'if', 'long[-1]', '==', "'=':", 'l', '=', 'l', '-', '1', 'if', 'short', 'is', 'not', 'None:', 'l', '=', 'l', '+', '5', 'if', 'l', ... | 447,099 |
uber/causalml | filters.py | FilterSelect.get_importance | get_importance | Rank features based on the chosen statistic of the interaction. | [
"Rank",
"features",
"based",
"on",
"the",
"chosen",
"statistic",
"of",
"the",
"interaction."
] | def get_importance(self, data, features, y_name, method, experiment_group_column='treatment_group_key', control_group='control', treatment_group='treatment', n_bins=5, null_impute=None, order=1, disp=False):
if method == 'F':
data = data[data[experiment_group_column].isin([control_group, treatment_group])]
... | ['def', 'get_importance(self,', 'data,', 'features,', 'y_name,', 'method,', "experiment_group_column='treatment_group_key',", "control_group='control',", "treatment_group='treatment',", 'n_bins=5,', 'null_impute=None,', 'order=1,', 'disp=False):', 'if', 'method', '==', "'F':", 'data', '=', 'data[data[experiment_group_c... | 456,410 |
Kvatsx/Artificial-Intelligence-Assignments | test_constrainedlayout.py | test_constrained_layout15 | test_constrained_layout15 | Test that rcparams work. | [
"Test",
"that",
"rcparams",
"work."
] | def test_constrained_layout15():
rcParams['figure.constrained_layout.use'] = True
(fig, axs) = plt.subplots(2, 2)
for ax in axs.flatten():
example_plot(ax, fontsize=12) | ['def', 'test_constrained_layout15():', "rcParams['figure.constrained_layout.use']", '=', 'True', '(fig,', 'axs)', '=', 'plt.subplots(2,', '2)', 'for', 'ax', 'in', 'axs.flatten():', 'example_plot(ax,', 'fontsize=12)'] | 1,486 |
llu0120/Geometry-Computer-Vision | FeatureMatching.py | FeatureMatching.rgb2gray | rgb2gray | Convert rgb image to grayscale. | [
"Convert",
"rgb",
"image",
"to",
"grayscale."
] | def rgb2gray(self, rgb):
return np.dot(rgb[..., :3], [0.299, 0.587, 0.114]) | ['def', 'rgb2gray(self,', 'rgb):', 'return', 'np.dot(rgb[...,', ':3],', '[0.299,', '0.587,', '0.114])'] | 557,093 |
apeterswu/RL4NMT | text_encoder.py | SubwordTextEncoder.dump | dump | Debugging dump of the current subtoken vocabulary. | [
"Debugging",
"dump",
"of",
"the",
"current",
"subtoken",
"vocabulary."
] | def dump(self):
subtoken_strings = [(i, s) for (s, i) in six.iteritems(self._subtoken_string_to_id)]
print(u', '.join((u"{0} : '{1}'".format(i, s) for (i, s) in sorted(subtoken_strings)))) | ['def', 'dump(self):', 'subtoken_strings', '=', '[(i,', 's)', 'for', '(s,', 'i)', 'in', 'six.iteritems(self._subtoken_string_to_id)]', "print(u',", '\'.join((u"{0}', ':', '\'{1}\'".format(i,', 's)', 'for', '(i,', 's)', 'in', 'sorted(subtoken_strings))))'] | 331,418 |
nahueespinosa/ai50 | minesweeper.py | MinesweeperAI.add_knowledge | add_knowledge | Called when the Minesweeper board tells us, for a given safe cell, how many neighboring cells have mines in them. | [
"Called",
"when",
"the",
"Minesweeper",
"board",
"tells",
"us,",
"for",
"a",
"given",
"safe",
"cell,",
"how",
"many",
"neighboring",
"cells",
"have",
"mines",
"in",
"them."
] | def add_knowledge(self, cell, count):
self.moves_made.add(cell)
self.safes.add(cell)
neighbors = self.get_neighbor_cells(cell[0], cell[1])
newCells = set()
for neighbor in neighbors:
if neighbor not in self.safes:
newCells.add(neighbor)
sentence = Sentence(newCells, count)
... | ['def', 'add_knowledge(self,', 'cell,', 'count):', 'self.moves_made.add(cell)', 'self.safes.add(cell)', 'neighbors', '=', 'self.get_neighbor_cells(cell[0],', 'cell[1])', 'newCells', '=', 'set()', 'for', 'neighbor', 'in', 'neighbors:', 'if', 'neighbor', 'not', 'in', 'self.safes:', 'newCells.add(neighbor)', 'sentence', '... | 85,469 |
calico/basenji | basenji_data_hic_read.py | read_blacklist | read_blacklist | Construct interval trees of blacklist regions for each chromosome. | [
"Construct",
"interval",
"trees",
"of",
"blacklist",
"regions",
"for",
"each",
"chromosome."
] | def read_blacklist(blacklist_bed, black_buffer=20):
black_chr_trees = {}
if blacklist_bed is not None and os.path.isfile(blacklist_bed):
for line in open(blacklist_bed):
a = line.split()
chrm = a[0]
start = max(0, int(a[1]) - black_buffer)
end = int(a[2]) ... | ['def', 'read_blacklist(blacklist_bed,', 'black_buffer=20):', 'black_chr_trees', '=', '{}', 'if', 'blacklist_bed', 'is', 'not', 'None', 'and', 'os.path.isfile(blacklist_bed):', 'for', 'line', 'in', 'open(blacklist_bed):', 'a', '=', 'line.split()', 'chrm', '=', 'a[0]', 'start', '=', 'max(0,', 'int(a[1])', '-', 'black_bu... | 94,756 |
jbwang1997/CrossKD | sim_ota_assigner.py | SimOTAAssigner.dynamic_k_matching | dynamic_k_matching | Use IoU and matching cost to calculate the dynamic top-k positive targets. | [
"Use",
"IoU",
"and",
"matching",
"cost",
"to",
"calculate",
"the",
"dynamic",
"top-k",
"positive",
"targets."
] | def dynamic_k_matching(self, cost: Tensor, pairwise_ious: Tensor, num_gt: int, valid_mask: Tensor) -> Tuple[Tensor, Tensor]:
matching_matrix = torch.zeros_like(cost, dtype=torch.uint8)
candidate_topk = min(self.candidate_topk, pairwise_ious.size(0))
(topk_ious, _) = torch.topk(pairwise_ious, candidate_topk,... | ['def', 'dynamic_k_matching(self,', 'cost:', 'Tensor,', 'pairwise_ious:', 'Tensor,', 'num_gt:', 'int,', 'valid_mask:', 'Tensor)', '->', 'Tuple[Tensor,', 'Tensor]:', 'matching_matrix', '=', 'torch.zeros_like(cost,', 'dtype=torch.uint8)', 'candidate_topk', '=', 'min(self.candidate_topk,', 'pairwise_ious.size(0))', '(topk... | 491,528 |
mj-will/nessai | test_flowmodel_base.py | test_sample_log_prob_alt_dist | test_sample_log_prob_alt_dist | Assert the alternate distribution is used. | [
"Assert",
"the",
"alternate",
"distribution",
"is",
"used."
] | def test_sample_log_prob_alt_dist(model):
z = torch.randn(5, 2)
x = torch.randn(5, 2)
log_prob = torch.randn(5)
log_j = torch.randn(5)
log_prob_expected = log_prob - log_j
model.model = MagicMock()
model.model.device = 'cpu'
model.model.eval = MagicMock()
model.model.base_distributio... | ['def', 'test_sample_log_prob_alt_dist(model):', 'z', '=', 'torch.randn(5,', '2)', 'x', '=', 'torch.randn(5,', '2)', 'log_prob', '=', 'torch.randn(5)', 'log_j', '=', 'torch.randn(5)', 'log_prob_expected', '=', 'log_prob', '-', 'log_j', 'model.model', '=', 'MagicMock()', 'model.model.device', '=', "'cpu'", 'model.model.... | 292,478 |
Eric3911/OpenAGI | schema.py | ServiceSchema.state_slots | state_slots | Set of slots which are permitted to be in the dialogue state. | [
"Set",
"of",
"slots",
"which",
"are",
"permitted",
"to",
"be",
"in",
"the",
"dialogue",
"state."
] | def state_slots(self) -> set:
state_slots = set()
for intent in self._schema_json['intents']:
state_slots.update(intent['required_slots'])
state_slots.update(intent['optional_slots'])
return state_slots | ['def', 'state_slots(self)', '->', 'set:', 'state_slots', '=', 'set()', 'for', 'intent', 'in', "self._schema_json['intents']:", "state_slots.update(intent['required_slots'])", "state_slots.update(intent['optional_slots'])", 'return', 'state_slots'] | 273,249 |
HoloClean/holoclean | dataset.py | Dataset.get_domain_info | get_domain_info | Returns (number of random variables, count of distinct values across all attributes). | [
"Returns",
"(number",
"of",
"random",
"variables,",
"count",
"of",
"distinct",
"values",
"across",
"all",
"attributes)."
] | def get_domain_info(self):
query = 'SELECT count(_vid_), max(domain_size) FROM %s' % AuxTables.cell_domain.name
res = self.engine.execute_query(query)
total_vars = int(res[0][0])
classes = int(res[0][1])
return (total_vars, classes) | ['def', 'get_domain_info(self):', 'query', '=', "'SELECT", 'count(_vid_),', 'max(domain_size)', 'FROM', "%s'", '%', 'AuxTables.cell_domain.name', 'res', '=', 'self.engine.execute_query(query)', 'total_vars', '=', 'int(res[0][0])', 'classes', '=', 'int(res[0][1])', 'return', '(total_vars,', 'classes)'] | 569,941 |
vturrisi/solo-learn | pretrain.py | add_and_assert_lightning_cfg | add_and_assert_lightning_cfg | Adds specific default values/checks for Pytorch Lightning config. | [
"Adds",
"specific",
"default",
"values/checks",
"for",
"Pytorch",
"Lightning",
"config."
] | def add_and_assert_lightning_cfg(cfg: omegaconf.DictConfig) -> omegaconf.DictConfig:
cfg.seed = omegaconf_select(cfg, 'seed', 5)
cfg.resume_from_checkpoint = omegaconf_select(cfg, 'resume_from_checkpoint', None)
cfg.strategy = omegaconf_select(cfg, 'strategy', None)
return cfg | ['def', 'add_and_assert_lightning_cfg(cfg:', 'omegaconf.DictConfig)', '->', 'omegaconf.DictConfig:', 'cfg.seed', '=', 'omegaconf_select(cfg,', "'seed',", '5)', 'cfg.resume_from_checkpoint', '=', 'omegaconf_select(cfg,', "'resume_from_checkpoint',", 'None)', 'cfg.strategy', '=', 'omegaconf_select(cfg,', "'strategy',", '... | 393,532 |
s3prl/s3prl | sliding_attn.py | global_attention_forward | global_attention_forward | Full/Global attention dot product as sliding attention with full-utterance window size. | [
"Full/Global",
"attention",
"dot",
"product",
"as",
"sliding",
"attention",
"with",
"full-utterance",
"window",
"size."
] | def global_attention_forward(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_mask=None, key_padding_mask=None, num_heads=None, dropout_p=0, training=False):
attn_weights = torch.bmm(q, k.transpose(1, 2))
attn_mask = merge_padding_attm_mask(attn_mask, key_padding_mask, num_heads, q.size(1))
if attn_m... | ['def', 'global_attention_forward(q:', 'torch.Tensor,', 'k:', 'torch.Tensor,', 'v:', 'torch.Tensor,', 'attn_mask=None,', 'key_padding_mask=None,', 'num_heads=None,', 'dropout_p=0,', 'training=False):', 'attn_weights', '=', 'torch.bmm(q,', 'k.transpose(1,', '2))', 'attn_mask', '=', 'merge_padding_attm_mask(attn_mask,', ... | 327,743 |
zihuitang/medical_AI_platform | clinic.py | IndentStack.indent | indent | Indents a line by the currently defined margin. | [
"Indents",
"a",
"line",
"by",
"the",
"currently",
"defined",
"margin."
] | def indent(self, line):
return self.margin + line | ['def', 'indent(self,', 'line):', 'return', 'self.margin', '+', 'line'] | 284,719 |
jeromewang-github/computer_vision | text_dataflow.py | get_roidb | get_roidb | Load generated numpy dataset for tensorpack dataflow. | [
"Load",
"generated",
"numpy",
"dataset",
"for",
"tensorpack",
"dataflow."
] | def get_roidb(dataset_name):
dataset = np.load(dataset_name)[()]
(filenames, labels, masks, bboxes, points) = (dataset['filenames'], dataset['labels'], dataset['masks'], dataset['bboxes'], dataset['points'])
roidb = []
for (filename, label, mask, bbox, polygon) in zip(filenames, labels, masks, bboxes, p... | ['def', 'get_roidb(dataset_name):', 'dataset', '=', 'np.load(dataset_name)[()]', '(filenames,', 'labels,', 'masks,', 'bboxes,', 'points)', '=', "(dataset['filenames'],", "dataset['labels'],", "dataset['masks'],", "dataset['bboxes'],", "dataset['points'])", 'roidb', '=', '[]', 'for', '(filename,', 'label,', 'mask,', 'bb... | 501,445 |
csuhan/ReDet | utils.py | validate_clockwise_points | validate_clockwise_points | Validates that the points that the 4 points that dlimite a polygon are in clockwise order. | [
"Validates",
"that",
"the",
"points",
"that",
"the",
"4",
"points",
"that",
"dlimite",
"a",
"polygon",
"are",
"in",
"clockwise",
"order."
] | def validate_clockwise_points(points):
if len(points) != 4:
raise Exception('Points list not valid.' + str(len(points)))
point = [[int(points[0][0]), int(points[0][1])], [int(points[1][0]), int(points[1][1])], [int(points[2][0]), int(points[2][1])], [int(points[3][0]), int(points[3][1])]]
edge = [(p... | ['def', 'validate_clockwise_points(points):', 'if', 'len(points)', '!=', '4:', 'raise', "Exception('Points", 'list', 'not', "valid.'", '+', 'str(len(points)))', 'point', '=', '[[int(points[0][0]),', 'int(points[0][1])],', '[int(points[1][0]),', 'int(points[1][1])],', '[int(points[2][0]),', 'int(points[2][1])],', '[int(... | 832,545 |
tensorflow/quantum | util_test.py | UtilFunctionsTest.test_get_circuit_symbols_all | test_get_circuit_symbols_all | Confirm that circuits have all the requested symbols. | [
"Confirm",
"that",
"circuits",
"have",
"all",
"the",
"requested",
"symbols."
] | def test_get_circuit_symbols_all(self):
expected_symbols = ['alpha', 'beta', 'gamma', 'omega']
qubits = cirq.GridQubit.rect(1, 2)
n_moments = 1
for _ in range(5):
test_circuit = util.random_symbol_circuit(qubits, expected_symbols, n_moments=n_moments)
extracted_symbols = util.get_circuit... | ['def', 'test_get_circuit_symbols_all(self):', 'expected_symbols', '=', "['alpha',", "'beta',", "'gamma',", "'omega']", 'qubits', '=', 'cirq.GridQubit.rect(1,', '2)', 'n_moments', '=', '1', 'for', '_', 'in', 'range(5):', 'test_circuit', '=', 'util.random_symbol_circuit(qubits,', 'expected_symbols,', 'n_moments=n_moment... | 835,167 |
rlworkgroup/garage | trainer.py | Trainer.obtain_episodes | obtain_episodes | Obtain one batch of episodes. | [
"Obtain",
"one",
"batch",
"of",
"episodes."
] | def obtain_episodes(self, itr, batch_size=None, agent_update=None, env_update=None):
if self._sampler is None:
raise ValueError('trainer was not initialized with `sampler`. the algo should have a `_sampler` field when`setup()` is called')
if batch_size is None and self._train_args.batch_size is None:
... | ['def', 'obtain_episodes(self,', 'itr,', 'batch_size=None,', 'agent_update=None,', 'env_update=None):', 'if', 'self._sampler', 'is', 'None:', 'raise', "ValueError('trainer", 'was', 'not', 'initialized', 'with', '`sampler`.', 'the', 'algo', 'should', 'have', 'a', '`_sampler`', 'field', 'when`setup()`', 'is', "called')",... | 200,117 |
cvjena/PartDetectorDisovery | puff.py | Puff.num_data | num_data | Return the number of data. | [
"Return",
"the",
"number",
"of",
"data."
] | def num_data(self):
return self._num_data | ['def', 'num_data(self):', 'return', 'self._num_data'] | 278,318 |
tensorly/quantum | noisy_pqc_test.py | NoisyPQCTest.test_noisy_pqc_model_circuit_error | test_noisy_pqc_model_circuit_error | Test that invalid circuits error properly. | [
"Test",
"that",
"invalid",
"circuits",
"error",
"properly."
] | def test_noisy_pqc_model_circuit_error(self):
qubit = cirq.GridQubit(0, 0)
no_symbols = cirq.Circuit(cirq.X(qubit))
with self.assertRaisesRegex(TypeError, expected_regex='model_circuit must be a cirq.Circuit'):
noisy_pqc.NoisyPQC('junk', cirq.Z(qubit), repetitions=1000, sample_based=False)
with ... | ['def', 'test_noisy_pqc_model_circuit_error(self):', 'qubit', '=', 'cirq.GridQubit(0,', '0)', 'no_symbols', '=', 'cirq.Circuit(cirq.X(qubit))', 'with', 'self.assertRaisesRegex(TypeError,', "expected_regex='model_circuit", 'must', 'be', 'a', "cirq.Circuit'):", "noisy_pqc.NoisyPQC('junk',", 'cirq.Z(qubit),', 'repetitions... | 835,406 |
lujiazho/SegDrawer | amg.py | build_all_layer_point_grids | build_all_layer_point_grids | Generates point grids for all crop layers. | [
"Generates",
"point",
"grids",
"for",
"all",
"crop",
"layers."
] | def build_all_layer_point_grids(n_per_side: int, n_layers: int, scale_per_layer: int) -> List[np.ndarray]:
points_by_layer = []
for i in range(n_layers + 1):
n_points = int(n_per_side / scale_per_layer ** i)
points_by_layer.append(build_point_grid(n_points))
return points_by_layer | ['def', 'build_all_layer_point_grids(n_per_side:', 'int,', 'n_layers:', 'int,', 'scale_per_layer:', 'int)', '->', 'List[np.ndarray]:', 'points_by_layer', '=', '[]', 'for', 'i', 'in', 'range(n_layers', '+', '1):', 'n_points', '=', 'int(n_per_side', '/', 'scale_per_layer', '**', 'i)', 'points_by_layer.append(build_point_... | 842,209 |
nosmokingbandit/watcher | client.py | Client.locate_torrent_data | locate_torrent_data | Locate torrent data at the provided location. | [
"Locate",
"torrent",
"data",
"at",
"the",
"provided",
"location."
] | def locate_torrent_data(self, ids, location, timeout=None):
self._rpc_version_warning(6)
args = {'location': location, 'move': False}
self._request('torrent-set-location', args, ids, True, timeout=timeout) | ['def', 'locate_torrent_data(self,', 'ids,', 'location,', 'timeout=None):', 'self._rpc_version_warning(6)', 'args', '=', "{'location':", 'location,', "'move':", 'False}', "self._request('torrent-set-location',", 'args,', 'ids,', 'True,', 'timeout=timeout)'] | 381,965 |
Speedwagon13/CS-3600-Introduction-to-- | quoprimime.py | body_quopri_len | body_quopri_len | Return the length of str when it is encoded with body quopri. | [
"Return",
"the",
"length",
"of",
"str",
"when",
"it",
"is",
"encoded",
"with",
"body",
"quopri."
] | def body_quopri_len(str):
count = 0
for c in str:
if bqre.match(c):
count += 3
else:
count += 1
return count | ['def', 'body_quopri_len(str):', 'count', '=', '0', 'for', 'c', 'in', 'str:', 'if', 'bqre.match(c):', 'count', '+=', '3', 'else:', 'count', '+=', '1', 'return', 'count'] | 140,176 |
Nrgeup/EasyNLP | model.py | clones | clones | Produce N identical layers. | [
"Produce",
"N",
"identical",
"layers."
] | def clones(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) | ['def', 'clones(module,', 'N):', 'return', 'nn.ModuleList([copy.deepcopy(module)', 'for', '_', 'in', 'range(N)])'] | 546,964 |
benedekrozemberczki/GraphWave | spectral_machinery.py | WaveletMachine.create_embedding | create_embedding | Depending the mechanism setting creating an exact or approximate embedding. | [
"Depending",
"the",
"mechanism",
"setting",
"creating",
"an",
"exact",
"or",
"approximate",
"embedding."
] | def create_embedding(self):
if self.settings.mechanism == 'exact':
self.exact_structural_wavelet_embedding()
else:
self.approximate_structural_wavelet_embedding() | ['def', 'create_embedding(self):', 'if', 'self.settings.mechanism', '==', "'exact':", 'self.exact_structural_wavelet_embedding()', 'else:', 'self.approximate_structural_wavelet_embedding()'] | 580,825 |
ifwe/digsby | UberButton.py | UberButton.CallMenu | CallMenu | Click (down then up) handling. | [
"Click",
"(down",
"then",
"up)",
"handling."
] | def CallMenu(self):
self.Active()
if self.active:
event = wx.MenuEvent(wx.wxEVT_MENU_OPEN, -1)
event.SetEventObject(self.menu)
self.Top.ProcessEvent(event)
self.ReleaseAllCapture()
self.menu.Display(self) | ['def', 'CallMenu(self):', 'self.Active()', 'if', 'self.active:', 'event', '=', 'wx.MenuEvent(wx.wxEVT_MENU_OPEN,', '-1)', 'event.SetEventObject(self.menu)', 'self.Top.ProcessEvent(event)', 'self.ReleaseAllCapture()', 'self.menu.Display(self)'] | 185,653 |
sktime/sktime | test_mlflow_sktime_model_export.py | test_auto_arima_model_save_and_load | test_auto_arima_model_save_and_load | Test saving and loading of native sktime auto_arima_model. | [
"Test",
"saving",
"and",
"loading",
"of",
"native",
"sktime",
"auto_arima_model."
] | def test_auto_arima_model_save_and_load(auto_arima_model, model_path, serialization_format):
from sktime.utils import mlflow_sktime
mlflow_sktime.save_model(sktime_model=auto_arima_model, path=model_path, serialization_format=serialization_format)
loaded_model = mlflow_sktime.load_model(model_uri=model_path... | ['def', 'test_auto_arima_model_save_and_load(auto_arima_model,', 'model_path,', 'serialization_format):', 'from', 'sktime.utils', 'import', 'mlflow_sktime', 'mlflow_sktime.save_model(sktime_model=auto_arima_model,', 'path=model_path,', 'serialization_format=serialization_format)', 'loaded_model', '=', 'mlflow_sktime.lo... | 878,052 |
DLR-RM/stable-baselines3 | test_vec_stacked_obs.py | test_compute_stacking_image_channel_first | test_compute_stacking_image_channel_first | Detect that image is channel first and stack in that dimension. | [
"Detect",
"that",
"image",
"is",
"channel",
"first",
"and",
"stack",
"in",
"that",
"dimension."
] | def test_compute_stacking_image_channel_first():
space = spaces.Box(0, 255, (C, H, W), dtype=np.uint8)
(channels_first, stack_dimension, stacked_shape, repeat_axis) = compute_stacking(N_STACK, observation_space=space)
assert channels_first
assert stack_dimension == 1
assert stacked_shape == (N_STACK... | ['def', 'test_compute_stacking_image_channel_first():', 'space', '=', 'spaces.Box(0,', '255,', '(C,', 'H,', 'W),', 'dtype=np.uint8)', '(channels_first,', 'stack_dimension,', 'stacked_shape,', 'repeat_axis)', '=', 'compute_stacking(N_STACK,', 'observation_space=space)', 'assert', 'channels_first', 'assert', 'stack_dimen... | 383,298 |
chribsen/simple-machine-learning-examples | test_basic.py | test_no_scripts | test_no_scripts | Make sure entry point scripts are not generated. | [
"Make",
"sure",
"entry",
"point",
"scripts",
"are",
"not",
"generated."
] | def test_no_scripts():
dist = 'complex-dist'
basedir = pkg_resources.resource_filename('wheel.test', dist)
for (dirname, subdirs, filenames) in os.walk(basedir):
for filename in filenames:
if filename.endswith('.whl'):
whl = ZipFile(os.path.join(dirname, filename))
... | ['def', 'test_no_scripts():', 'dist', '=', "'complex-dist'", 'basedir', '=', "pkg_resources.resource_filename('wheel.test',", 'dist)', 'for', '(dirname,', 'subdirs,', 'filenames)', 'in', 'os.walk(basedir):', 'for', 'filename', 'in', 'filenames:', 'if', "filename.endswith('.whl'):", 'whl', '=', 'ZipFile(os.path.join(dir... | 883,089 |
catlab-team/latentclr | util.py | get_top_level_function_name | get_top_level_function_name | Return the fully-qualified name of a top-level function. | [
"Return",
"the",
"fully-qualified",
"name",
"of",
"a",
"top-level",
"function."
] | def get_top_level_function_name(obj: Any) -> str:
assert is_top_level_function(obj)
return obj.__module__ + '.' + obj.__name__ | ['def', 'get_top_level_function_name(obj:', 'Any)', '->', 'str:', 'assert', 'is_top_level_function(obj)', 'return', 'obj.__module__', '+', "'.'", '+', 'obj.__name__'] | 261,946 |
txie-93/cdvae | scaling.py | AutomaticFit.set_next_active | set_next_active | Set the next variable in the queue that should be fitted. | [
"Set",
"the",
"next",
"variable",
"in",
"the",
"queue",
"that",
"should",
"be",
"fitted."
] | def set_next_active(self):
queue = AutomaticFit.queue
if len(queue) == 0:
logging.debug('Processed all variables.')
AutomaticFit.queue = None
AutomaticFit.activeVar = None
return
AutomaticFit.activeVar = queue.pop(0) | ['def', 'set_next_active(self):', 'queue', '=', 'AutomaticFit.queue', 'if', 'len(queue)', '==', '0:', "logging.debug('Processed", 'all', "variables.')", 'AutomaticFit.queue', '=', 'None', 'AutomaticFit.activeVar', '=', 'None', 'return', 'AutomaticFit.activeVar', '=', 'queue.pop(0)'] | 457,369 |
greydanus/mr_london | tests.py | test_undefined | test_undefined | Like :func:`defined` but the other way round. | [
"Like",
":func:`defined`",
"but",
"the",
"other",
"way",
"round."
] | def test_undefined(value):
return isinstance(value, Undefined) | ['def', 'test_undefined(value):', 'return', 'isinstance(value,', 'Undefined)'] | 262,455 |
brjathu/SKD | resnet.py | seresnet12 | seresnet12 | Constructs a ResNet-12 model. | [
"Constructs",
"a",
"ResNet-12",
"model."
] | def seresnet12(keep_prob=1.0, avg_pool=False, **kwargs):
model = ResNet(BasicBlock, [1, 1, 1, 1], keep_prob=keep_prob, avg_pool=avg_pool, use_se=True, **kwargs)
return model | ['def', 'seresnet12(keep_prob=1.0,', 'avg_pool=False,', '**kwargs):', 'model', '=', 'ResNet(BasicBlock,', '[1,', '1,', '1,', '1],', 'keep_prob=keep_prob,', 'avg_pool=avg_pool,', 'use_se=True,', '**kwargs)', 'return', 'model'] | 350,894 |
instadeepai/jumanji | utils.py | build_adjecency_matrix | build_adjecency_matrix | Build adjaceny matrix from an array with edges. | [
"Build",
"adjaceny",
"matrix",
"from",
"an",
"array",
"with",
"edges."
] | def build_adjecency_matrix(num_nodes: int, edges: jnp.ndarray) -> jnp.ndarray:
adj_matrix = jnp.zeros((num_nodes, num_nodes), dtype=int)
adj_matrix = adj_matrix.at[edges[:, 0], edges[:, 1]].set(1)
adj_matrix = adj_matrix.at[edges[:, 1], edges[:, 0]].set(1)
return adj_matrix | ['def', 'build_adjecency_matrix(num_nodes:', 'int,', 'edges:', 'jnp.ndarray)', '->', 'jnp.ndarray:', 'adj_matrix', '=', 'jnp.zeros((num_nodes,', 'num_nodes),', 'dtype=int)', 'adj_matrix', '=', 'adj_matrix.at[edges[:,', '0],', 'edges[:,', '1]].set(1)', 'adj_matrix', '=', 'adj_matrix.at[edges[:,', '1],', 'edges[:,', '0]]... | 594,403 |
rudranil723/mini-main | defaulttags.py | autoescape | autoescape | Force autoescape behavior for this block. | [
"Force",
"autoescape",
"behavior",
"for",
"this",
"block."
] | def autoescape(parser, token):
args = token.contents.split()
if len(args) != 2:
raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.")
arg = args[1]
if arg not in ('on', 'off'):
raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'")
nodelist ... | ['def', 'autoescape(parser,', 'token):', 'args', '=', 'token.contents.split()', 'if', 'len(args)', '!=', '2:', 'raise', 'TemplateSyntaxError("\'autoescape\'', 'tag', 'requires', 'exactly', 'one', 'argument.")', 'arg', '=', 'args[1]', 'if', 'arg', 'not', 'in', "('on',", "'off'):", 'raise', 'TemplateSyntaxError("\'autoes... | 316,441 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | offsetbox.py | OffsetBox.get_extent | get_extent | Return a tuple ``width, height, xdescent, ydescent`` of the box. | [
"Return",
"a",
"tuple",
"``width,",
"height,",
"xdescent,",
"ydescent``",
"of",
"the",
"box."
] | def get_extent(self, renderer):
(w, h, xd, yd, offsets) = self.get_extent_offsets(renderer)
return (w, h, xd, yd) | ['def', 'get_extent(self,', 'renderer):', '(w,', 'h,', 'xd,', 'yd,', 'offsets)', '=', 'self.get_extent_offsets(renderer)', 'return', '(w,', 'h,', 'xd,', 'yd)'] | 306,864 |
nlp-uoregon/trankit | lemma_model.py | Trainer.postprocess | postprocess | Postprocess, mainly for handing edits. | [
"Postprocess,",
"mainly",
"for",
"handing",
"edits."
] | def postprocess(self, words, preds, edits=None):
assert len(words) == len(preds), 'Lemma predictions must have same length as words.'
edited = []
if self.args.get('edit', False):
assert edits is not None and len(words) == len(edits)
for (w, p, e) in zip(words, preds, edits):
lem ... | ['def', 'postprocess(self,', 'words,', 'preds,', 'edits=None):', 'assert', 'len(words)', '==', 'len(preds),', "'Lemma", 'predictions', 'must', 'have', 'same', 'length', 'as', "words.'", 'edited', '=', '[]', 'if', "self.args.get('edit',", 'False):', 'assert', 'edits', 'is', 'not', 'None', 'and', 'len(words)', '==', 'len... | 920,453 |
wandb/wandb | __init__.py | get_all_styles | get_all_styles | Return an generator for all styles by name, both builtin and plugin. | [
"Return",
"an",
"generator",
"for",
"all",
"styles",
"by",
"name,",
"both",
"builtin",
"and",
"plugin."
] | def get_all_styles():
for name in STYLE_MAP:
yield name
for (name, _) in find_plugin_styles():
yield name | ['def', 'get_all_styles():', 'for', 'name', 'in', 'STYLE_MAP:', 'yield', 'name', 'for', '(name,', '_)', 'in', 'find_plugin_styles():', 'yield', 'name'] | 942,103 |
Megvii-BaseDetection/DynamicRouting | catalog.py | DatasetCatalog.clear | clear | Remove all registered dataset. | [
"Remove",
"all",
"registered",
"dataset."
] | def clear():
DatasetCatalog._REGISTERED.clear() | ['def', 'clear():', 'DatasetCatalog._REGISTERED.clear()'] | 555,149 |
Kvatsx/Artificial-Intelligence-Assignments | backend_bases.py | NavigationToolbar2.zoom | zoom | Activate zoom to rect mode. | [
"Activate",
"zoom",
"to",
"rect",
"mode."
] | def zoom(self, *args):
if self._active == 'ZOOM':
self._active = None
else:
self._active = 'ZOOM'
if self._idPress is not None:
self._idPress = self.canvas.mpl_disconnect(self._idPress)
self.mode = ''
if self._idRelease is not None:
self._idRelease = self.canvas.m... | ['def', 'zoom(self,', '*args):', 'if', 'self._active', '==', "'ZOOM':", 'self._active', '=', 'None', 'else:', 'self._active', '=', "'ZOOM'", 'if', 'self._idPress', 'is', 'not', 'None:', 'self._idPress', '=', 'self.canvas.mpl_disconnect(self._idPress)', 'self.mode', '=', "''", 'if', 'self._idRelease', 'is', 'not', 'None... | 275 |
weimin17/Object-Detection_HelmetDetection | transformer_main.py | define_transformer_flags | define_transformer_flags | Add flags and flag validators for running transformer_main. | [
"Add",
"flags",
"and",
"flag",
"validators",
"for",
"running",
"transformer_main."
] | def define_transformer_flags():
flags_core.define_base(multi_gpu=False, num_gpu=False, export_dir=False)
flags_core.define_performance(num_parallel_calls=True, inter_op=False, intra_op=False, synthetic_data=False, max_train_steps=False, dtype=False)
flags_core.define_benchmark()
flags.adopt_module_key_f... | ['def', 'define_transformer_flags():', 'flags_core.define_base(multi_gpu=False,', 'num_gpu=False,', 'export_dir=False)', 'flags_core.define_performance(num_parallel_calls=True,', 'inter_op=False,', 'intra_op=False,', 'synthetic_data=False,', 'max_train_steps=False,', 'dtype=False)', 'flags_core.define_benchmark()', 'fl... | 748,706 |
jpmorganchase/Phantom | fsm.py | FiniteStateMachineEnv.view | view | Return an immutable view to the FSM environment's public state. | [
"Return",
"an",
"immutable",
"view",
"to",
"the",
"FSM",
"environment's",
"public",
"state."
] | def view(self, agent_views: Dict[AgentID, AgentView]) -> FSMEnvView:
return FSMEnvView(self.current_step, self.current_step / self.num_steps, self.current_stage) | ['def', 'view(self,', 'agent_views:', 'Dict[AgentID,', 'AgentView])', '->', 'FSMEnvView:', 'return', 'FSMEnvView(self.current_step,', 'self.current_step', '/', 'self.num_steps,', 'self.current_stage)'] | 768,697 |
intel/neural-compressor | utils.py | get_super_module_by_name | get_super_module_by_name | Get the father module with given name of child module. | [
"Get",
"the",
"father",
"module",
"with",
"given",
"name",
"of",
"child",
"module."
] | def get_super_module_by_name(model, module_name):
name_list = module_name.split('.')
for name in name_list[:-1]:
if hasattr(model, name):
model = getattr(model, name)
else:
return None
if hasattr(model, name_list[-1]):
return model
else:
return Non... | ['def', 'get_super_module_by_name(model,', 'module_name):', 'name_list', '=', "module_name.split('.')", 'for', 'name', 'in', 'name_list[:-1]:', 'if', 'hasattr(model,', 'name):', 'model', '=', 'getattr(model,', 'name)', 'else:', 'return', 'None', 'if', 'hasattr(model,', 'name_list[-1]):', 'return', 'model', 'else:', 're... | 737,946 |
ZumoLabs/zpy | objects.py | load_blend_obj | load_blend_obj | Load object from blend file. | [
"Load",
"object",
"from",
"blend",
"file."
] | def load_blend_obj(name: str, path: Union[Path, str], link: bool=False) -> bpy.types.Object:
path = zpy.files.verify_path(path, make=False)
scene = zpy.blender.verify_blender_scene()
with bpy.data.libraries.load(str(path), link=link) as (data_from, data_to):
for from_obj in data_from.objects:
... | ['def', 'load_blend_obj(name:', 'str,', 'path:', 'Union[Path,', 'str],', 'link:', 'bool=False)', '->', 'bpy.types.Object:', 'path', '=', 'zpy.files.verify_path(path,', 'make=False)', 'scene', '=', 'zpy.blender.verify_blender_scene()', 'with', 'bpy.data.libraries.load(str(path),', 'link=link)', 'as', '(data_from,', 'dat... | 972,073 |
benedekrozemberczki/karateclub | community_detection_nonoverlapping_test.py | test_label_propagation | test_label_propagation | Test Label Propagation procedure. | [
"Test",
"Label",
"Propagation",
"procedure."
] | def test_label_propagation():
graph = nx.newman_watts_strogatz_graph(50, 5, 0.3)
model = LabelPropagation()
model.fit(graph)
memberships = model.get_memberships()
indices = [k for (k, v) in memberships.items()].sort()
nodes = [node for node in graph.nodes()].sort()
assert graph.number_of_nod... | ['def', 'test_label_propagation():', 'graph', '=', 'nx.newman_watts_strogatz_graph(50,', '5,', '0.3)', 'model', '=', 'LabelPropagation()', 'model.fit(graph)', 'memberships', '=', 'model.get_memberships()', 'indices', '=', '[k', 'for', '(k,', 'v)', 'in', 'memberships.items()].sort()', 'nodes', '=', '[node', 'for', 'node... | 247,399 |
myothida/Supervised-Machine-Learning | core.py | disable_diag | disable_diag | Disable a global pyparsing diagnostic flag (see :class:`Diagnostics`). | [
"Disable",
"a",
"global",
"pyparsing",
"diagnostic",
"flag",
"(see",
":class:`Diagnostics`)."
] | def disable_diag(diag_enum: Diagnostics) -> None:
__diag__.disable(diag_enum.name) | ['def', 'disable_diag(diag_enum:', 'Diagnostics)', '->', 'None:', '__diag__.disable(diag_enum.name)'] | 445,470 |
caiostringari/deepwaves | predict.py | display_mask | display_mask | Display a model's prediction. | [
"Display",
"a",
"model's",
"prediction."
] | def display_mask(val_preds, i):
mask = np.argmax(val_preds[i], axis=-1)
mask = np.expand_dims(mask, axis=-1)
return mask | ['def', 'display_mask(val_preds,', 'i):', 'mask', '=', 'np.argmax(val_preds[i],', 'axis=-1)', 'mask', '=', 'np.expand_dims(mask,', 'axis=-1)', 'return', 'mask'] | 540,956 |
OpenMDAO/OpenMDAO-Framework | domain.py | DomainObj.copy | copy | Returns a deep copy of self. | [
"Returns",
"a",
"deep",
"copy",
"of",
"self."
] | def copy(self):
return copy.deepcopy(self) | ['def', 'copy(self):', 'return', 'copy.deepcopy(self)'] | 275,459 |
enyac-group/NeuralPower | flops_profiler.py | FlopsProfiler.profile_apply_updates | profile_apply_updates | Time for update all model parameters. | [
"Time",
"for",
"update",
"all",
"model",
"parameters."
] | def profile_apply_updates(self, params_in_bytes):
num_parameters = params_in_bytes // 4
flops = 2 * num_parameters
comp_time = self._estimate_comp_time(flops)
comm_time = 3 * self._estimate_comm_time(params_in_bytes)
return TimeMeasure(comp_time=comp_time, comm_time=comm_time) | ['def', 'profile_apply_updates(self,', 'params_in_bytes):', 'num_parameters', '=', 'params_in_bytes', '//', '4', 'flops', '=', '2', '*', 'num_parameters', 'comp_time', '=', 'self._estimate_comp_time(flops)', 'comm_time', '=', '3', '*', 'self._estimate_comm_time(params_in_bytes)', 'return', 'TimeMeasure(comp_time=comp_t... | 293,464 |
SamsungLabs/fcaf3d | min_enclosing_box.py | smallest_bounding_box | smallest_bounding_box | return width and length of the smallest bouding box which encloses two boxes. | [
"return",
"width",
"and",
"length",
"of",
"the",
"smallest",
"bouding",
"box",
"which",
"encloses",
"two",
"boxes."
] | def smallest_bounding_box(corners: torch.Tensor, verbose=False):
(lines, points, _, _) = gather_lines_points(corners)
proj = point_line_projection_range(lines, points)
dist = point_line_distance_range(lines, points)
area = proj * dist
zero_mask = (area == 0).type(corners.dtype)
fake = torch.ones... | ['def', 'smallest_bounding_box(corners:', 'torch.Tensor,', 'verbose=False):', '(lines,', 'points,', '_,', '_)', '=', 'gather_lines_points(corners)', 'proj', '=', 'point_line_projection_range(lines,', 'points)', 'dist', '=', 'point_line_distance_range(lines,', 'points)', 'area', '=', 'proj', '*', 'dist', 'zero_mask', '=... | 560,577 |
suarez12138/AI-Reversi_IMP_TextDichotomy | plot_directive.py | out_of_date | out_of_date | Return whether *derived* is out-of-date relative to *original*, both of which are full file paths. | [
"Return",
"whether",
"*derived*",
"is",
"out-of-date",
"relative",
"to",
"*original*,",
"both",
"of",
"which",
"are",
"full",
"file",
"paths."
] | def out_of_date(original, derived):
return not os.path.exists(derived) or (os.path.exists(original) and os.stat(derived).st_mtime < os.stat(original).st_mtime) | ['def', 'out_of_date(original,', 'derived):', 'return', 'not', 'os.path.exists(derived)', 'or', '(os.path.exists(original)', 'and', 'os.stat(derived).st_mtime', '<', 'os.stat(original).st_mtime)'] | 97,223 |
scikit-learn/scikit-learn | test_online_lda.py | test_lda_dtype_match | test_lda_dtype_match | Check data type preservation of fitted attributes. | [
"Check",
"data",
"type",
"preservation",
"of",
"fitted",
"attributes."
] | def test_lda_dtype_match(learning_method, global_dtype):
rng = np.random.RandomState(0)
X = rng.uniform(size=(20, 10)).astype(global_dtype, copy=False)
lda = LatentDirichletAllocation(n_components=5, random_state=0, learning_method=learning_method)
lda.fit(X)
assert lda.components_.dtype == global_d... | ['def', 'test_lda_dtype_match(learning_method,', 'global_dtype):', 'rng', '=', 'np.random.RandomState(0)', 'X', '=', 'rng.uniform(size=(20,', '10)).astype(global_dtype,', 'copy=False)', 'lda', '=', 'LatentDirichletAllocation(n_components=5,', 'random_state=0,', 'learning_method=learning_method)', 'lda.fit(X)', 'assert'... | 853,071 |
sercant/mobile-segmentation | utils.py | scale_dimension | scale_dimension | Scales the input dimension. | [
"Scales",
"the",
"input",
"dimension."
] | def scale_dimension(dim, scale):
if isinstance(dim, tf.Tensor):
return tf.cast((tf.cast(dim, tf.float32) - 1.0) * scale + 1.0, dtype=tf.int32)
else:
return int((float(dim) - 1.0) * scale + 1.0) | ['def', 'scale_dimension(dim,', 'scale):', 'if', 'isinstance(dim,', 'tf.Tensor):', 'return', 'tf.cast((tf.cast(dim,', 'tf.float32)', '-', '1.0)', '*', 'scale', '+', '1.0,', 'dtype=tf.int32)', 'else:', 'return', 'int((float(dim)', '-', '1.0)', '*', 'scale', '+', '1.0)'] | 626,146 |
sktime/sktime | _sfa_fast_numba.py | create_bag_feature_selection | create_bag_feature_selection | Create bag, feature selection. | [
"Create",
"bag,",
"feature",
"selection."
] | def create_bag_feature_selection(n_instances, relevant_features_idx, feature_names, sfa_words, remove_repeat_words):
relevant_features = Dict.empty(key_type=types.uint32, value_type=types.uint32)
for (k, v) in zip(feature_names[relevant_features_idx], np.arange(len(relevant_features_idx), dtype=np.uint32)):
... | ['def', 'create_bag_feature_selection(n_instances,', 'relevant_features_idx,', 'feature_names,', 'sfa_words,', 'remove_repeat_words):', 'relevant_features', '=', 'Dict.empty(key_type=types.uint32,', 'value_type=types.uint32)', 'for', '(k,', 'v)', 'in', 'zip(feature_names[relevant_features_idx],', 'np.arange(len(relevan... | 877,697 |
sek788432/Waymo-2D-Object-Detection | models_test.py | process_decoded_ids | process_decoded_ids | Transforms decoded tensors to lists ending with END_TOKEN_ID. | [
"Transforms",
"decoded",
"tensors",
"to",
"lists",
"ending",
"with",
"END_TOKEN_ID."
] | def process_decoded_ids(predictions, end_token_id):
if isinstance(predictions, tf.Tensor):
predictions = predictions.numpy()
flatten_ids = predictions.reshape((-1, predictions.shape[-1]))
results = []
for ids in flatten_ids:
ids = list(ids)
if end_token_id in ids:
ids... | ['def', 'process_decoded_ids(predictions,', 'end_token_id):', 'if', 'isinstance(predictions,', 'tf.Tensor):', 'predictions', '=', 'predictions.numpy()', 'flatten_ids', '=', 'predictions.reshape((-1,', 'predictions.shape[-1]))', 'results', '=', '[]', 'for', 'ids', 'in', 'flatten_ids:', 'ids', '=', 'list(ids)', 'if', 'en... | 972,740 |
palVikram/Machine-Learning-using-Python | function_module.py | alias_root | alias_root | Return the variable to which v is aliased by view_maps and destroy_maps. | [
"Return",
"the",
"variable",
"to",
"which",
"v",
"is",
"aliased",
"by",
"view_maps",
"and",
"destroy_maps."
] | def alias_root(v):
if v.owner is None:
return v
vmap = getattr(v.owner.op, 'view_map', {})
dmap = getattr(v.owner.op, 'destroy_map', {})
outpos = v.owner.outputs.index(v)
v_views = vmap.get(outpos, []) + dmap.get(outpos, [])
if len(v_views) > 1:
raise NotImplementedError(str(v) +... | ['def', 'alias_root(v):', 'if', 'v.owner', 'is', 'None:', 'return', 'v', 'vmap', '=', 'getattr(v.owner.op,', "'view_map',", '{})', 'dmap', '=', 'getattr(v.owner.op,', "'destroy_map',", '{})', 'outpos', '=', 'v.owner.outputs.index(v)', 'v_views', '=', 'vmap.get(outpos,', '[])', '+', 'dmap.get(outpos,', '[])', 'if', 'len... | 621,192 |
rudranil723/mini-main | utils.py | parse_rst | parse_rst | Convert the string from reST to an XHTML fragment. | [
"Convert",
"the",
"string",
"from",
"reST",
"to",
"an",
"XHTML",
"fragment."
] | def parse_rst(text, default_reference_context, thing_being_parsed=None):
overrides = {'doctitle_xform': True, 'initial_header_level': 3, 'default_reference_context': default_reference_context, 'link_base': reverse('django-admindocs-docroot').rstrip('/'), 'raw_enabled': False, 'file_insertion_enabled': False}
th... | ['def', 'parse_rst(text,', 'default_reference_context,', 'thing_being_parsed=None):', 'overrides', '=', "{'doctitle_xform':", 'True,', "'initial_header_level':", '3,', "'default_reference_context':", 'default_reference_context,', "'link_base':", "reverse('django-admindocs-docroot').rstrip('/'),", "'raw_enabled':", 'Fal... | 314,869 |
openvinotoolkit/datumaro | format_detection.py | FormatDetectionContext.raise_unsupported | raise_unsupported | Raises a `FormatDetectionUnsupported` exception to signal that the current format does not support detection. | [
"Raises",
"a",
"`FormatDetectionUnsupported`",
"exception",
"to",
"signal",
"that",
"the",
"current",
"format",
"does",
"not",
"support",
"detection."
] | def raise_unsupported(self) -> NoReturn:
raise FormatDetectionUnsupported | ['def', 'raise_unsupported(self)', '->', 'NoReturn:', 'raise', 'FormatDetectionUnsupported'] | 498,090 |
jpmorganchase/Phantom | env.py | PhantomEnv.is_truncated | is_truncated | Implements the logic to decide when the episode is truncated. | [
"Implements",
"the",
"logic",
"to",
"decide",
"when",
"the",
"episode",
"is",
"truncated."
] | def is_truncated(self) -> bool:
is_at_max_step = self.num_steps is not None and self.current_step == self.num_steps
return is_at_max_step or len(self._truncations) == len(self.strategic_agents) | ['def', 'is_truncated(self)', '->', 'bool:', 'is_at_max_step', '=', 'self.num_steps', 'is', 'not', 'None', 'and', 'self.current_step', '==', 'self.num_steps', 'return', 'is_at_max_step', 'or', 'len(self._truncations)', '==', 'len(self.strategic_agents)'] | 768,686 |
43Carrig/recurrent_neural_networks_practice | gen_data_flow_ops.py | ordered_map_incomplete_size | ordered_map_incomplete_size | Op returns the number of incomplete elements in the underlying container. | [
"Op",
"returns",
"the",
"number",
"of",
"incomplete",
"elements",
"in",
"the",
"underlying",
"container."
] | def ordered_map_incomplete_size(dtypes, capacity=0, memory_limit=0, container='', shared_name='', name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
if not isinstance(dtypes, (list, tuple)):
raise TypeError("Expected list for 'dtypes' argument to 'order... | ['def', 'ordered_map_incomplete_size(dtypes,', 'capacity=0,', 'memory_limit=0,', "container='',", "shared_name='',", 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(dtypes,', '(list,', 'tuple)):', 'raise', 'TypeError("Ex... | 337,714 |
FreshAirTonight/af2complex | data_transforms.py | squeeze_features | squeeze_features | Remove singleton and repeated dimensions in protein features. | [
"Remove",
"singleton",
"and",
"repeated",
"dimensions",
"in",
"protein",
"features."
] | def squeeze_features(protein):
protein['aatype'] = tf.argmax(protein['aatype'], axis=-1, output_type=tf.int32)
for k in ['domain_name', 'msa', 'num_alignments', 'seq_length', 'sequence', 'superfamily', 'deletion_matrix', 'resolution', 'between_segment_residues', 'residue_index', 'template_all_atom_masks']:
... | ['def', 'squeeze_features(protein):', "protein['aatype']", '=', "tf.argmax(protein['aatype'],", 'axis=-1,', 'output_type=tf.int32)', 'for', 'k', 'in', "['domain_name',", "'msa',", "'num_alignments',", "'seq_length',", "'sequence',", "'superfamily',", "'deletion_matrix',", "'resolution',", "'between_segment_residues',",... | 400,771 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.