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 |
|---|---|---|---|---|---|---|---|---|
weimin17/Object-Detection_HelmetDetection | model_lib_test.py | ModelLibTest.test_create_estimator_and_inputs | test_create_estimator_and_inputs | Tests that Estimator and input function are constructed correctly. | [
"Tests",
"that",
"Estimator",
"and",
"input",
"function",
"are",
"constructed",
"correctly."
] | def test_create_estimator_and_inputs(self):
run_config = tf.estimator.RunConfig()
hparams = model_hparams.create_hparams(hparams_overrides='load_pretrained=false')
pipeline_config_path = get_pipeline_config_path(MODEL_NAME_FOR_TEST)
train_steps = 20
eval_steps = 10
train_and_eval_dict = model_li... | ['def', 'test_create_estimator_and_inputs(self):', 'run_config', '=', 'tf.estimator.RunConfig()', 'hparams', '=', "model_hparams.create_hparams(hparams_overrides='load_pretrained=false')", 'pipeline_config_path', '=', 'get_pipeline_config_path(MODEL_NAME_FOR_TEST)', 'train_steps', '=', '20', 'eval_steps', '=', '10', 't... | 758,448 |
stonezwr/TSSL-BP | utils.py | aboutCudaDevices.info | info | Class representation as number of devices connected and about them. | [
"Class",
"representation",
"as",
"number",
"of",
"devices",
"connected",
"and",
"about",
"them."
] | def info(self):
num = cuda.Device.count()
string = ''
string += '%d device(s) found:\n' % num
for i in range(num):
string += ' %d) %s (Id: %d)\n' % (i + 1, cuda.Device(i).name(), i)
string += ' Memory: %.2f GB\n' % (cuda.Device(i).total_memory() / 1000000000.0)
return str... | ['def', 'info(self):', 'num', '=', 'cuda.Device.count()', 'string', '=', "''", 'string', '+=', "'%d", 'device(s)', "found:\\n'", '%', 'num', 'for', 'i', 'in', 'range(num):', 'string', '+=', "'", '%d)', '%s', '(Id:', "%d)\\n'", '%', '(i', '+', '1,', 'cuda.Device(i).name(),', 'i)', 'string', '+=', "'", 'Memory:', '%.2f',... | 952,677 |
mathieuorhan/pointnet2_semantic | pc_util.py | volume_to_point_cloud | volume_to_point_cloud | vol is occupancy grid (value = 0 or 1) of size vsize*vsize*vsize return Nx3 numpy array. | [
"vol",
"is",
"occupancy",
"grid",
"(value",
"=",
"0",
"or",
"1)",
"of",
"size",
"vsize*vsize*vsize",
"return",
"Nx3",
"numpy",
"array."
] | def volume_to_point_cloud(vol):
vsize = vol.shape[0]
assert vol.shape[1] == vsize and vol.shape[1] == vsize
points = []
for a in range(vsize):
for b in range(vsize):
for c in range(vsize):
if vol[a, b, c] == 1:
points.append(np.array([a, b, c]))
... | ['def', 'volume_to_point_cloud(vol):', 'vsize', '=', 'vol.shape[0]', 'assert', 'vol.shape[1]', '==', 'vsize', 'and', 'vol.shape[1]', '==', 'vsize', 'points', '=', '[]', 'for', 'a', 'in', 'range(vsize):', 'for', 'b', 'in', 'range(vsize):', 'for', 'c', 'in', 'range(vsize):', 'if', 'vol[a,', 'b,', 'c]', '==', '1:', 'point... | 781,083 |
sunishsheth2009/ChatterBot | formparser.py | MultiPartParser.parse_parts | parse_parts | Generate ``('file', (name, val))`` and ``('form', (name, val))`` parts. | [
"Generate",
"``('file',",
"(name,",
"val))``",
"and",
"``('form',",
"(name,",
"val))``",
"parts."
] | def parse_parts(self, file, boundary, content_length):
in_memory = 0
for (ellt, ell) in self.parse_lines(file, boundary, content_length):
if ellt == _begin_file:
(headers, name, filename) = ell
is_file = True
guard_memory = False
(filename, container) = se... | ['def', 'parse_parts(self,', 'file,', 'boundary,', 'content_length):', 'in_memory', '=', '0', 'for', '(ellt,', 'ell)', 'in', 'self.parse_lines(file,', 'boundary,', 'content_length):', 'if', 'ellt', '==', '_begin_file:', '(headers,', 'name,', 'filename)', '=', 'ell', 'is_file', '=', 'True', 'guard_memory', '=', 'False',... | 482,100 |
skorokithakis/encbup | test_integration.py | TestIntegration.is_restore_complete | is_restore_complete | Compare the files in the backup dir those in the restore dir, and return True if they are identical, False otherwise. | [
"Compare",
"the",
"files",
"in",
"the",
"backup",
"dir",
"those",
"in",
"the",
"restore",
"dir,",
"and",
"return",
"True",
"if",
"they",
"are",
"identical,",
"False",
"otherwise."
] | def is_restore_complete(self):
sd = set(scandir(self.source_dir).keys())
bd = set(scandir(self.restore_dir).keys())
return len(sd - bd | bd - sd) == 0 | ['def', 'is_restore_complete(self):', 'sd', '=', 'set(scandir(self.source_dir).keys())', 'bd', '=', 'set(scandir(self.restore_dir).keys())', 'return', 'len(sd', '-', 'bd', '|', 'bd', '-', 'sd)', '==', '0'] | 177,929 |
ChenhongyiYang/PGD | test_head.py | test_yolov3_head_get_bboxes | test_yolov3_head_get_bboxes | Test yolov3 head get_bboxes() in torch and ort env. | [
"Test",
"yolov3",
"head",
"get_bboxes()",
"in",
"torch",
"and",
"ort",
"env."
] | def test_yolov3_head_get_bboxes():
yolo_model = yolo_config()
s = 128
img_metas = [{'img_shape_for_onnx': torch.Tensor([s, s]), 'img_shape': (s, s, 3), 'scale_factor': np.ones(4), 'pad_shape': (s, s, 3)}]
yolo_head_data = 'yolov3_head_get_bboxes.pkl'
pred_maps = mmcv.load(osp.join(data_path, yolo_he... | ['def', 'test_yolov3_head_get_bboxes():', 'yolo_model', '=', 'yolo_config()', 's', '=', '128', 'img_metas', '=', "[{'img_shape_for_onnx':", 'torch.Tensor([s,', 's]),', "'img_shape':", '(s,', 's,', '3),', "'scale_factor':", 'np.ones(4),', "'pad_shape':", '(s,', 's,', '3)}]', 'yolo_head_data', '=', "'yolov3_head_get_bbox... | 768,323 |
microsoft/nni | nn_meter.py | to_onnx | to_onnx | Helper function to convert a model to onnx model. | [
"Helper",
"function",
"to",
"convert",
"a",
"model",
"to",
"onnx",
"model."
] | def to_onnx(model: nn.Module, example_inputs: Any) -> Any:
try:
import onnx
import onnxsim
import onnxruntime
except ImportError:
_logger.error('Please install onnx, onnxruntime, onnxsim to use this function.')
raise
with tempfile.TemporaryFile() as fp:
torch.... | ['def', 'to_onnx(model:', 'nn.Module,', 'example_inputs:', 'Any)', '->', 'Any:', 'try:', 'import', 'onnx', 'import', 'onnxsim', 'import', 'onnxruntime', 'except', 'ImportError:', "_logger.error('Please", 'install', 'onnx,', 'onnxruntime,', 'onnxsim', 'to', 'use', 'this', "function.')", 'raise', 'with', 'tempfile.Tempor... | 728,880 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | real_nvp_utils.py | variable_on_cpu | variable_on_cpu | Helper to create a Variable stored on CPU memory. | [
"Helper",
"to",
"create",
"a",
"Variable",
"stored",
"on",
"CPU",
"memory."
] | def variable_on_cpu(name, shape, initializer, trainable=True):
var = tf.get_variable(name, shape, initializer=initializer, trainable=trainable)
return var | ['def', 'variable_on_cpu(name,', 'shape,', 'initializer,', 'trainable=True):', 'var', '=', 'tf.get_variable(name,', 'shape,', 'initializer=initializer,', 'trainable=trainable)', 'return', 'var'] | 109,468 |
43Carrig/recurrent_neural_networks_practice | tensor_spec.py | BoundedTensorSpec.maximum | maximum | Returns a NumPy array specifying the maximum bounds (inclusive). | [
"Returns",
"a",
"NumPy",
"array",
"specifying",
"the",
"maximum",
"bounds",
"(inclusive)."
] | def maximum(self):
return self._maximum | ['def', 'maximum(self):', 'return', 'self._maximum'] | 336,492 |
gongchenghhu/cs420-zeroshot-tts-korean | cleaners.py | english_cleaners | english_cleaners | Pipeline for English text, including number and abbreviation expansion. | [
"Pipeline",
"for",
"English",
"text,",
"including",
"number",
"and",
"abbreviation",
"expansion."
] | def english_cleaners(text):
text = convert_to_ascii(text)
text = lowercase(text)
text = expand_numbers(text)
text = expand_abbreviations(text)
text = collapse_whitespace(text)
return text | ['def', 'english_cleaners(text):', 'text', '=', 'convert_to_ascii(text)', 'text', '=', 'lowercase(text)', 'text', '=', 'expand_numbers(text)', 'text', '=', 'expand_abbreviations(text)', 'text', '=', 'collapse_whitespace(text)', 'return', 'text'] | 508,221 |
enuguru/artificial_intelligence_and_machine_ | wrappers.py | ReverseSlashBehaviorRequestMixin.script_root | script_root | The root path of the script includling a trailing slash. | [
"The",
"root",
"path",
"of",
"the",
"script",
"includling",
"a",
"trailing",
"slash."
] | def script_root(self):
path = wsgi_decoding_dance(self.environ.get('SCRIPT_NAME') or '', self.charset, self.encoding_errors)
return path.rstrip('/') + '/' | ['def', 'script_root(self):', 'path', '=', "wsgi_decoding_dance(self.environ.get('SCRIPT_NAME')", 'or', "'',", 'self.charset,', 'self.encoding_errors)', 'return', "path.rstrip('/')", '+', "'/'"] | 132,745 |
angeladai/ScanComplete | complete_scan.py | export_prediction_to_mesh | export_prediction_to_mesh | Saves predicted df/sem + input (+ target, if any) to mesh visualization. | [
"Saves",
"predicted",
"df/sem",
"+",
"input",
"(+",
"target,",
"if",
"any)",
"to",
"mesh",
"visualization."
] | def export_prediction_to_mesh(outprefix, input_sdf, output_df, output_sem, target_df, target_sem):
(scene_dim_z, scene_dim_y, scene_dim_x) = input_sdf.shape
save_input_sdf = constants.TRUNCATION * np.ones([scene_dim_z, 2 * FLAGS.pad_test + scene_dim_y, scene_dim_x])
save_prediction = np.copy(save_input_sdf)... | ['def', 'export_prediction_to_mesh(outprefix,', 'input_sdf,', 'output_df,', 'output_sem,', 'target_df,', 'target_sem):', '(scene_dim_z,', 'scene_dim_y,', 'scene_dim_x)', '=', 'input_sdf.shape', 'save_input_sdf', '=', 'constants.TRUNCATION', '*', 'np.ones([scene_dim_z,', '2', '*', 'FLAGS.pad_test', '+', 'scene_dim_y,', ... | 845,841 |
suarez12138/AI-Reversi_IMP_TextDichotomy | animation.py | MovieWriterRegistry.list | list | Get a list of available MovieWriters. | [
"Get",
"a",
"list",
"of",
"available",
"MovieWriters."
] | def list(self):
return [*self] | ['def', 'list(self):', 'return', '[*self]'] | 96,032 |
jshilong/DDQ | photometric.py | imnormalize | imnormalize | Normalize an image with mean and std. | [
"Normalize",
"an",
"image",
"with",
"mean",
"and",
"std."
] | def imnormalize(img, mean, std, to_rgb=True):
img = img.copy().astype(np.float32)
return imnormalize_(img, mean, std, to_rgb) | ['def', 'imnormalize(img,', 'mean,', 'std,', 'to_rgb=True):', 'img', '=', 'img.copy().astype(np.float32)', 'return', 'imnormalize_(img,', 'mean,', 'std,', 'to_rgb)'] | 499,065 |
sunishsheth2009/ChatterBot | expression.py | Select.having | having | return a new select() construct with the given expression added to its HAVING clause, joined to the existing clause via AND, if any. | [
"return",
"a",
"new",
"select()",
"construct",
"with",
"the",
"given",
"expression",
"added",
"to",
"its",
"HAVING",
"clause,",
"joined",
"to",
"the",
"existing",
"clause",
"via",
"AND,",
"if",
"any."
] | def having(self, having):
self.append_having(having) | ['def', 'having(self,', 'having):', 'self.append_having(having)'] | 534,927 |
zhang614/MicroGrid | vertexattribute.py | AbstractAttribute.enable | enable | Enable the attribute using ``glEnableClientState``. | [
"Enable",
"the",
"attribute",
"using",
"``glEnableClientState``."
] | def enable(self):
raise NotImplementedError('abstract') | ['def', 'enable(self):', 'raise', "NotImplementedError('abstract')"] | 668,680 |
PacktPublishing/Hands-On-Artificial--for-Banking | _trustregion.py | BaseQuadraticSubproblem.hess | hess | Value of Hessian of objective function at current iteration. | [
"Value",
"of",
"Hessian",
"of",
"objective",
"function",
"at",
"current",
"iteration."
] | def hess(self):
if self._h is None:
self._h = self._hess(self._x)
return self._h | ['def', 'hess(self):', 'if', 'self._h', 'is', 'None:', 'self._h', '=', 'self._hess(self._x)', 'return', 'self._h'] | 203,053 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | wide_deep.py | build_model_columns | build_model_columns | Builds a set of wide and deep feature columns. | [
"Builds",
"a",
"set",
"of",
"wide",
"and",
"deep",
"feature",
"columns."
] | def build_model_columns():
age = tf.feature_column.numeric_column('age')
education_num = tf.feature_column.numeric_column('education_num')
capital_gain = tf.feature_column.numeric_column('capital_gain')
capital_loss = tf.feature_column.numeric_column('capital_loss')
hours_per_week = tf.feature_colum... | ['def', 'build_model_columns():', 'age', '=', "tf.feature_column.numeric_column('age')", 'education_num', '=', "tf.feature_column.numeric_column('education_num')", 'capital_gain', '=', "tf.feature_column.numeric_column('capital_gain')", 'capital_loss', '=', "tf.feature_column.numeric_column('capital_loss')", 'hours_per... | 20,226 |
ryu-ed/SpaceInvaders_Ros | frontend.py | validate_ternary | validate_ternary | Check/normalize three-value settings: True: '1', 'on', 'yes', 'true' False: '0', 'off', 'no','false', '' any other value: returned as-is. | [
"Check/normalize",
"three-value",
"settings:",
"True:",
"'1',",
"'on',",
"'yes',",
"'true'",
"False:",
"'0',",
"'off',",
"'no','false',",
"''",
"any",
"other",
"value:",
"returned",
"as-is."
] | def validate_ternary(setting, value, option_parser, config_parser=None, config_section=None):
if isinstance(value, bool) or value is None:
return value
try:
return option_parser.booleans[value.strip().lower()]
except KeyError:
return value | ['def', 'validate_ternary(setting,', 'value,', 'option_parser,', 'config_parser=None,', 'config_section=None):', 'if', 'isinstance(value,', 'bool)', 'or', 'value', 'is', 'None:', 'return', 'value', 'try:', 'return', 'option_parser.booleans[value.strip().lower()]', 'except', 'KeyError:', 'return', 'value'] | 394,729 |
chribsen/simple-machine-learning-examples | test_t_sne.py | test_optimization_minimizes_kl_divergence | test_optimization_minimizes_kl_divergence | t-SNE should give a lower KL divergence with more iterations. | [
"t-SNE",
"should",
"give",
"a",
"lower",
"KL",
"divergence",
"with",
"more",
"iterations."
] | def test_optimization_minimizes_kl_divergence():
random_state = check_random_state(0)
(X, _) = make_blobs(n_features=3, random_state=random_state)
kl_divergences = []
for n_iter in [200, 250, 300]:
tsne = TSNE(n_components=2, perplexity=10, learning_rate=100.0, n_iter=n_iter, random_state=0)
... | ['def', 'test_optimization_minimizes_kl_divergence():', 'random_state', '=', 'check_random_state(0)', '(X,', '_)', '=', 'make_blobs(n_features=3,', 'random_state=random_state)', 'kl_divergences', '=', '[]', 'for', 'n_iter', 'in', '[200,', '250,', '300]:', 'tsne', '=', 'TSNE(n_components=2,', 'perplexity=10,', 'learning... | 939,503 |
sktime/sktime | test_testscenarios.py | test_testscenario_object_default_arg_sequence | test_testscenario_object_default_arg_sequence | Test basic workflow: construct with args and default arg sequence. | [
"Test",
"basic",
"workflow:",
"construct",
"with",
"args",
"and",
"default",
"arg",
"sequence."
] | def test_testscenario_object_default_arg_sequence():
obj = MockTestedClass(a='super')
scenario = TestScenario(args={'foo': {'b': 'cali'}, 'bar': {'c': 'fragi', 'd': 'listic'}}, default_arg_sequence=['foo', 'bar'])
result = scenario.run(obj)
assert result == 'supercalifragilistic' | ['def', 'test_testscenario_object_default_arg_sequence():', 'obj', '=', "MockTestedClass(a='super')", 'scenario', '=', "TestScenario(args={'foo':", "{'b':", "'cali'},", "'bar':", "{'c':", "'fragi',", "'d':", "'listic'}},", "default_arg_sequence=['foo',", "'bar'])", 'result', '=', 'scenario.run(obj)', 'assert', 'result'... | 878,162 |
intel/neural-compressor | graph_converter_without_calib.py | GraphConverterWithoutCalib.convert_without_calib | convert_without_calib | Do conversion without calibration. | [
"Do",
"conversion",
"without",
"calibration."
] | def convert_without_calib(self):
model = self._tmp_model
if len(self.op_wise_config) > 0:
model = self.quantize_without_calib()
if len(self.bf16_ops) > 0:
model = self.bf16_convert()
post_cse_graph_def = PostCseOptimizer(model.graph_def).do_transformation()
post_cse_graph_def.library... | ['def', 'convert_without_calib(self):', 'model', '=', 'self._tmp_model', 'if', 'len(self.op_wise_config)', '>', '0:', 'model', '=', 'self.quantize_without_calib()', 'if', 'len(self.bf16_ops)', '>', '0:', 'model', '=', 'self.bf16_convert()', 'post_cse_graph_def', '=', 'PostCseOptimizer(model.graph_def).do_transformation... | 737,582 |
nicknochnack/RealTimeSignLanguageTFJS | classifier_trainer_test.py | ClassifierTest.test_gpu_train | test_gpu_train | Test train_and_eval and export for Keras classifier models. | [
"Test",
"train_and_eval",
"and",
"export",
"for",
"Keras",
"classifier",
"models."
] | def test_gpu_train(self, distribution, model, dataset, dtype):
model_dir = self.create_tempdir().full_path
base_flags = ['--data_dir=not_used', '--model_type=' + model, '--dataset=' + dataset]
train_and_eval_flags = base_flags + [get_params_override(basic_params_override(dtype)), '--mode=train_and_eval']
... | ['def', 'test_gpu_train(self,', 'distribution,', 'model,', 'dataset,', 'dtype):', 'model_dir', '=', 'self.create_tempdir().full_path', 'base_flags', '=', "['--data_dir=not_used',", "'--model_type='", '+', 'model,', "'--dataset='", '+', 'dataset]', 'train_and_eval_flags', '=', 'base_flags', '+', '[get_params_override(ba... | 851,158 |
weimin17/Object-Detection_HelmetDetection | resources.py | GetSyntaxNetResource | GetSyntaxNetResource | Returns the content of a resource. | [
"Returns",
"the",
"content",
"of",
"a",
"resource."
] | def GetSyntaxNetResource(path):
with GetSyntaxNetResourceAsFile(path) as resource_file:
return resource_file.read() | ['def', 'GetSyntaxNetResource(path):', 'with', 'GetSyntaxNetResourceAsFile(path)', 'as', 'resource_file:', 'return', 'resource_file.read()'] | 753,663 |
befelix/safe_learning | test_functions.py | TestGridworld.test_0d | test_0d | Check that initialization works for 1d-discretization. | [
"Check",
"that",
"initialization",
"works",
"for",
"1d-discretization."
] | def test_0d(self):
grid = GridWorld([[0, 1]], 3)
test = np.array([[0.1, 0.4, 0.9]]).T
res = np.array([0, 1, 2])
assert_allclose(grid.state_to_index(test), res)
res = np.array([0, 0, 1])
assert_allclose(grid.state_to_rectangle(test), res)
assert_allclose(grid.rectangle_to_state(res), res[:, N... | ['def', 'test_0d(self):', 'grid', '=', 'GridWorld([[0,', '1]],', '3)', 'test', '=', 'np.array([[0.1,', '0.4,', '0.9]]).T', 'res', '=', 'np.array([0,', '1,', '2])', 'assert_allclose(grid.state_to_index(test),', 'res)', 'res', '=', 'np.array([0,', '0,', '1])', 'assert_allclose(grid.state_to_rectangle(test),', 'res)', 'as... | 328,239 |
google-research/ssl_detection | custom_ops.py | fc | fc | Creates a fully connected layer applied to `inputs`. | [
"Creates",
"a",
"fully",
"connected",
"layer",
"applied",
"to",
"`inputs`."
] | def fc(inputs, num_units_out, scope=None, reuse=None):
if len(inputs.shape) > 2:
inputs = tf.reshape(inputs, [int(inputs.shape[0]), -1])
with tf.variable_scope(scope, 'FC', [inputs], reuse=reuse):
num_units_in = inputs.shape[1]
weights_shape = [num_units_in, num_units_out]
unif_i... | ['def', 'fc(inputs,', 'num_units_out,', 'scope=None,', 'reuse=None):', 'if', 'len(inputs.shape)', '>', '2:', 'inputs', '=', 'tf.reshape(inputs,', '[int(inputs.shape[0]),', '-1])', 'with', 'tf.variable_scope(scope,', "'FC',", '[inputs],', 'reuse=reuse):', 'num_units_in', '=', 'inputs.shape[1]', 'weights_shape', '=', '[n... | 382,105 |
FreshAirTonight/af2complex | folding_multimer.py | sidechain_loss | sidechain_loss | Sidechain Loss using cleaned up rigids. | [
"Sidechain",
"Loss",
"using",
"cleaned",
"up",
"rigids."
] | def sidechain_loss(gt_frames: geometry.Rigid3Array, gt_frames_mask: jnp.ndarray, gt_positions: geometry.Vec3Array, gt_mask: jnp.ndarray, pred_frames: geometry.Rigid3Array, pred_positions: geometry.Vec3Array, config: ml_collections.ConfigDict) -> Dict[str, jnp.ndarray]:
flat_gt_frames = jax.tree_map(jnp.ravel, gt_fr... | ['def', 'sidechain_loss(gt_frames:', 'geometry.Rigid3Array,', 'gt_frames_mask:', 'jnp.ndarray,', 'gt_positions:', 'geometry.Vec3Array,', 'gt_mask:', 'jnp.ndarray,', 'pred_frames:', 'geometry.Rigid3Array,', 'pred_positions:', 'geometry.Vec3Array,', 'config:', 'ml_collections.ConfigDict)', '->', 'Dict[str,', 'jnp.ndarray... | 400,651 |
TheCurryMan/MedicAI | wrappers.py | BaseRequest.remote_addr | remote_addr | The remote address of the client. | [
"The",
"remote",
"address",
"of",
"the",
"client."
] | def remote_addr(self):
return self.environ.get('REMOTE_ADDR') | ['def', 'remote_addr(self):', 'return', "self.environ.get('REMOTE_ADDR')"] | 649,772 |
replit-archive/empythoned | __init__.py | LoggerAdapter.info | info | Delegate an info call to the underlying logger, after adding contextual information from this adapter instance. | [
"Delegate",
"an",
"info",
"call",
"to",
"the",
"underlying",
"logger,",
"after",
"adding",
"contextual",
"information",
"from",
"this",
"adapter",
"instance."
] | def info(self, msg, *args, **kwargs):
(msg, kwargs) = self.process(msg, kwargs)
self.logger.info(msg, *args, **kwargs) | ['def', 'info(self,', 'msg,', '*args,', '**kwargs):', '(msg,', 'kwargs)', '=', 'self.process(msg,', 'kwargs)', 'self.logger.info(msg,', '*args,', '**kwargs)'] | 176,941 |
43Carrig/recurrent_neural_networks_practice | loss_scale_manager.py | LossScaleManager.update_loss_scale | update_loss_scale | Updates loss scale based on if gradients are finite in current step. | [
"Updates",
"loss",
"scale",
"based",
"on",
"if",
"gradients",
"are",
"finite",
"in",
"current",
"step."
] | def update_loss_scale(self, finite_grads):
del finite_grads
return | ['def', 'update_loss_scale(self,', 'finite_grads):', 'del', 'finite_grads', 'return'] | 334,971 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | nb_007.py | LanguageModelLoader.batchify | batchify | Splits the data in batches. | [
"Splits",
"the",
"data",
"in",
"batches."
] | def batchify(self, data: np.ndarray) -> LongTensor:
nb = data.shape[0] // self.bs
data = np.array(data[:nb * self.bs]).reshape(self.bs, -1).T
if self.backwards:
data = data[::-1]
return LongTensor(data) | ['def', 'batchify(self,', 'data:', 'np.ndarray)', '->', 'LongTensor:', 'nb', '=', 'data.shape[0]', '//', 'self.bs', 'data', '=', 'np.array(data[:nb', '*', 'self.bs]).reshape(self.bs,', '-1).T', 'if', 'self.backwards:', 'data', '=', 'data[::-1]', 'return', 'LongTensor(data)'] | 81,521 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | treewizard.py | TreeWizard.getTokenType | getTokenType | Using the map of token names to token types, return the type. | [
"Using",
"the",
"map",
"of",
"token",
"names",
"to",
"token",
"types,",
"return",
"the",
"type."
] | def getTokenType(self, tokenName):
try:
return self.tokenNameToTypeMap[tokenName]
except KeyError:
return INVALID_TOKEN_TYPE | ['def', 'getTokenType(self,', 'tokenName):', 'try:', 'return', 'self.tokenNameToTypeMap[tokenName]', 'except', 'KeyError:', 'return', 'INVALID_TOKEN_TYPE'] | 16,765 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nested_utils.py | read_tas | read_tas | Performs a read operation on a set of TensorArrays. | [
"Performs",
"a",
"read",
"operation",
"on",
"a",
"set",
"of",
"TensorArrays."
] | def read_tas(tas, index):
return map_nested(lambda ta: ta.read(index), tas) | ['def', 'read_tas(tas,', 'index):', 'return', 'map_nested(lambda', 'ta:', 'ta.read(index),', 'tas)'] | 54,613 |
ChenhongyiYang/PPAL | transformer.py | DeformableDetrTransformerDecoder.forward | forward | Forward function for `TransformerDecoder`. | [
"Forward",
"function",
"for",
"`TransformerDecoder`."
] | def forward(self, query, *args, reference_points=None, valid_ratios=None, reg_branches=None, **kwargs):
output = query
intermediate = []
intermediate_reference_points = []
for (lid, layer) in enumerate(self.layers):
if reference_points.shape[-1] == 4:
reference_points_input = referen... | ['def', 'forward(self,', 'query,', '*args,', 'reference_points=None,', 'valid_ratios=None,', 'reg_branches=None,', '**kwargs):', 'output', '=', 'query', 'intermediate', '=', '[]', 'intermediate_reference_points', '=', '[]', 'for', '(lid,', 'layer)', 'in', 'enumerate(self.layers):', 'if', 'reference_points.shape[-1]', '... | 821,825 |
awslabs/mxnet-lambda | basic_layers.py | HybridSequential.add | add | Adds block on top of the stack. | [
"Adds",
"block",
"on",
"top",
"of",
"the",
"stack."
] | def add(self, *blocks):
for block in blocks:
self.register_child(block) | ['def', 'add(self,', '*blocks):', 'for', 'block', 'in', 'blocks:', 'self.register_child(block)'] | 287,948 |
zackmcnulty/CSE_446-Machine_Learning | _base.py | _process_plot_var_args.get_next_color | get_next_color | Return the next color in the cycle. | [
"Return",
"the",
"next",
"color",
"in",
"the",
"cycle."
] | def get_next_color(self):
if 'color' not in self._prop_keys:
return 'k'
return next(self.prop_cycler)['color'] | ['def', 'get_next_color(self):', 'if', "'color'", 'not', 'in', 'self._prop_keys:', 'return', "'k'", 'return', "next(self.prop_cycler)['color']"] | 194,833 |
muhanzhang/D-VAE | nnet.py | local_useless_crossentropy_softmax_1hot_with_bias_dx_alloc | local_useless_crossentropy_softmax_1hot_with_bias_dx_alloc | Replace a CrossentropySoftmax1HotWithBiasDx op, whose incoming gradient is an `alloc` of a scalar variable or one that has either broadcastable or matching dimensions with the output variable, by one that skips the intermediate `alloc`. | [
"Replace",
"a",
"CrossentropySoftmax1HotWithBiasDx",
"op,",
"whose",
"incoming",
"gradient",
"is",
"an",
"`alloc`",
"of",
"a",
"scalar",
"variable",
"or",
"one",
"that",
"has",
"either",
"broadcastable",
"or",
"matching",
"dimensions",
"with",
"the",
"output",
"va... | def local_useless_crossentropy_softmax_1hot_with_bias_dx_alloc(node):
if isinstance(node.op, CrossentropySoftmax1HotWithBiasDx):
(dy, sm, y_idx) = node.inputs
if dy.ndim == 0:
return False
if dy.ndim == 1 and dy.broadcastable[0]:
return False
assert dy.ndim ==... | ['def', 'local_useless_crossentropy_softmax_1hot_with_bias_dx_alloc(node):', 'if', 'isinstance(node.op,', 'CrossentropySoftmax1HotWithBiasDx):', '(dy,', 'sm,', 'y_idx)', '=', 'node.inputs', 'if', 'dy.ndim', '==', '0:', 'return', 'False', 'if', 'dy.ndim', '==', '1', 'and', 'dy.broadcastable[0]:', 'return', 'False', 'ass... | 525,698 |
Katja-M/Python_NaturalLanguageProcessing | collocations.py | TrigramCollocationFinder.score_ngram | score_ngram | Returns the score for a given trigram using the given scoring function. | [
"Returns",
"the",
"score",
"for",
"a",
"given",
"trigram",
"using",
"the",
"given",
"scoring",
"function."
] | def score_ngram(self, score_fn, w1, w2, w3):
n_all = self.N
n_iii = self.ngram_fd[w1, w2, w3]
if not n_iii:
return
n_iix = self.bigram_fd[w1, w2]
n_ixi = self.wildcard_fd[w1, w3]
n_xii = self.bigram_fd[w2, w3]
n_ixx = self.word_fd[w1]
n_xix = self.word_fd[w2]
n_xxi = self.wor... | ['def', 'score_ngram(self,', 'score_fn,', 'w1,', 'w2,', 'w3):', 'n_all', '=', 'self.N', 'n_iii', '=', 'self.ngram_fd[w1,', 'w2,', 'w3]', 'if', 'not', 'n_iii:', 'return', 'n_iix', '=', 'self.bigram_fd[w1,', 'w2]', 'n_ixi', '=', 'self.wildcard_fd[w1,', 'w3]', 'n_xii', '=', 'self.bigram_fd[w2,', 'w3]', 'n_ixx', '=', 'self... | 865,713 |
wallix/pylogsparser | test_lognormalizer.py | Test.test_008_normalizer_multiple_paths | test_008_normalizer_multiple_paths | Verify we can can deal with multiple normalizer paths. | [
"Verify",
"we",
"can",
"can",
"deal",
"with",
"multiple",
"normalizer",
"paths."
] | def test_008_normalizer_multiple_paths(self):
fdir = tempfile.mkdtemp()
sdir = tempfile.mkdtemp()
for f in os.listdir(self.normalizer_path):
path_f = os.path.join(self.normalizer_path, f)
if os.path.isfile(path_f):
shutil.copyfile(path_f, os.path.join(fdir, f))
shutil.move(os... | ['def', 'test_008_normalizer_multiple_paths(self):', 'fdir', '=', 'tempfile.mkdtemp()', 'sdir', '=', 'tempfile.mkdtemp()', 'for', 'f', 'in', 'os.listdir(self.normalizer_path):', 'path_f', '=', 'os.path.join(self.normalizer_path,', 'f)', 'if', 'os.path.isfile(path_f):', 'shutil.copyfile(path_f,', 'os.path.join(fdir,', '... | 296,725 |
michaelhush/M-LOOP | visualizations.py | DifferentialEvolutionVisualizer.plot_costs_vs_generations | plot_costs_vs_generations | Create a plot of the costs versus run number. | [
"Create",
"a",
"plot",
"of",
"the",
"costs",
"versus",
"run",
"number."
] | def plot_costs_vs_generations(self):
if self.costs_generations.size == 0:
self.log.warning('Unable to plot DE: costs vs generations as the initial generation did not complete.')
return
global figure_counter, cost_label, generation_label
figure_counter += 1
plt.figure(figure_counter)
... | ['def', 'plot_costs_vs_generations(self):', 'if', 'self.costs_generations.size', '==', '0:', "self.log.warning('Unable", 'to', 'plot', 'DE:', 'costs', 'vs', 'generations', 'as', 'the', 'initial', 'generation', 'did', 'not', "complete.')", 'return', 'global', 'figure_counter,', 'cost_label,', 'generation_label', 'figure... | 619,961 |
ludwig-ai/ludwig | deepspeed.py | DeepSpeedStrategy.allow_mixed_precision | allow_mixed_precision | DeepSpeed handles mixed precision internally. | [
"DeepSpeed",
"handles",
"mixed",
"precision",
"internally."
] | def allow_mixed_precision(self) -> bool:
return False | ['def', 'allow_mixed_precision(self)', '->', 'bool:', 'return', 'False'] | 616,730 |
eddylau328/fyp-artificial-intelligence-ac-control-device | face.py | GenericStub.event_stream_stream | event_stream_stream | Event-driven invocation of a unary-request-stream-response method. | [
"Event-driven",
"invocation",
"of",
"a",
"unary-request-stream-response",
"method."
] | def event_stream_stream(self, group, method, receiver, abortion_callback, timeout, metadata=None, protocol_options=None):
raise NotImplementedError() | ['def', 'event_stream_stream(self,', 'group,', 'method,', 'receiver,', 'abortion_callback,', 'timeout,', 'metadata=None,', 'protocol_options=None):', 'raise', 'NotImplementedError()'] | 215,709 |
ncbi-nlp/DeepRel | bllipparser.py | Bllip.parse | parse | Parse the sentence text using Reranking parser. | [
"Parse",
"the",
"sentence",
"text",
"using",
"Reranking",
"parser."
] | def parse(self, s: str):
if not s:
raise ValueError('Cannot parse empty sentence: {}'.format(s))
try:
nbest = self.rrp.parse(str(s))
return str(nbest[0].ptb_parse)
except:
raise ValueError('Cannot parse sentence: %s' % s) | ['def', 'parse(self,', 's:', 'str):', 'if', 'not', 's:', 'raise', "ValueError('Cannot", 'parse', 'empty', 'sentence:', "{}'.format(s))", 'try:', 'nbest', '=', 'self.rrp.parse(str(s))', 'return', 'str(nbest[0].ptb_parse)', 'except:', 'raise', "ValueError('Cannot", 'parse', 'sentence:', "%s'", '%', 's)'] | 180,763 |
salesforce/CodeRL | hf_argparser.py | HfArgumentParser.parse_dict | parse_dict | Alternative helper method that does not use `argparse` at all, instead uses a dict and populating the dataclass types. | [
"Alternative",
"helper",
"method",
"that",
"does",
"not",
"use",
"`argparse`",
"at",
"all,",
"instead",
"uses",
"a",
"dict",
"and",
"populating",
"the",
"dataclass",
"types."
] | def parse_dict(self, args: dict) -> Tuple[DataClass, ...]:
outputs = []
for dtype in self.dataclass_types:
keys = {f.name for f in dataclasses.fields(dtype) if f.init}
inputs = {k: v for (k, v) in args.items() if k in keys}
obj = dtype(**inputs)
outputs.append(obj)
return (*o... | ['def', 'parse_dict(self,', 'args:', 'dict)', '->', 'Tuple[DataClass,', '...]:', 'outputs', '=', '[]', 'for', 'dtype', 'in', 'self.dataclass_types:', 'keys', '=', '{f.name', 'for', 'f', 'in', 'dataclasses.fields(dtype)', 'if', 'f.init}', 'inputs', '=', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'args.items()', 'if', 'k', 'i... | 493,979 |
apeterswu/RL4NMT | diet.py | make_diet_var_getter | make_diet_var_getter | Create a custom variable getter for diet variables according to params. | [
"Create",
"a",
"custom",
"variable",
"getter",
"for",
"diet",
"variables",
"according",
"to",
"params."
] | def make_diet_var_getter(params):
def diet_var_initializer(shape, dtype, partition_info=None):
del dtype
del partition_info
with common_layers.fn_device_dependency('diet_init') as out_deps:
float_range = math.sqrt(3)
ret = tf.random_uniform(shape, -float_range, float... | ['def', 'make_diet_var_getter(params):', 'def', 'diet_var_initializer(shape,', 'dtype,', 'partition_info=None):', 'del', 'dtype', 'del', 'partition_info', 'with', "common_layers.fn_device_dependency('diet_init')", 'as', 'out_deps:', 'float_range', '=', 'math.sqrt(3)', 'ret', '=', 'tf.random_uniform(shape,', '-float_ran... | 331,244 |
sunishsheth2009/ChatterBot | test_core.py | TestMaskedArray.test_basic2d | test_basic2d | Test of basic array creation and properties in 2 dimensions. | [
"Test",
"of",
"basic",
"array",
"creation",
"and",
"properties",
"in",
"2",
"dimensions."
] | def test_basic2d(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
for s in [(4, 3), (6, 2)]:
x.shape = s
y.shape = s
xm.shape = s
ym.shape = s
xf.shape = s
self.assertTrue(not isMaskedArray(x))
self.assertTrue(isMaskedArray(xm))
assert_equal(... | ['def', 'test_basic2d(self):', '(x,', 'y,', 'a10,', 'm1,', 'm2,', 'xm,', 'ym,', 'z,', 'zm,', 'xf)', '=', 'self.d', 'for', 's', 'in', '[(4,', '3),', '(6,', '2)]:', 'x.shape', '=', 's', 'y.shape', '=', 's', 'xm.shape', '=', 's', 'ym.shape', '=', 's', 'xf.shape', '=', 's', 'self.assertTrue(not', 'isMaskedArray(x))', 'self... | 531,846 |
PacktPublishing/Hands-On-Artificial--for-Banking | __init__.py | DebuggedApplication.debug_application | debug_application | Run the application and conserve the traceback frames. | [
"Run",
"the",
"application",
"and",
"conserve",
"the",
"traceback",
"frames."
] | def debug_application(self, environ, start_response):
app_iter = None
try:
app_iter = self.app(environ, start_response)
for item in app_iter:
yield item
if hasattr(app_iter, 'close'):
app_iter.close()
except Exception:
if hasattr(app_iter, 'close'):
... | ['def', 'debug_application(self,', 'environ,', 'start_response):', 'app_iter', '=', 'None', 'try:', 'app_iter', '=', 'self.app(environ,', 'start_response)', 'for', 'item', 'in', 'app_iter:', 'yield', 'item', 'if', 'hasattr(app_iter,', "'close'):", 'app_iter.close()', 'except', 'Exception:', 'if', 'hasattr(app_iter,', "... | 205,035 |
ifwe/digsby | textutil.py | GetFontHeight | GetFontHeight | Calculates the height of a font in pixels. | [
"Calculates",
"the",
"height",
"of",
"a",
"font",
"in",
"pixels."
] | def GetFontHeight(font=None, dc=None, line_height=False, descent=False):
assert font or dc
dc = dc or get_measuring_context()
if font:
dc.SetFont(font)
else:
font = dc.Font
nativeinfo = font.NativeFontInfoDesc
try:
extents = _heightcache[nativeinfo]
except KeyError:
... | ['def', 'GetFontHeight(font=None,', 'dc=None,', 'line_height=False,', 'descent=False):', 'assert', 'font', 'or', 'dc', 'dc', '=', 'dc', 'or', 'get_measuring_context()', 'if', 'font:', 'dc.SetFont(font)', 'else:', 'font', '=', 'dc.Font', 'nativeinfo', '=', 'font.NativeFontInfoDesc', 'try:', 'extents', '=', '_heightcache... | 185,314 |
rudranil723/mini-main | woff2.py | WOFF2DirectoryEntry.transformed | transformed | Return True if the table has any transformation, else return False. | [
"Return",
"True",
"if",
"the",
"table",
"has",
"any",
"transformation,",
"else",
"return",
"False."
] | def transformed(self):
if self.tag in {'glyf', 'loca'}:
return self.transformVersion != 3
else:
return self.transformVersion != 0 | ['def', 'transformed(self):', 'if', 'self.tag', 'in', "{'glyf',", "'loca'}:", 'return', 'self.transformVersion', '!=', '3', 'else:', 'return', 'self.transformVersion', '!=', '0'] | 317,437 |
011235813/cm3 | networks.py | Q_global | Q_global | Used by COMA for both SUMO and particle experiments. | [
"Used",
"by",
"COMA",
"for",
"both",
"SUMO",
"and",
"particle",
"experiments."
] | def Q_global(v_global, action_others, v_goal, v_goal_others, agent_labels, v_obs, n_actions=5, stage=2, units=256):
n_others = action_others.get_shape().as_list()[1]
actions_reshaped = tf.reshape(action_others, [-1, n_others * n_actions])
concated = tf.concat([v_global, actions_reshaped, v_goal, v_goal_othe... | ['def', 'Q_global(v_global,', 'action_others,', 'v_goal,', 'v_goal_others,', 'agent_labels,', 'v_obs,', 'n_actions=5,', 'stage=2,', 'units=256):', 'n_others', '=', 'action_others.get_shape().as_list()[1]', 'actions_reshaped', '=', 'tf.reshape(action_others,', '[-1,', 'n_others', '*', 'n_actions])', 'concated', '=', 'tf... | 488,602 |
intel/neural-compressor | strategy.py | TuneStrategy.pre_tuning_algo_scheduler | pre_tuning_algo_scheduler | Sets the pre-tuning algo scheduler. | [
"Sets",
"the",
"pre-tuning",
"algo",
"scheduler."
] | def pre_tuning_algo_scheduler(self, algo_scheduler):
self._pre_tuning_algo_scheduler = algo_scheduler | ['def', 'pre_tuning_algo_scheduler(self,', 'algo_scheduler):', 'self._pre_tuning_algo_scheduler', '=', 'algo_scheduler'] | 721,404 |
arshpreetsingh/quantopian-machinelearning | _utils.py | equal | equal | Check if two things are equal, but evade booleans and ints being equal. | [
"Check",
"if",
"two",
"things",
"are",
"equal,",
"but",
"evade",
"booleans",
"and",
"ints",
"being",
"equal."
] | def equal(one, two):
return unbool(one) == unbool(two) | ['def', 'equal(one,', 'two):', 'return', 'unbool(one)', '==', 'unbool(two)'] | 887,706 |
andrewekhalel/edafa | pnasnet.py | build_pnasnet_large | build_pnasnet_large | Build PNASNet Large model for the ImageNet Dataset. | [
"Build",
"PNASNet",
"Large",
"model",
"for",
"the",
"ImageNet",
"Dataset."
] | def build_pnasnet_large(images, num_classes, is_training=True, final_endpoint=None, config=None):
hparams = copy.deepcopy(config) if config else large_imagenet_config()
nasnet._update_hparams(hparams, is_training)
if tf.test.is_gpu_available() and hparams.data_format == 'NHWC':
tf.logging.info('A GP... | ['def', 'build_pnasnet_large(images,', 'num_classes,', 'is_training=True,', 'final_endpoint=None,', 'config=None):', 'hparams', '=', 'copy.deepcopy(config)', 'if', 'config', 'else', 'large_imagenet_config()', 'nasnet._update_hparams(hparams,', 'is_training)', 'if', 'tf.test.is_gpu_available()', 'and', 'hparams.data_for... | 548,084 |
google-research/scenic | test_optimizers.py | OptimizersTest.test_sgd | test_sgd | Test obtaining basic sgd optimizer. | [
"Test",
"obtaining",
"basic",
"sgd",
"optimizer."
] | def test_sgd(self):
optimizer_config = ml_collections.ConfigDict()
optimizer_config.optimizer = 'sgd'
optimizer = optimizers.get_optimizer(optimizer_config, self.lr, self.params)
optimizer_state = optimizer.init(self.params)
(_, grad) = self.compute_gradient_fn(self.params, self.label_causing_loss)
... | ['def', 'test_sgd(self):', 'optimizer_config', '=', 'ml_collections.ConfigDict()', 'optimizer_config.optimizer', '=', "'sgd'", 'optimizer', '=', 'optimizers.get_optimizer(optimizer_config,', 'self.lr,', 'self.params)', 'optimizer_state', '=', 'optimizer.init(self.params)', '(_,', 'grad)', '=', 'self.compute_gradient_fn... | 847,668 |
kubeflow/pipelines | spec_input_parsers.py | SpecInputParsers.yaml_or_json_dict | yaml_or_json_dict | Parses a YAML or JSON dictionary to a Python dictionary. | [
"Parses",
"a",
"YAML",
"or",
"JSON",
"dictionary",
"to",
"a",
"Python",
"dictionary."
] | def yaml_or_json_dict(value):
parsed = SpecInputParsers._yaml_or_json_str(value)
if parsed is not None and (not isinstance(parsed, Dict)):
raise ArgumentTypeError(f'{value} (type {type(value)}) is not a dictionary')
return parsed | ['def', 'yaml_or_json_dict(value):', 'parsed', '=', 'SpecInputParsers._yaml_or_json_str(value)', 'if', 'parsed', 'is', 'not', 'None', 'and', '(not', 'isinstance(parsed,', 'Dict)):', 'raise', "ArgumentTypeError(f'{value}", '(type', '{type(value)})', 'is', 'not', 'a', "dictionary')", 'return', 'parsed'] | 770,676 |
moscow25/deep_draw | draw_poker.py | create_iter_functions | create_iter_functions | Create functions for training, validation and testing to iterate one epoch. | [
"Create",
"functions",
"for",
"training,",
"validation",
"and",
"testing",
"to",
"iterate",
"one",
"epoch."
] | def create_iter_functions(dataset, output_layer, X_tensor_type=T.tensor4, batch_size=BATCH_SIZE, learning_rate=LEARNING_RATE, momentum=MOMENTUM):
print('creating iter funtions')
print('input dataset %s' % dataset)
batch_index = T.iscalar('batch_index')
X_batch = X_tensor_type('x')
y_batch = T.ivecto... | ['def', 'create_iter_functions(dataset,', 'output_layer,', 'X_tensor_type=T.tensor4,', 'batch_size=BATCH_SIZE,', 'learning_rate=LEARNING_RATE,', 'momentum=MOMENTUM):', "print('creating", 'iter', "funtions')", "print('input", 'dataset', "%s'", '%', 'dataset)', 'batch_index', '=', "T.iscalar('batch_index')", 'X_batch', '... | 181,086 |
Ruturaj123/Flowchart-Detection | execute.py | args_to_mixed_eager_tensors | args_to_mixed_eager_tensors | Converts a list of same-length lists of values to eager tensors. | [
"Converts",
"a",
"list",
"of",
"same-length",
"lists",
"of",
"values",
"to",
"eager",
"tensors."
] | def args_to_mixed_eager_tensors(lists):
assert len(lists) > 1
lists_ret = []
for l in lists[1:]:
if len(l) != len(lists[0]):
raise ValueError('Expected list arguments to be the same length: %d != %d (%r vs. %r)' % (len(lists[0]), len(l), lists[0], l))
lists_ret.append([])
typ... | ['def', 'args_to_mixed_eager_tensors(lists):', 'assert', 'len(lists)', '>', '1', 'lists_ret', '=', '[]', 'for', 'l', 'in', 'lists[1:]:', 'if', 'len(l)', '!=', 'len(lists[0]):', 'raise', "ValueError('Expected", 'list', 'arguments', 'to', 'be', 'the', 'same', 'length:', '%d', '!=', '%d', '(%r', 'vs.', "%r)'", '%', '(len(... | 605,166 |
OpenMDAO/OpenMDAO-Framework | hasconstraints.py | _HasConstraintsBase.parent | parent | The object we are a delegate of. | [
"The",
"object",
"we",
"are",
"a",
"delegate",
"of."
] | def parent(self):
return None if self._parent is None else self._parent() | ['def', 'parent(self):', 'return', 'None', 'if', 'self._parent', 'is', 'None', 'else', 'self._parent()'] | 275,683 |
PacktPublishing/Hands-On-Reinforcement-Learning-for-Games | deepmind.py | PillEater.start | start | Starts a new episode. | [
"Starts",
"a",
"new",
"episode."
] | def start(self):
self.frame = 0
self._init_level(1)
self.reward = 0
self.pcontinue = 1
self.ghost_speed = self.ghost_speed_init
return (self._make_image(), self.reward, self.pcontinue) | ['def', 'start(self):', 'self.frame', '=', '0', 'self._init_level(1)', 'self.reward', '=', '0', 'self.pcontinue', '=', '1', 'self.ghost_speed', '=', 'self.ghost_speed_init', 'return', '(self._make_image(),', 'self.reward,', 'self.pcontinue)'] | 205,272 |
enuguru/artificial_intelligence_and_machine_learning | sql.py | TokenList.insert_before | insert_before | Inserts *token* before *where*. | [
"Inserts",
"*token*",
"before",
"*where*."
] | def insert_before(self, where, token):
self.tokens.insert(self.token_index(where), token) | ['def', 'insert_before(self,', 'where,', 'token):', 'self.tokens.insert(self.token_index(where),', 'token)'] | 161,023 |
replit-archive/empythoned | __init__.py | Handler.acquire | acquire | Acquire the I/O thread lock. | [
"Acquire",
"the",
"I/O",
"thread",
"lock."
] | def acquire(self):
if self.lock:
self.lock.acquire() | ['def', 'acquire(self):', 'if', 'self.lock:', 'self.lock.acquire()'] | 177,715 |
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations | util.py | copy_obs_dict | copy_obs_dict | Deep-copy an observation dict. | [
"Deep-copy",
"an",
"observation",
"dict."
] | def copy_obs_dict(obs):
return {k: np.copy(v) for (k, v) in obs.items()} | ['def', 'copy_obs_dict(obs):', 'return', '{k:', 'np.copy(v)', 'for', '(k,', 'v)', 'in', 'obs.items()}'] | 432,803 |
OpenMDAO/OpenMDAO-Framework | test_wrkpool.py | TestCase.tearDown | tearDown | Invoked after each test. | [
"Invoked",
"after",
"each",
"test."
] | def tearDown(self):
self.reply_q = None | ['def', 'tearDown(self):', 'self.reply_q', '=', 'None'] | 276,330 |
43Carrig/recurrent_neural_networks_practice | image_ops.py | compose_transforms | compose_transforms | Composes the transforms tensors. | [
"Composes",
"the",
"transforms",
"tensors."
] | def compose_transforms(*transforms):
assert transforms, 'transforms cannot be empty'
with ops.name_scope('compose_transforms'):
composed = flat_transforms_to_matrices(transforms[0])
for tr in transforms[1:]:
composed = math_ops.matmul(composed, flat_transforms_to_matrices(tr))
... | ['def', 'compose_transforms(*transforms):', 'assert', 'transforms,', "'transforms", 'cannot', 'be', "empty'", 'with', "ops.name_scope('compose_transforms'):", 'composed', '=', 'flat_transforms_to_matrices(transforms[0])', 'for', 'tr', 'in', 'transforms[1:]:', 'composed', '=', 'math_ops.matmul(composed,', 'flat_transfor... | 313,311 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model.py | Model.fit_values | fit_values | Train value network using value-specific optimizer. | [
"Train",
"value",
"network",
"using",
"value-specific",
"optimizer."
] | def fit_values(self, sess, observations, internal_state, actions, rewards, terminated, pads):
feed_dict = {self.internal_state: internal_state, self.rewards: rewards, self.terminated: terminated, self.pads: pads}
for (action_place, action) in zip(self.actions, actions):
feed_dict[action_place] = action
... | ['def', 'fit_values(self,', 'sess,', 'observations,', 'internal_state,', 'actions,', 'rewards,', 'terminated,', 'pads):', 'feed_dict', '=', '{self.internal_state:', 'internal_state,', 'self.rewards:', 'rewards,', 'self.terminated:', 'terminated,', 'self.pads:', 'pads}', 'for', '(action_place,', 'action)', 'in', 'zip(se... | 26,110 |
THUNLP-MT/THUCC | networks.py | Network.updates | updates | Defines the list of functions that update the network parameters. | [
"Defines",
"the",
"list",
"of",
"functions",
"that",
"update",
"the",
"network",
"parameters."
] | def updates(self, cost):
updates = []
for layer in filter(lambda x: x not in self.exceptions, self.layers):
for update in layer.updates(cost):
(param, _) = update
if param not in self.exceptions:
updates.append(update)
return updates | ['def', 'updates(self,', 'cost):', 'updates', '=', '[]', 'for', 'layer', 'in', 'filter(lambda', 'x:', 'x', 'not', 'in', 'self.exceptions,', 'self.layers):', 'for', 'update', 'in', 'layer.updates(cost):', '(param,', '_)', '=', 'update', 'if', 'param', 'not', 'in', 'self.exceptions:', 'updates.append(update)', 'return', ... | 916,250 |
rwth-i6/returnn | test_TFNetworkRecLayer.py | test_convert_lstm_params_save_load | test_convert_lstm_params_save_load | Test conversions from different units to different units. | [
"Test",
"conversions",
"from",
"different",
"units",
"to",
"different",
"units."
] | def test_convert_lstm_params_save_load():
(n_in, n_hidden0, n_hidden1, n_hidden2, n_out) = (2, 5, 7, 11, 3)
def make_config(lstm_unit):
unit_opts = {}
if lstm_unit.lower() in {'standardlstm', 'basiclstm', 'lstmblock', 'lstmblockfused'}:
unit_opts['forget_bias'] = 0.0
net_dic... | ['def', 'test_convert_lstm_params_save_load():', '(n_in,', 'n_hidden0,', 'n_hidden1,', 'n_hidden2,', 'n_out)', '=', '(2,', '5,', '7,', '11,', '3)', 'def', 'make_config(lstm_unit):', 'unit_opts', '=', '{}', 'if', 'lstm_unit.lower()', 'in', "{'standardlstm',", "'basiclstm',", "'lstmblock',", "'lstmblockfused'}:", "unit_o... | 348,428 |
aws/sagemaker-training-toolkit | files.py | write_file | write_file | Write data to a file. | [
"Write",
"data",
"to",
"a",
"file."
] | def write_file(path, data, mode='w'):
with open(path, mode) as f:
f.write(data) | ['def', 'write_file(path,', 'data,', "mode='w'):", 'with', 'open(path,', 'mode)', 'as', 'f:', 'f.write(data)'] | 845,033 |
devashish-patel/webcam-motion-detector | basic.py | load_abort_and_exit_bindings | load_abort_and_exit_bindings | Basic bindings for abort (Ctrl-C) and exit (Ctrl-D). | [
"Basic",
"bindings",
"for",
"abort",
"(Ctrl-C)",
"and",
"exit",
"(Ctrl-D)."
] | def load_abort_and_exit_bindings():
registry = Registry()
handle = registry.add_binding
@handle(Keys.ControlC)
def _(event):
event.cli.abort()
@Condition
def ctrl_d_condition(cli):
return cli.current_buffer_name == DEFAULT_BUFFER and (not cli.current_buffer.text)
handle(Key... | ['def', 'load_abort_and_exit_bindings():', 'registry', '=', 'Registry()', 'handle', '=', 'registry.add_binding', '@handle(Keys.ControlC)', 'def', '_(event):', 'event.cli.abort()', '@Condition', 'def', 'ctrl_d_condition(cli):', 'return', 'cli.current_buffer_name', '==', 'DEFAULT_BUFFER', 'and', '(not', 'cli.current_buff... | 983,913 |
pramodiperera/virtual-keyboard | __init__.py | MemoizedZipManifests.load | load | Load a manifest at path or return a suitable manifest already loaded. | [
"Load",
"a",
"manifest",
"at",
"path",
"or",
"return",
"a",
"suitable",
"manifest",
"already",
"loaded."
] | def load(self, path):
path = os.path.normpath(path)
mtime = os.stat(path).st_mtime
if path not in self or self[path].mtime != mtime:
manifest = self.build(path)
self[path] = self.manifest_mod(manifest, mtime)
return self[path].manifest | ['def', 'load(self,', 'path):', 'path', '=', 'os.path.normpath(path)', 'mtime', '=', 'os.stat(path).st_mtime', 'if', 'path', 'not', 'in', 'self', 'or', 'self[path].mtime', '!=', 'mtime:', 'manifest', '=', 'self.build(path)', 'self[path]', '=', 'self.manifest_mod(manifest,', 'mtime)', 'return', 'self[path].manifest'] | 932,802 |
ctu-vras/traversability_estimation | segmentation.py | fit_sticks | fit_sticks | Segment points into planes. | [
"Segment",
"points",
"into",
"planes."
] | def fit_sticks(x, distance_threshold, max_iterations=1000, **kwargs):
assert isinstance(x, np.ndarray)
assert isinstance(distance_threshold, float)
assert distance_threshold >= 0.0
if x.dtype.names:
x = structured_to_unstructured(x[['x', 'y', 'z']])
models = fit_models_iteratively(x, lambda ... | ['def', 'fit_sticks(x,', 'distance_threshold,', 'max_iterations=1000,', '**kwargs):', 'assert', 'isinstance(x,', 'np.ndarray)', 'assert', 'isinstance(distance_threshold,', 'float)', 'assert', 'distance_threshold', '>=', '0.0', 'if', 'x.dtype.names:', 'x', '=', "structured_to_unstructured(x[['x',", "'y',", "'z']])", 'mo... | 951,358 |
IBM/mi-prometheus | stim_generator.py | ObjectSet.shift | shift | Shift every object in the set. | [
"Shift",
"every",
"object",
"in",
"the",
"set."
] | def shift(self, x):
self.n_epoch += x
if self.n_epoch < 1:
raise ValueError('n_epoch + x <= 0')
new_set = list()
new_end_epoch = list()
new_dict = defaultdict(list)
for obj in self.set:
obj.epoch[0] = max((0, obj.epoch[0] + x))
obj.epoch[1] += x
if obj.epoch[1] > ... | ['def', 'shift(self,', 'x):', 'self.n_epoch', '+=', 'x', 'if', 'self.n_epoch', '<', '1:', 'raise', "ValueError('n_epoch", '+', 'x', '<=', "0')", 'new_set', '=', 'list()', 'new_end_epoch', '=', 'list()', 'new_dict', '=', 'defaultdict(list)', 'for', 'obj', 'in', 'self.set:', 'obj.epoch[0]', '=', 'max((0,', 'obj.epoch[0]'... | 635,741 |
aws/sagemaker-python-sdk | lineage_trial_component.py | LineageTrialComponent.dataset_artifacts | dataset_artifacts | Use the lineage query to retrieve datasets that use this trial component. | [
"Use",
"the",
"lineage",
"query",
"to",
"retrieve",
"datasets",
"that",
"use",
"this",
"trial",
"component."
] | def dataset_artifacts(self, direction: LineageQueryDirectionEnum=LineageQueryDirectionEnum.ASCENDANTS) -> List[Artifact]:
query_filter = LineageFilter(entities=[LineageEntityEnum.ARTIFACT], sources=[LineageSourceEnum.DATASET])
query_result = LineageQuery(self.sagemaker_session).query(start_arns=[self.trial_comp... | ['def', 'dataset_artifacts(self,', 'direction:', 'LineageQueryDirectionEnum=LineageQueryDirectionEnum.ASCENDANTS)', '->', 'List[Artifact]:', 'query_filter', '=', 'LineageFilter(entities=[LineageEntityEnum.ARTIFACT],', 'sources=[LineageSourceEnum.DATASET])', 'query_result', '=', 'LineageQuery(self.sagemaker_session).que... | 830,282 |
openvinotoolkit/training_extensions | no_bias_decay_hook.py | NoBiasDecayHook.after_train_epoch | after_train_epoch | Merge splited groups before saving checkpoint. | [
"Merge",
"splited",
"groups",
"before",
"saving",
"checkpoint."
] | def after_train_epoch(self, runner):
params = []
for module in runner.model.modules():
if isinstance(module, (nn.Conv2d, nn.Linear)):
params.append(module.weight)
if module.bias is not None:
params.append(module.bias)
elif hasattr(module, 'weight') or hasa... | ['def', 'after_train_epoch(self,', 'runner):', 'params', '=', '[]', 'for', 'module', 'in', 'runner.model.modules():', 'if', 'isinstance(module,', '(nn.Conv2d,', 'nn.Linear)):', 'params.append(module.weight)', 'if', 'module.bias', 'is', 'not', 'None:', 'params.append(module.bias)', 'elif', 'hasattr(module,', "'weight')"... | 917,841 |
ArtificialIntelligenceToolkit/aitk.robots | bulbs.py | Bulb.initialize | initialize | Internal method to set all settings to default values. | [
"Internal",
"method",
"to",
"set",
"all",
"settings",
"to",
"default",
"values."
] | def initialize(self):
self.type = 'bulb'
self.state = 'on'
self.dist_from_center = distance(0, 0, self._x, self._y)
self.dir_from_center = math.atan2(-self._x, self._y) | ['def', 'initialize(self):', 'self.type', '=', "'bulb'", 'self.state', '=', "'on'", 'self.dist_from_center', '=', 'distance(0,', '0,', 'self._x,', 'self._y)', 'self.dir_from_center', '=', 'math.atan2(-self._x,', 'self._y)'] | 86,705 |
facebookresearch/dmae_st | meters.py | topk_accuracies | topk_accuracies | Computes the top-k accuracy for each k. | [
"Computes",
"the",
"top-k",
"accuracy",
"for",
"each",
"k."
] | def topk_accuracies(preds, labels, ks):
num_topks_correct = topks_correct(preds, labels, ks)
return [x / preds.size(0) * 100.0 for x in num_topks_correct] | ['def', 'topk_accuracies(preds,', 'labels,', 'ks):', 'num_topks_correct', '=', 'topks_correct(preds,', 'labels,', 'ks)', 'return', '[x', '/', 'preds.size(0)', '*', '100.0', 'for', 'x', 'in', 'num_topks_correct]'] | 521,995 |
GeekLiB/keras | test_image_data_tasks.py | test_image_classification | test_image_classification | Classify random 16x16 color images into several classes using logistic regression with convolutional hidden layer. | [
"Classify",
"random",
"16x16",
"color",
"images",
"into",
"several",
"classes",
"using",
"logistic",
"regression",
"with",
"convolutional",
"hidden",
"layer."
] | def test_image_classification():
np.random.seed(1337)
input_shape = (16, 16, 3)
((X_train, y_train), (X_test, y_test)) = get_test_data(nb_train=500, nb_test=200, input_shape=input_shape, classification=True, nb_class=4)
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)
nb_conv = ... | ['def', 'test_image_classification():', 'np.random.seed(1337)', 'input_shape', '=', '(16,', '16,', '3)', '((X_train,', 'y_train),', '(X_test,', 'y_test))', '=', 'get_test_data(nb_train=500,', 'nb_test=200,', 'input_shape=input_shape,', 'classification=True,', 'nb_class=4)', 'y_train', '=', 'to_categorical(y_train)', 'y... | 247,904 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_template.py | FigureCanvasTemplate.draw | draw | Draw the figure using the renderer. | [
"Draw",
"the",
"figure",
"using",
"the",
"renderer."
] | def draw(self):
renderer = RendererTemplate(self.figure.dpi)
self.figure.draw(renderer) | ['def', 'draw(self):', 'renderer', '=', 'RendererTemplate(self.figure.dpi)', 'self.figure.draw(renderer)'] | 257,693 |
mindsdb/lightwood | icp.py | IcpTSRegressor.calibrate | calibrate | After calibration, handles incomplete target information by imputing the row-wise mean. | [
"After",
"calibration,",
"handles",
"incomplete",
"target",
"information",
"by",
"imputing",
"the",
"row-wise",
"mean."
] | def calibrate(self, x, y, increment=False):
super(IcpTSRegressor, self).calibrate(x, y, increment)
for (k, v) in self.cal_scores.items():
row_mean = np.nanmean(v, axis=1)
idxs = np.where(np.isnan(v))
v[idxs] = np.take(row_mean, idxs[0])
self.cal_scores[k] = v | ['def', 'calibrate(self,', 'x,', 'y,', 'increment=False):', 'super(IcpTSRegressor,', 'self).calibrate(x,', 'y,', 'increment)', 'for', '(k,', 'v)', 'in', 'self.cal_scores.items():', 'row_mean', '=', 'np.nanmean(v,', 'axis=1)', 'idxs', '=', 'np.where(np.isnan(v))', 'v[idxs]', '=', 'np.take(row_mean,', 'idxs[0])', 'self.c... | 602,291 |
rudranil723/mini-main | __init__.py | GenericRpcHandler.service | service | Returns the handler for servicing the RPC. | [
"Returns",
"the",
"handler",
"for",
"servicing",
"the",
"RPC."
] | def service(self, handler_call_details):
raise NotImplementedError() | ['def', 'service(self,', 'handler_call_details):', 'raise', 'NotImplementedError()'] | 318,598 |
Ruturaj123/Flowchart-Detection | supervisor.py | Supervisor.summary_computed | summary_computed | Indicate that a summary was computed. | [
"Indicate",
"that",
"a",
"summary",
"was",
"computed."
] | def summary_computed(self, sess, summary, global_step=None):
if not self._summary_writer:
raise RuntimeError('Writing a summary requires a summary writer.')
if global_step is None and self.global_step is not None:
global_step = training_util.global_step(sess, self.global_step)
self._summary_... | ['def', 'summary_computed(self,', 'sess,', 'summary,', 'global_step=None):', 'if', 'not', 'self._summary_writer:', 'raise', "RuntimeError('Writing", 'a', 'summary', 'requires', 'a', 'summary', "writer.')", 'if', 'global_step', 'is', 'None', 'and', 'self.global_step', 'is', 'not', 'None:', 'global_step', '=', 'training_... | 606,614 |
Eric3911/OpenAGI | ssl_models.py | SpeechEncDecSelfSupervisedModel.decoder_loss_step | decoder_loss_step | Forward pass through all decoders and calculate corresponding losses. | [
"Forward",
"pass",
"through",
"all",
"decoders",
"and",
"calculate",
"corresponding",
"losses."
] | def decoder_loss_step(self, spectrograms, spec_masks, encoded, encoded_len, targets=None, target_lengths=None):
loss_val_dict = {}
if self.decoder_losses is None:
if hasattr(self.decoder_ssl, 'needs_labels') and self.decoder_ssl.needs_labels:
outputs = self.decoder_ssl(encoder_output=encoded... | ['def', 'decoder_loss_step(self,', 'spectrograms,', 'spec_masks,', 'encoded,', 'encoded_len,', 'targets=None,', 'target_lengths=None):', 'loss_val_dict', '=', '{}', 'if', 'self.decoder_losses', 'is', 'None:', 'if', 'hasattr(self.decoder_ssl,', "'needs_labels')", 'and', 'self.decoder_ssl.needs_labels:', 'outputs', '=', ... | 272,514 |
westerberg-science/openscope-glo-stim | translator.py | TrialTranslator.find_vsyncs | find_vsyncs | Finds stimulus vsync intervals. | [
"Finds",
"stimulus",
"vsync",
"intervals."
] | def find_vsyncs(self, exp_data):
intervals = exp_data['items']['behavior'].get('intervalsms', [])
if len(intervals) == 0:
vsyncs = exp_data['items']['behavior']['update_count']
intervals = [16.0] * vsyncs
return intervals | ['def', 'find_vsyncs(self,', 'exp_data):', 'intervals', '=', "exp_data['items']['behavior'].get('intervalsms',", '[])', 'if', 'len(intervals)', '==', '0:', 'vsyncs', '=', "exp_data['items']['behavior']['update_count']", 'intervals', '=', '[16.0]', '*', 'vsyncs', 'return', 'intervals'] | 757,689 |
sony/nnabla-rl | q_function.py | QFunction.q | q | Compute Q-value for given state and action. | [
"Compute",
"Q-value",
"for",
"given",
"state",
"and",
"action."
] | def q(self, s: nn.Variable, a: nn.Variable) -> nn.Variable:
raise NotImplementedError | ['def', 'q(self,', 's:', 'nn.Variable,', 'a:', 'nn.Variable)', '->', 'nn.Variable:', 'raise', 'NotImplementedError'] | 734,410 |
ZhAnGToNG1/transfer_learning_cspt | analyze_results.py | bbox_map_eval | bbox_map_eval | Evaluate mAP of single image det result. | [
"Evaluate",
"mAP",
"of",
"single",
"image",
"det",
"result."
] | def bbox_map_eval(det_result, annotation):
if isinstance(det_result, tuple):
bbox_det_result = [det_result[0]]
else:
bbox_det_result = [det_result]
iou_thrs = np.linspace(0.5, 0.95, int(np.round((0.95 - 0.5) / 0.05)) + 1, endpoint=True)
mean_aps = []
for thr in iou_thrs:
(mea... | ['def', 'bbox_map_eval(det_result,', 'annotation):', 'if', 'isinstance(det_result,', 'tuple):', 'bbox_det_result', '=', '[det_result[0]]', 'else:', 'bbox_det_result', '=', '[det_result]', 'iou_thrs', '=', 'np.linspace(0.5,', '0.95,', 'int(np.round((0.95', '-', '0.5)', '/', '0.05))', '+', '1,', 'endpoint=True)', 'mean_a... | 964,391 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | request.py | HTTPPasswordMgr.reduce_uri | reduce_uri | Accept authority or URI and extract only the authority and path. | [
"Accept",
"authority",
"or",
"URI",
"and",
"extract",
"only",
"the",
"authority",
"and",
"path."
] | def reduce_uri(self, uri, default_port=True):
parts = urlsplit(uri)
if parts[1]:
scheme = parts[0]
authority = parts[1]
path = parts[2] or '/'
else:
scheme = None
authority = uri
path = '/'
(host, port) = splitport(authority)
if default_port and port i... | ['def', 'reduce_uri(self,', 'uri,', 'default_port=True):', 'parts', '=', 'urlsplit(uri)', 'if', 'parts[1]:', 'scheme', '=', 'parts[0]', 'authority', '=', 'parts[1]', 'path', '=', 'parts[2]', 'or', "'/'", 'else:', 'scheme', '=', 'None', 'authority', '=', 'uri', 'path', '=', "'/'", '(host,', 'port)', '=', 'splitport(auth... | 377,211 |
amzn/xfer | metalogger.py | MetaLogger.log_loss | log_loss | Append loss to dictionary. | [
"Append",
"loss",
"to",
"dictionary."
] | def log_loss(self, metastep, task, epoch, loss):
if metastep not in self._losses.keys():
self._losses[metastep] = {}
if task not in self._losses[metastep].keys():
self._losses[metastep][task] = []
self._losses[metastep][task].append(loss) | ['def', 'log_loss(self,', 'metastep,', 'task,', 'epoch,', 'loss):', 'if', 'metastep', 'not', 'in', 'self._losses.keys():', 'self._losses[metastep]', '=', '{}', 'if', 'task', 'not', 'in', 'self._losses[metastep].keys():', 'self._losses[metastep][task]', '=', '[]', 'self._losses[metastep][task].append(loss)'] | 961,927 |
nlp-uoregon/trankit | modeling_tf_xlnet.py | TFXLNetMainLayer.cache_mem | cache_mem | cache hidden states into memory. | [
"cache",
"hidden",
"states",
"into",
"memory."
] | def cache_mem(self, curr_out, prev_mem):
if self.reuse_len is not None and self.reuse_len > 0:
curr_out = curr_out[:self.reuse_len]
if prev_mem is None:
new_mem = curr_out[-self.mem_len:]
else:
new_mem = tf.concat([prev_mem, curr_out], 0)[-self.mem_len:]
return tf.stop_gradient(n... | ['def', 'cache_mem(self,', 'curr_out,', 'prev_mem):', 'if', 'self.reuse_len', 'is', 'not', 'None', 'and', 'self.reuse_len', '>', '0:', 'curr_out', '=', 'curr_out[:self.reuse_len]', 'if', 'prev_mem', 'is', 'None:', 'new_mem', '=', 'curr_out[-self.mem_len:]', 'else:', 'new_mem', '=', 'tf.concat([prev_mem,', 'curr_out],',... | 920,192 |
tensorforce/tensorforce | environment.py | Environment.reset | reset | Resets the environment to start a new episode. | [
"Resets",
"the",
"environment",
"to",
"start",
"a",
"new",
"episode."
] | def reset(self, num_parallel=None):
raise NotImplementedError | ['def', 'reset(self,', 'num_parallel=None):', 'raise', 'NotImplementedError'] | 365,844 |
PKU-Alignment/safe-rlhf | trainer.py | CostTrainer.train_step | train_step | Perform a single training step. | [
"Perform",
"a",
"single",
"training",
"step."
] | def train_step(self, safer_input_ids: torch.LongTensor, safer_attention_mask: torch.BoolTensor, safer_safety_sign: torch.LongTensor, unsafer_input_ids: torch.LongTensor, unsafer_attention_mask: torch.BoolTensor, unsafer_safety_sign: torch.LongTensor) -> dict[str, Any]:
loss_dict = self.loss(safer_input_ids=safer_in... | ['def', 'train_step(self,', 'safer_input_ids:', 'torch.LongTensor,', 'safer_attention_mask:', 'torch.BoolTensor,', 'safer_safety_sign:', 'torch.LongTensor,', 'unsafer_input_ids:', 'torch.LongTensor,', 'unsafer_attention_mask:', 'torch.BoolTensor,', 'unsafer_safety_sign:', 'torch.LongTensor)', '->', 'dict[str,', 'Any]:'... | 829,214 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | utils.py | RouletteWheel.total_weight | total_weight | Total cumulative weight across all objects. | [
"Total",
"cumulative",
"weight",
"across",
"all",
"objects."
] | def total_weight(self):
if self.partial_sums:
return self.partial_sums[-1]
return 0.0 | ['def', 'total_weight(self):', 'if', 'self.partial_sums:', 'return', 'self.partial_sums[-1]', 'return', '0.0'] | 46,361 |
triaquae/triaquae | prime.py | randomized_primality_testing | randomized_primality_testing | Calculates whether n is composite (which is always correct) or prime (which is incorrect with error probability 2**-k) Returns False if the number is composite, and True if it's probably prime. | [
"Calculates",
"whether",
"n",
"is",
"composite",
"(which",
"is",
"always",
"correct)",
"or",
"prime",
"(which",
"is",
"incorrect",
"with",
"error",
"probability",
"2**-k)",
"Returns",
"False",
"if",
"the",
"number",
"is",
"composite,",
"and",
"True",
"if",
"it... | def randomized_primality_testing(n, k):
for _ in range(k):
x = rsa.randnum.randint(n - 1)
if jacobi_witness(x, n):
return False
return True | ['def', 'randomized_primality_testing(n,', 'k):', 'for', '_', 'in', 'range(k):', 'x', '=', 'rsa.randnum.randint(n', '-', '1)', 'if', 'jacobi_witness(x,', 'n):', 'return', 'False', 'return', 'True'] | 356,847 |
TengXiaoDai/DistributedCrawling | _bootstrap_external.py | SourceFileLoader.path_stats | path_stats | Return the metadata for the path. | [
"Return",
"the",
"metadata",
"for",
"the",
"path."
] | def path_stats(self, path):
st = _path_stat(path)
return {'mtime': st.st_mtime, 'size': st.st_size} | ['def', 'path_stats(self,', 'path):', 'st', '=', '_path_stat(path)', 'return', "{'mtime':", 'st.st_mtime,', "'size':", 'st.st_size}'] | 188,224 |
bolunwang/translearn | mimic_penalty_dssim.py | MimicPenaltyDSSIM.attack_batch | attack_batch | Run the attack on a batch of images and labels. | [
"Run",
"the",
"attack",
"on",
"a",
"batch",
"of",
"images",
"and",
"labels."
] | def attack_batch(self, source_imgs, target_imgs, weights):
nb_imgs = source_imgs.shape[0]
mask = [True] * nb_imgs + [False] * (self.batch_size - nb_imgs)
mask = np.array(mask, dtype=np.bool)
source_imgs = np.array(source_imgs)
target_imgs = np.array(target_imgs)
simg_tanh = self.preprocess_arcta... | ['def', 'attack_batch(self,', 'source_imgs,', 'target_imgs,', 'weights):', 'nb_imgs', '=', 'source_imgs.shape[0]', 'mask', '=', '[True]', '*', 'nb_imgs', '+', '[False]', '*', '(self.batch_size', '-', 'nb_imgs)', 'mask', '=', 'np.array(mask,', 'dtype=np.bool)', 'source_imgs', '=', 'np.array(source_imgs)', 'target_imgs',... | 951,271 |
surafelml/adapt-mnmt | adafactor.py | get_optimizer_from_params | get_optimizer_from_params | Get the Adafactor optimizer from user parameters. | [
"Get",
"the",
"Adafactor",
"optimizer",
"from",
"user",
"parameters."
] | def get_optimizer_from_params(optimizer_class, params, learning_rate=None):
params = copy.deepcopy(params)
decay_type = params.get('decay_type', 'pow')
if decay_type == 'pow':
decay_rate = adafactor_decay_rate_pow(float(params.get('memory_exponent', 0.8)))
elif decay_type == 'adam':
deca... | ['def', 'get_optimizer_from_params(optimizer_class,', 'params,', 'learning_rate=None):', 'params', '=', 'copy.deepcopy(params)', 'decay_type', '=', "params.get('decay_type',", "'pow')", 'if', 'decay_type', '==', "'pow':", 'decay_rate', '=', "adafactor_decay_rate_pow(float(params.get('memory_exponent',", '0.8)))', 'elif... | 407,990 |
gunthercox/ChatterBot | test_io.py | TestFromTxt.test_converters_cornercases | test_converters_cornercases | Test the conversion to datetime. | [
"Test",
"the",
"conversion",
"to",
"datetime."
] | def test_converters_cornercases(self):
converter = {'date': lambda s: strptime(s, '%Y-%m-%d %H:%M:%SZ')}
data = TextIO('2009-02-03 12:00:00Z, 72214.0')
test = np.ndfromtxt(data, delimiter=',', dtype=None, names=['date', 'stid'], converters=converter)
control = np.array((datetime(2009, 2, 3), 72214.0), d... | ['def', 'test_converters_cornercases(self):', 'converter', '=', "{'date':", 'lambda', 's:', 'strptime(s,', "'%Y-%m-%d", "%H:%M:%SZ')}", 'data', '=', "TextIO('2009-02-03", '12:00:00Z,', "72214.0')", 'test', '=', 'np.ndfromtxt(data,', "delimiter=',',", 'dtype=None,', "names=['date',", "'stid'],", 'converters=converter)',... | 531,501 |
JinliangLu96/CL_UNMT | dictionary.py | Dictionary.read_vocab | read_vocab | Create a dictionary from a vocabulary file. | [
"Create",
"a",
"dictionary",
"from",
"a",
"vocabulary",
"file."
] | def read_vocab(vocab_path):
skipped = 0
assert os.path.isfile(vocab_path), vocab_path
word2id = {BOS_WORD: 0, EOS_WORD: 1, PAD_WORD: 2, UNK_WORD: 3}
for i in range(SPECIAL_WORDS):
word2id[SPECIAL_WORD % i] = 4 + i
counts = {k: 0 for k in word2id.keys()}
f = open(vocab_path, 'r', encoding... | ['def', 'read_vocab(vocab_path):', 'skipped', '=', '0', 'assert', 'os.path.isfile(vocab_path),', 'vocab_path', 'word2id', '=', '{BOS_WORD:', '0,', 'EOS_WORD:', '1,', 'PAD_WORD:', '2,', 'UNK_WORD:', '3}', 'for', 'i', 'in', 'range(SPECIAL_WORDS):', 'word2id[SPECIAL_WORD', '%', 'i]', '=', '4', '+', 'i', 'counts', '=', '{k... | 123,184 |
kornia/kornia | draw.py | draw_rectangle | draw_rectangle | Draw N rectangles on a batch of image tensors. | [
"Draw",
"N",
"rectangles",
"on",
"a",
"batch",
"of",
"image",
"tensors."
] | def draw_rectangle(image: torch.Tensor, rectangle: torch.Tensor, color: Optional[torch.Tensor]=None, fill: Optional[bool]=None) -> torch.Tensor:
(batch, c, h, w) = image.shape
(batch_rect, num_rectangle, num_points) = rectangle.shape
if batch != batch_rect:
raise AssertionError('Image batch and rect... | ['def', 'draw_rectangle(image:', 'torch.Tensor,', 'rectangle:', 'torch.Tensor,', 'color:', 'Optional[torch.Tensor]=None,', 'fill:', 'Optional[bool]=None)', '->', 'torch.Tensor:', '(batch,', 'c,', 'h,', 'w)', '=', 'image.shape', '(batch_rect,', 'num_rectangle,', 'num_points)', '=', 'rectangle.shape', 'if', 'batch', '!='... | 622,296 |
bnpy/bnpy | Letters.py | get_data | get_data | Generate data as GroupXData object Guarantees that each letter is used at least once every 26 docs. | [
"Generate",
"data",
"as",
"GroupXData",
"object",
"Guarantees",
"that",
"each",
"letter",
"is",
"used",
"at",
"least",
"once",
"every",
"26",
"docs."
] | def get_data(nDocTotal=200, nObsPerDoc=300, nLetterPerDoc=3, seed=0, dstart=0, **kwargs):
nLetters = 26
PRNG = np.random.RandomState(seed)
LetterProbs = np.ones(nLetters)
for i in range(1, nLetters):
LetterProbs[i] = 0.95 * LetterProbs[i - 1]
LetterProbs /= LetterProbs.sum()
X = np.zeros... | ['def', 'get_data(nDocTotal=200,', 'nObsPerDoc=300,', 'nLetterPerDoc=3,', 'seed=0,', 'dstart=0,', '**kwargs):', 'nLetters', '=', '26', 'PRNG', '=', 'np.random.RandomState(seed)', 'LetterProbs', '=', 'np.ones(nLetters)', 'for', 'i', 'in', 'range(1,', 'nLetters):', 'LetterProbs[i]', '=', '0.95', '*', 'LetterProbs[i', '-'... | 464,620 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | mailbox.py | _PartialFile.tell | tell | Return the position with respect to start. | [
"Return",
"the",
"position",
"with",
"respect",
"to",
"start."
] | def tell(self):
return _ProxyFile.tell(self) - self._start | ['def', 'tell(self):', 'return', '_ProxyFile.tell(self)', '-', 'self._start'] | 428,894 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.