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
google-research/scenic
test_transforms.py
RandomResizeTest.test_resize_shape
test_resize_shape
Test whether resize produces the correct output shape.
[ "Test", "whether", "resize", "produces", "the", "correct", "output", "shape." ]
def test_resize_shape(self, size, max_size, expected_shape): features = fake_decoded_features(7, 5, 4) features_resized = transforms.resize(features, size, max_size=max_size) self.assertSequenceEqual(features_resized['inputs'].shape, expected_shape)
['def', 'test_resize_shape(self,', 'size,', 'max_size,', 'expected_shape):', 'features', '=', 'fake_decoded_features(7,', '5,', '4)', 'features_resized', '=', 'transforms.resize(features,', 'size,', 'max_size=max_size)', "self.assertSequenceEqual(features_resized['inputs'].shape,", 'expected_shape)']
846,689
matsu0228/nlp-jp
_expm_multiply.py
LazyOperatorNormInfo.onenorm
onenorm
Compute the exact 1-norm.
[ "Compute", "the", "exact", "1-norm." ]
def onenorm(self): if self._A_1_norm is None: self._A_1_norm = _exact_1_norm(self._A) return self._scale * self._A_1_norm
['def', 'onenorm(self):', 'if', 'self._A_1_norm', 'is', 'None:', 'self._A_1_norm', '=', '_exact_1_norm(self._A)', 'return', 'self._scale', '*', 'self._A_1_norm']
805,900
alex-petrenko/sample-factory
train_isaacgym.py
override_default_params_func
override_default_params_func
Most of these parameters are taken from IsaacGymEnvs default config files.
[ "Most", "of", "these", "parameters", "are", "taken", "from", "IsaacGymEnvs", "default", "config", "files." ]
def override_default_params_func(env, parser): parser.set_defaults(batched_sampling=True, num_workers=1, num_envs_per_worker=1, worker_num_splits=1, actor_worker_gpus=[0], train_for_env_steps=10000000, use_rnn=False, adaptive_stddev=False, policy_initialization='torch_default', env_gpu_actions=True, reward_scale=0....
['def', 'override_default_params_func(env,', 'parser):', 'parser.set_defaults(batched_sampling=True,', 'num_workers=1,', 'num_envs_per_worker=1,', 'worker_num_splits=1,', 'actor_worker_gpus=[0],', 'train_for_env_steps=10000000,', 'use_rnn=False,', 'adaptive_stddev=False,', "policy_initialization='torch_default',", 'env...
329,216
greydanus/mr_london
pildriver.py
PILDriver.do_invert
do_invert
usage: invert <image:pic1> Invert the top image.
[ "usage:", "invert", "<image:pic1>", "Invert", "the", "top", "image." ]
def do_invert(self): from PIL import ImageChops self.push(ImageChops.invert(self.do_pop()))
['def', 'do_invert(self):', 'from', 'PIL', 'import', 'ImageChops', 'self.push(ImageChops.invert(self.do_pop()))']
241,760
ludwig-ai/ludwig
archives.py
extract_archive
extract_archive
Extracts files from archive (into the same directory), returns a list of extracted files.
[ "Extracts", "files", "from", "archive", "(into", "the", "same", "directory),", "returns", "a", "list", "of", "extracted", "files." ]
def extract_archive(archive_path: str, archive_type: Optional[ArchiveType]=None) -> List[str]: if archive_type is None: archive_type = infer_archive_type(archive_path) if archive_type == ArchiveType.UNKNOWN: logger.error(f'Could not infer type of archive {archive_path}. May be an unsupported ar...
['def', 'extract_archive(archive_path:', 'str,', 'archive_type:', 'Optional[ArchiveType]=None)', '->', 'List[str]:', 'if', 'archive_type', 'is', 'None:', 'archive_type', '=', 'infer_archive_type(archive_path)', 'if', 'archive_type', '==', 'ArchiveType.UNKNOWN:', "logger.error(f'Could", 'not', 'infer', 'type', 'of', 'ar...
616,658
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
videos_to_tfrecords.py
AddSequences
AddSequences
Creates one training, validation.
[ "Creates", "one", "training,", "validation." ]
def AddSequences(): errors = [] sequences = FindPatternFiles(FLAGS.input_dir, FLAGS.view_pattern, errors) num_frames = PrintSequencesInfo(sequences, 'Found the following datasets and files:') if FLAGS.max_per_shard > 0: sequences = ShardSequences(sequences, FLAGS.max_per_shard) num_frame...
['def', 'AddSequences():', 'errors', '=', '[]', 'sequences', '=', 'FindPatternFiles(FLAGS.input_dir,', 'FLAGS.view_pattern,', 'errors)', 'num_frames', '=', 'PrintSequencesInfo(sequences,', "'Found", 'the', 'following', 'datasets', 'and', "files:')", 'if', 'FLAGS.max_per_shard', '>', '0:', 'sequences', '=', 'ShardSequen...
29,561
43Carrig/recurrent_neural_networks_practice
rnn_cell.py
IntersectionRNNCell.call
call
Run one step of the Intersection RNN.
[ "Run", "one", "step", "of", "the", "Intersection", "RNN." ]
def call(self, inputs, state): sigmoid = math_ops.sigmoid tanh = math_ops.tanh input_size = inputs.get_shape().with_rank(2)[1] if input_size.value is None: raise ValueError('Could not infer input size from inputs.get_shape()[-1]') with vs.variable_scope(vs.get_variable_scope(), initializer=s...
['def', 'call(self,', 'inputs,', 'state):', 'sigmoid', '=', 'math_ops.sigmoid', 'tanh', '=', 'math_ops.tanh', 'input_size', '=', 'inputs.get_shape().with_rank(2)[1]', 'if', 'input_size.value', 'is', 'None:', 'raise', "ValueError('Could", 'not', 'infer', 'input', 'size', 'from', "inputs.get_shape()[-1]')", 'with', 'vs.v...
335,117
locationlabs/mockredis
test_list.py
TestRedisList.test_rpush
test_rpush
Insertion maintains order but not uniqueness.
[ "Insertion", "maintains", "order", "but", "not", "uniqueness." ]
def test_rpush(self): eq_(1, self.redis.rpush(LIST1, VAL1)) eq_(2, self.redis.rpush(LIST1, VAL2)) eq_(b'list', self.redis.type(LIST1)) eq_([bVAL1, bVAL2], self.redis.lrange(LIST1, 0, -1)) eq_(4, self.redis.rpush(LIST1, VAL1, VAL3)) eq_(b'list', self.redis.type(LIST1)) eq_([bVAL1, bVAL2, bVAL...
['def', 'test_rpush(self):', 'eq_(1,', 'self.redis.rpush(LIST1,', 'VAL1))', 'eq_(2,', 'self.redis.rpush(LIST1,', 'VAL2))', "eq_(b'list',", 'self.redis.type(LIST1))', 'eq_([bVAL1,', 'bVAL2],', 'self.redis.lrange(LIST1,', '0,', '-1))', 'eq_(4,', 'self.redis.rpush(LIST1,', 'VAL1,', 'VAL3))', "eq_(b'list',", 'self.redis.ty...
240,652
LLNL/merlin
run_tests.py
clear_test_studies_dir
clear_test_studies_dir
Deletes the 'test_studies' directory, in order to preserve state each time cli tests are run.
[ "Deletes", "the", "'test_studies'", "directory,", "in", "order", "to", "preserve", "state", "each", "time", "cli", "tests", "are", "run." ]
def clear_test_studies_dir(): with suppress(FileNotFoundError): shutil.rmtree(f'./{OUTPUT_DIR}')
['def', 'clear_test_studies_dir():', 'with', 'suppress(FileNotFoundError):', "shutil.rmtree(f'./{OUTPUT_DIR}')"]
632,905
prophetlin/COMP3608-Artificial-Intelligence-Advanced
game_actions.py
SCORE
SCORE
Computes the SCORE of myself.
[ "Computes", "the", "SCORE", "of", "myself." ]
def SCORE(array_board, player): return 10 * NUM_IN_A_ROW(2, array_board, player) + 1000 * NUM_IN_A_ROW(3, array_board, player) + 1000 * NUM_IN_A_ROW(4, array_board, player)
['def', 'SCORE(array_board,', 'player):', 'return', '10', '*', 'NUM_IN_A_ROW(2,', 'array_board,', 'player)', '+', '1000', '*', 'NUM_IN_A_ROW(3,', 'array_board,', 'player)', '+', '1000', '*', 'NUM_IN_A_ROW(4,', 'array_board,', 'player)']
125,272
jxhe/unify-parameter-efficient-tuning
optimization.py
Adafactor.step
step
Performs a single optimization step Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss.
[ "Performs", "a", "single", "optimization", "step", "Arguments:", "closure", "(callable,", "optional):", "A", "closure", "that", "reevaluates", "the", "model", "and", "returns", "the", "loss." ]
def step(self, closure=None): loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad.data if grad.dtype in {torch.float16, torch.bfloat16}: ...
['def', 'step(self,', 'closure=None):', 'loss', '=', 'None', 'if', 'closure', 'is', 'not', 'None:', 'loss', '=', 'closure()', 'for', 'group', 'in', 'self.param_groups:', 'for', 'p', 'in', "group['params']:", 'if', 'p.grad', 'is', 'None:', 'continue', 'grad', '=', 'p.grad.data', 'if', 'grad.dtype', 'in', '{torch.float16...
948,374
chenbinghui1/DSL
coco.py
CocoDataset.xyxy2xywh
xyxy2xywh
Convert ``xyxy`` style bounding boxes to ``xywh`` style for COCO evaluation.
[ "Convert", "``xyxy``", "style", "bounding", "boxes", "to", "``xywh``", "style", "for", "COCO", "evaluation." ]
def xyxy2xywh(self, bbox): _bbox = bbox.tolist() return [_bbox[0], _bbox[1], _bbox[2] - _bbox[0], _bbox[3] - _bbox[1]]
['def', 'xyxy2xywh(self,', 'bbox):', '_bbox', '=', 'bbox.tolist()', 'return', '[_bbox[0],', '_bbox[1],', '_bbox[2]', '-', '_bbox[0],', '_bbox[3]', '-', '_bbox[1]]']
167,531
AboudyKreidieh/h-baselines
ant_maze_env.py
AntMazeEnv.viewer
viewer
Return the mujoco viewer object.
[ "Return", "the", "mujoco", "viewer", "object." ]
def viewer(self): return self.wrapped_env.viewer
['def', 'viewer(self):', 'return', 'self.wrapped_env.viewer']
573,839
zihuitang/medical_AI_platform
pdb.py
Pdb.do_tbreak
do_tbreak
tbreak [ ([filename:]lineno | function) [, condition] ] Same arguments as break, but sets a temporary breakpoint: it is automatically deleted when first hit.
[ "tbreak", "[", "([filename:]lineno", "|", "function)", "[,", "condition]", "]", "Same", "arguments", "as", "break,", "but", "sets", "a", "temporary", "breakpoint:", "it", "is", "automatically", "deleted", "when", "first", "hit." ]
def do_tbreak(self, arg): self.do_break(arg, 1)
['def', 'do_tbreak(self,', 'arg):', 'self.do_break(arg,', '1)']
281,014
sek788432/Waymo-2D-Object-Detection
weighted_sparse_categorical_crossentropy_test.py
ClassificationLossTest.test_legacy_lm_loss_compatibility
test_legacy_lm_loss_compatibility
Test to validate computational correctness during refactors.
[ "Test", "to", "validate", "computational", "correctness", "during", "refactors." ]
def test_legacy_lm_loss_compatibility(self): output_data = np.array([[[-2.5286622, -1.0963473, -1.4925185, -2.4451098, -1.2923571], [-2.7117882, -1.1205841, -4.02187, -0.9966936, -1.5119683]], [[-2.5379114, -0.82479054, -2.287932, -1.3747153, -2.053741], [-2.5379114, -0.82479054, -2.287932, -1.3747153, -2.053741]],...
['def', 'test_legacy_lm_loss_compatibility(self):', 'output_data', '=', 'np.array([[[-2.5286622,', '-1.0963473,', '-1.4925185,', '-2.4451098,', '-1.2923571],', '[-2.7117882,', '-1.1205841,', '-4.02187,', '-0.9966936,', '-1.5119683]],', '[[-2.5379114,', '-0.82479054,', '-2.287932,', '-1.3747153,', '-2.053741],', '[-2.53...
972,622
Eric3911/OpenAGI
interctc_mixin.py
InterCTCMixin.is_interctc_enabled
is_interctc_enabled
Returns whether interCTC loss is enabled.
[ "Returns", "whether", "interCTC", "loss", "is", "enabled." ]
def is_interctc_enabled(self) -> bool: self._verify_setup_was_called() return self.get_interctc_param('enabled')
['def', 'is_interctc_enabled(self)', '->', 'bool:', 'self._verify_setup_was_called()', 'return', "self.get_interctc_param('enabled')"]
272,687
sek788432/Waymo-2D-Object-Detection
preprocess_ops.py
resize_crop_filter
resize_crop_filter
Apply zooming to the image and boxes.
[ "Apply", "zooming", "to", "the", "image", "and", "boxes." ]
def resize_crop_filter(image, boxes, default_width, default_height, target_width, target_height): with tf.name_scope('resize_crop_filter'): image = tf.image.resize(image, (target_width, target_height)) image = tf.image.resize_with_crop_or_pad(image, target_height=default_height, target_width=default...
['def', 'resize_crop_filter(image,', 'boxes,', 'default_width,', 'default_height,', 'target_width,', 'target_height):', 'with', "tf.name_scope('resize_crop_filter'):", 'image', '=', 'tf.image.resize(image,', '(target_width,', 'target_height))', 'image', '=', 'tf.image.resize_with_crop_or_pad(image,', 'target_height=def...
973,396
matsu0228/nlp-jp
status.py
Status.update
update
Update the status of this request.
[ "Update", "the", "status", "of", "this", "request." ]
def update(self): status = self.route53connection.get_change(self.id)['GetChangeResponse']['ChangeInfo']['Status'] self.status = status return status
['def', 'update(self):', 'status', '=', "self.route53connection.get_change(self.id)['GetChangeResponse']['ChangeInfo']['Status']", 'self.status', '=', 'status', 'return', 'status']
785,183
huawei-noah/xingtian
timm_trainer_callback.py
TimmTrainerCallback.before_epoch
before_epoch
Be called before each epoch.
[ "Be", "called", "before", "each", "epoch." ]
def before_epoch(self, epoch, logs=None): if self.distributed: self.trainer.train_loader.sampler.set_epoch(epoch) self.num_updates = epoch * len(self.trainer.train_loader) self.epoch = epoch self.trainer.model.train()
['def', 'before_epoch(self,', 'epoch,', 'logs=None):', 'if', 'self.distributed:', 'self.trainer.train_loader.sampler.set_epoch(epoch)', 'self.num_updates', '=', 'epoch', '*', 'len(self.trainer.train_loader)', 'self.epoch', '=', 'epoch', 'self.trainer.model.train()']
968,389
uber/causalml
filters.py
FilterSelect.filter_F
filter_F
Rank features based on the F-statistics of the interaction.
[ "Rank", "features", "based", "on", "the", "F-statistics", "of", "the", "interaction." ]
def filter_F(self, data, treatment_indicator, features, y_name, order=1): if order not in [1, 2, 3]: raise Exception('ValueError: order argument only takes value 1,2,3.') all_result = pd.DataFrame() for x_name_i in features: one_result = self._filter_F_one_feature(data=data, treatment_indica...
['def', 'filter_F(self,', 'data,', 'treatment_indicator,', 'features,', 'y_name,', 'order=1):', 'if', 'order', 'not', 'in', '[1,', '2,', '3]:', 'raise', "Exception('ValueError:", 'order', 'argument', 'only', 'takes', 'value', "1,2,3.')", 'all_result', '=', 'pd.DataFrame()', 'for', 'x_name_i', 'in', 'features:', 'one_re...
456,407
facebookresearch/dinov2
__init__.py
FSDPCheckpointer.has_checkpoint
has_checkpoint
Returns: bool: whether a checkpoint exists in the target directory.
[ "Returns:", "bool:", "whether", "a", "checkpoint", "exists", "in", "the", "target", "directory." ]
def has_checkpoint(self) -> bool: save_file = os.path.join(self.save_dir, f'last_checkpoint.{rankstr()}') return self.path_manager.exists(save_file)
['def', 'has_checkpoint(self)', '->', 'bool:', 'save_file', '=', 'os.path.join(self.save_dir,', "f'last_checkpoint.{rankstr()}')", 'return', 'self.path_manager.exists(save_file)']
186,196
Ruturaj123/Flowchart-Detection
parser.py
_ClassPageInfo.properties
properties
Returns a list of `_PropertyInfo` describing the class' properties.
[ "Returns", "a", "list", "of", "`_PropertyInfo`", "describing", "the", "class'", "properties." ]
def properties(self): return self._properties
['def', 'properties(self):', 'return', 'self._properties']
606,756
Audio-WestlakeU/audiossl
byol_a.py
create_data_source
create_data_source
Creates data source object for downstream task you want.
[ "Creates", "data", "source", "object", "for", "downstream", "task", "you", "want." ]
def create_data_source(mode): assert mode in ['us8k', 'spcv1', 'spcv2', 'nsynth', 'fsdnoisy18k'] return TaskDataSource(mode)
['def', 'create_data_source(mode):', 'assert', 'mode', 'in', "['us8k',", "'spcv1',", "'spcv2',", "'nsynth',", "'fsdnoisy18k']", 'return', 'TaskDataSource(mode)']
93,316
iffiX/machin
pool.py
proxy_ctx_caller
proxy_ctx_caller
Call a serialized function with worker context and return results.
[ "Call", "a", "serialized", "function", "with", "worker", "context", "and", "return", "results." ]
def proxy_ctx_caller(*input_): if len(input_) == 1: (func_str, args, kwargs) = input_[0] else: (func_str, args, kwargs) = input_ func = loads(func_str) return func(CtxPoolStorage.storage, *args, **kwargs)
['def', 'proxy_ctx_caller(*input_):', 'if', 'len(input_)', '==', '1:', '(func_str,', 'args,', 'kwargs)', '=', 'input_[0]', 'else:', '(func_str,', 'args,', 'kwargs)', '=', 'input_', 'func', '=', 'loads(func_str)', 'return', 'func(CtxPoolStorage.storage,', '*args,', '**kwargs)']
620,360
imranparuk/speaker-recognition-3d-cnn
speechpy.py
lmfe
lmfe
Compute log Mel-filterbank energy features from an audio signal.
[ "Compute", "log", "Mel-filterbank", "energy", "features", "from", "an", "audio", "signal." ]
def lmfe(signal, sampling_frequency, frame_length=0.02, frame_stride=0.01, num_filters=40, fft_length=512, low_frequency=0, high_frequency=None): (feature, frame_energies) = mfe(signal, sampling_frequency=sampling_frequency, frame_length=frame_length, frame_stride=frame_stride, num_filters=num_filters, fft_length=f...
['def', 'lmfe(signal,', 'sampling_frequency,', 'frame_length=0.02,', 'frame_stride=0.01,', 'num_filters=40,', 'fft_length=512,', 'low_frequency=0,', 'high_frequency=None):', '(feature,', 'frame_energies)', '=', 'mfe(signal,', 'sampling_frequency=sampling_frequency,', 'frame_length=frame_length,', 'frame_stride=frame_st...
894,793
gunthercox/ChatterBot
plugins.py
GroupPlugin.do_groups
do_groups
This filter finds open and close bracket markers in a flat group and uses them to organize the nodes into a hierarchy.
[ "This", "filter", "finds", "open", "and", "close", "bracket", "markers", "in", "a", "flat", "group", "and", "uses", "them", "to", "organize", "the", "nodes", "into", "a", "hierarchy." ]
def do_groups(self, parser, group): (ob, cb) = (self.OpenBracket, self.CloseBracket) stack = [parser.group()] for node in group: if isinstance(node, ob): stack.append(parser.group()) elif isinstance(node, cb): if len(stack) > 1: last = stack.pop() ...
['def', 'do_groups(self,', 'parser,', 'group):', '(ob,', 'cb)', '=', '(self.OpenBracket,', 'self.CloseBracket)', 'stack', '=', '[parser.group()]', 'for', 'node', 'in', 'group:', 'if', 'isinstance(node,', 'ob):', 'stack.append(parser.group())', 'elif', 'isinstance(node,', 'cb):', 'if', 'len(stack)', '>', '1:', 'last', '...
526,928
openvinotoolkit/training_extensions
accuracy.py
compute_unnormalized_confusion_matrices_from_resultset
compute_unnormalized_confusion_matrices_from_resultset
Computes an (unnormalized) confusion matrix for every label group in the resultset.
[ "Computes", "an", "(unnormalized)", "confusion", "matrix", "for", "every", "label", "group", "in", "the", "resultset." ]
def compute_unnormalized_confusion_matrices_from_resultset(resultset: ResultSetEntity) -> List[MatrixMetric]: if len(resultset.ground_truth_dataset) == 0 or len(resultset.prediction_dataset) == 0: raise ValueError('Cannot compute the confusion matrix of an empty result set.') unnormalized_confusion_matr...
['def', 'compute_unnormalized_confusion_matrices_from_resultset(resultset:', 'ResultSetEntity)', '->', 'List[MatrixMetric]:', 'if', 'len(resultset.ground_truth_dataset)', '==', '0', 'or', 'len(resultset.prediction_dataset)', '==', '0:', 'raise', "ValueError('Cannot", 'compute', 'the', 'confusion', 'matrix', 'of', 'an',...
918,733
yekeren/Cap2Det
reader.py
get_input_fn
get_input_fn
Returns a function that generate input examples.
[ "Returns", "a", "function", "that", "generate", "input", "examples." ]
def get_input_fn(options): if not isinstance(options, reader_pb2.Reader): raise ValueError('options has to be an instance of Reader.') reader_oneof = options.WhichOneof('reader_oneof') if 'cap2det_reader' == reader_oneof: return cap2det_reader.get_input_fn(options.cap2det_reader) raise V...
['def', 'get_input_fn(options):', 'if', 'not', 'isinstance(options,', 'reader_pb2.Reader):', 'raise', "ValueError('options", 'has', 'to', 'be', 'an', 'instance', 'of', "Reader.')", 'reader_oneof', '=', "options.WhichOneof('reader_oneof')", 'if', "'cap2det_reader'", '==', 'reader_oneof:', 'return', 'cap2det_reader.get_i...
108,977
Farama-Foundation/Gymnasium
space_utils.py
batch_space
batch_space
Create a (batched) space, containing multiple copies of a single space.
[ "Create", "a", "(batched)", "space,", "containing", "multiple", "copies", "of", "a", "single", "space." ]
def batch_space(space: Space[Any], n: int=1) -> Space[Any]: raise TypeError(f'The space provided to `batch_space` is not a gymnasium Space instance, type: {type(space)}, {space}')
['def', 'batch_space(space:', 'Space[Any],', 'n:', 'int=1)', '->', 'Space[Any]:', 'raise', "TypeError(f'The", 'space', 'provided', 'to', '`batch_space`', 'is', 'not', 'a', 'gymnasium', 'Space', 'instance,', 'type:', '{type(space)},', "{space}')"]
573,143
sek788432/Waymo-2D-Object-Detection
tf_sequence_example_decoder.py
TFSequenceExampleDecoderHelper.list_items
list_items
Returns keys of items.
[ "Returns", "keys", "of", "items." ]
def list_items(self): return self._items_to_handlers.keys()
['def', 'list_items(self):', 'return', 'self._items_to_handlers.keys()']
974,488
neeharperi/FutureDet
parse.py
list_from_file
list_from_file
Load a text file and parse the content as a list of strings.
[ "Load", "a", "text", "file", "and", "parse", "the", "content", "as", "a", "list", "of", "strings." ]
def list_from_file(filename, prefix='', offset=0, max_num=0): cnt = 0 item_list = [] with open(filename, 'r') as f: for _ in range(offset): f.readline() for line in f: if max_num > 0 and cnt >= max_num: break item_list.append(prefix + line....
['def', 'list_from_file(filename,', "prefix='',", 'offset=0,', 'max_num=0):', 'cnt', '=', '0', 'item_list', '=', '[]', 'with', 'open(filename,', "'r')", 'as', 'f:', 'for', '_', 'in', 'range(offset):', 'f.readline()', 'for', 'line', 'in', 'f:', 'if', 'max_num', '>', '0', 'and', 'cnt', '>=', 'max_num:', 'break', 'item_li...
565,814
RLE-Foundation/rllte
performance.py
Performance.aggregate_mean
aggregate_mean
Computes mean of sample mean scores per task.
[ "Computes", "mean", "of", "sample", "mean", "scores", "per", "task." ]
def aggregate_mean(self) -> Union[np.ndarray, Tuple[np.ndarray, np.ndarray]]: def _thunk(scores): mean_task_scores = np.mean(scores, axis=0, keepdims=False) return np.mean(mean_task_scores, axis=0) if self.get_ci: CIs = self.get_interval_estimates(scores=self.scores, metric=_thunk) ...
['def', 'aggregate_mean(self)', '->', 'Union[np.ndarray,', 'Tuple[np.ndarray,', 'np.ndarray]]:', 'def', '_thunk(scores):', 'mean_task_scores', '=', 'np.mean(scores,', 'axis=0,', 'keepdims=False)', 'return', 'np.mean(mean_task_scores,', 'axis=0)', 'if', 'self.get_ci:', 'CIs', '=', 'self.get_interval_estimates(scores=sel...
333,554
googleapis/python-aiplatform
models.py
Endpoint.create
create
Creates a new endpoint.
[ "Creates", "a", "new", "endpoint." ]
def create(cls, display_name: Optional[str]=None, description: Optional[str]=None, labels: Optional[Dict[str, str]]=None, metadata: Optional[Sequence[Tuple[str, str]]]=(), project: Optional[str]=None, location: Optional[str]=None, credentials: Optional[auth_credentials.Credentials]=None, encryption_spec_key_name: Optio...
['def', 'create(cls,', 'display_name:', 'Optional[str]=None,', 'description:', 'Optional[str]=None,', 'labels:', 'Optional[Dict[str,', 'str]]=None,', 'metadata:', 'Optional[Sequence[Tuple[str,', 'str]]]=(),', 'project:', 'Optional[str]=None,', 'location:', 'Optional[str]=None,', 'credentials:', 'Optional[auth_credentia...
809,764
43Carrig/recurrent_neural_networks_practice
gen_math_ops.py
floor
floor
Returns element-wise largest integer not greater than x.
[ "Returns", "element-wise", "largest", "integer", "not", "greater", "than", "x." ]
def floor(x, name=None): _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: (_, _, _op) = _op_def_lib._apply_op_helper('Floor', x=x, name=name) _result = _op.outputs[:] _inputs_flat = _op.inputs _attrs = ('T', _op.get_attr('T')) _execute.record_...
['def', 'floor(x,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', '(_,', '_,', '_op)', '=', "_op_def_lib._apply_op_helper('Floor',", 'x=x,', 'name=name)', '_result', '=', '_op.outputs[:]', '_inputs_flat', '=', '_op.inputs', '_attrs', '=', "('T...
338,133
google-research/scenic
test_model_utils.py
LossTest.test_weighted_box_l1_loss
test_weighted_box_l1_loss
Test weighted_box_l1_loss against manually specified targets.
[ "Test", "weighted_box_l1_loss", "against", "manually", "specified", "targets." ]
def test_weighted_box_l1_loss(self): x1 = jnp.array([[0.1, 0.3, 0.9, 0.8]], dtype=jnp.float32) y1 = jnp.array([[0.5, 0.1, 0.9, 0.7]], dtype=jnp.float32) out1 = model_utils.weighted_box_l1_loss(x1, y1) out1_target = jnp.array([[0.4, 0.2, 0, 0.1]], dtype=jnp.float32) self.assertSequenceAlmostEqual(out...
['def', 'test_weighted_box_l1_loss(self):', 'x1', '=', 'jnp.array([[0.1,', '0.3,', '0.9,', '0.8]],', 'dtype=jnp.float32)', 'y1', '=', 'jnp.array([[0.5,', '0.1,', '0.9,', '0.7]],', 'dtype=jnp.float32)', 'out1', '=', 'model_utils.weighted_box_l1_loss(x1,', 'y1)', 'out1_target', '=', 'jnp.array([[0.4,', '0.2,', '0,', '0.1...
846,229
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
ccompiler.py
CCompiler.library_dir_option
library_dir_option
Return the compiler option to add 'dir' to the list of directories searched for libraries.
[ "Return", "the", "compiler", "option", "to", "add", "'dir'", "to", "the", "list", "of", "directories", "searched", "for", "libraries." ]
def library_dir_option(self, dir): raise NotImplementedError
['def', 'library_dir_option(self,', 'dir):', 'raise', 'NotImplementedError']
430,270
rudranil723/mini-main
featureVars.py
remapFeatures
remapFeatures
Go through the scripts list, and remap feature indices.
[ "Go", "through", "the", "scripts", "list,", "and", "remap", "feature", "indices." ]
def remapFeatures(table, featureRemap): for (scriptIndex, script) in enumerate(table.ScriptList.ScriptRecord): defaultLangSys = script.Script.DefaultLangSys if defaultLangSys is not None: _remapLangSys(defaultLangSys, featureRemap) for (langSysRecordIndex, langSysRec) in enumerat...
['def', 'remapFeatures(table,', 'featureRemap):', 'for', '(scriptIndex,', 'script)', 'in', 'enumerate(table.ScriptList.ScriptRecord):', 'defaultLangSys', '=', 'script.Script.DefaultLangSys', 'if', 'defaultLangSys', 'is', 'not', 'None:', '_remapLangSys(defaultLangSys,', 'featureRemap)', 'for', '(langSysRecordIndex,', 'l...
317,563
tensorflow/agents
utils.py
SquashToSpecNormal.mean
mean
Compute mean of the SquashToSpecNormal distribution.
[ "Compute", "mean", "of", "the", "SquashToSpecNormal", "distribution." ]
def mean(self, name='mean', **kwargs): return self.mode(name)
['def', 'mean(self,', "name='mean',", '**kwargs):', 'return', 'self.mode(name)']
23,395
asyml/texar-pytorch
embedder_base.py
EmbedderBase.num_embeds
num_embeds
The number of embedding elements.
[ "The", "number", "of", "embedding", "elements." ]
def num_embeds(self) -> int: return self._num_embeds
['def', 'num_embeds(self)', '->', 'int:', 'return', 'self._num_embeds']
925,206
huawei-noah/xingtian
mcts.py
Mcts.backpropagate
backpropagate
Propagate the evaluation all the way up the tree to the root at the end of a simulation.
[ "Propagate", "the", "evaluation", "all", "the", "way", "up", "the", "tree", "to", "the", "root", "at", "the", "end", "of", "a", "simulation." ]
def backpropagate(self, search_path, value): for node in search_path[::-1]: node.value_sum += value node.visit_count += 1 self.min_max_stats.update(node.value()) value = node.reward + self.discount * value
['def', 'backpropagate(self,', 'search_path,', 'value):', 'for', 'node', 'in', 'search_path[::-1]:', 'node.value_sum', '+=', 'value', 'node.visit_count', '+=', '1', 'self.min_max_stats.update(node.value())', 'value', '=', 'node.reward', '+', 'self.discount', '*', 'value']
962,054
Kvatsx/Artificial-Intelligence-Assignments
_tifffile.py
TiffFile.is_movie
is_movie
Return if file is a movie.
[ "Return", "if", "file", "is", "a", "movie." ]
def is_movie(self): return self.pages.useframes
['def', 'is_movie(self):', 'return', 'self.pages.useframes']
37,573
replit-archive/empythoned
_exceptions.py
SAXParseException.getSystemId
getSystemId
Get the system identifier of the entity where the exception occurred.
[ "Get", "the", "system", "identifier", "of", "the", "entity", "where", "the", "exception", "occurred." ]
def getSystemId(self): return self._systemId
['def', 'getSystemId(self):', 'return', 'self._systemId']
177,077
Eric3911/OpenAGI
rnnt.py
StatelessTransducerDecoder.batch_select_state
batch_select_state
Get decoder state from batch of states, for given id.
[ "Get", "decoder", "state", "from", "batch", "of", "states,", "for", "given", "id." ]
def batch_select_state(self, batch_states: List[torch.Tensor], idx: int) -> List[List[torch.Tensor]]: if batch_states is not None: states = batch_states[0][idx] states = states.long() return [states] else: return None
['def', 'batch_select_state(self,', 'batch_states:', 'List[torch.Tensor],', 'idx:', 'int)', '->', 'List[List[torch.Tensor]]:', 'if', 'batch_states', 'is', 'not', 'None:', 'states', '=', 'batch_states[0][idx]', 'states', '=', 'states.long()', 'return', '[states]', 'else:', 'return', 'None']
272,598
pokaxpoka/sunrise
utils.py
posdef_eig_self_adjoint
posdef_eig_self_adjoint
Computes eigendecomposition using self_adjoint_eig.
[ "Computes", "eigendecomposition", "using", "self_adjoint_eig." ]
def posdef_eig_self_adjoint(mat): (evals, evecs) = linalg_ops.self_adjoint_eig(mat) evals = math_ops.abs(evals) return (evals, evecs)
['def', 'posdef_eig_self_adjoint(mat):', '(evals,', 'evecs)', '=', 'linalg_ops.self_adjoint_eig(mat)', 'evals', '=', 'math_ops.abs(evals)', 'return', '(evals,', 'evecs)']
911,853
tobegit3hub/deep_image_model
edit.py
detach_inputs
detach_inputs
Detach the inputs of a subgraph view.
[ "Detach", "the", "inputs", "of", "a", "subgraph", "view." ]
def detach_inputs(sgv, control_inputs=False): sgv = subgraph.make_view(sgv) with sgv.graph.as_default(): input_placeholders = [tf_array_ops.placeholder(dtype=input_t.dtype, name=util.placeholder_name(input_t)) for input_t in sgv.inputs] reroute.swap_inputs(sgv, input_placeholders) if control_inp...
['def', 'detach_inputs(sgv,', 'control_inputs=False):', 'sgv', '=', 'subgraph.make_view(sgv)', 'with', 'sgv.graph.as_default():', 'input_placeholders', '=', '[tf_array_ops.placeholder(dtype=input_t.dtype,', 'name=util.placeholder_name(input_t))', 'for', 'input_t', 'in', 'sgv.inputs]', 'reroute.swap_inputs(sgv,', 'input...
181,329
poapper-inc/fights
base.py
BaseEnv.step
step
Step through the environment.
[ "Step", "through", "the", "environment." ]
def step(self, state: S, agent_id: int, action: A, *, pre_step_fn: Optional[Callable[[S, int, A], None]]=None, post_step_fn: Optional[Callable[[S, int, A], None]]=None) -> S: ...
['def', 'step(self,', 'state:', 'S,', 'agent_id:', 'int,', 'action:', 'A,', '*,', 'pre_step_fn:', 'Optional[Callable[[S,', 'int,', 'A],', 'None]]=None,', 'post_step_fn:', 'Optional[Callable[[S,', 'int,', 'A],', 'None]]=None)', '->', 'S:', '...']
180,065
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
objective.py
discounted_future_sum
discounted_future_sum
Discounted future sum of time-major values.
[ "Discounted", "future", "sum", "of", "time-major", "values." ]
def discounted_future_sum(values, discount, rollout): discount_filter = tf.reshape(discount ** tf.range(float(rollout)), [-1, 1, 1]) expanded_values = tf.concat([values, tf.zeros([rollout - 1, tf.shape(values)[1]])], 0) conv_values = tf.transpose(tf.squeeze(tf.nn.conv1d(tf.expand_dims(tf.transpose(expanded_...
['def', 'discounted_future_sum(values,', 'discount,', 'rollout):', 'discount_filter', '=', 'tf.reshape(discount', '**', 'tf.range(float(rollout)),', '[-1,', '1,', '1])', 'expanded_values', '=', 'tf.concat([values,', 'tf.zeros([rollout', '-', '1,', 'tf.shape(values)[1]])],', '0)', 'conv_values', '=', 'tf.transpose(tf.sq...
26,137
microsoft/maro
request_order.py
get_order_data
get_order_data
Get the order data within one tick.
[ "Get", "the", "order", "data", "within", "one", "tick." ]
def get_order_data(experiment_name: str, episode: str, tick: str) -> pd.DataFrame: params = {'query': f"select {request_column.order_header.value} from {experiment_name}.full_on_ports where episode='{episode}' and tick='{tick}'", 'count': 'true'} original_order_data = requests.get(url=request_settings.request_u...
['def', 'get_order_data(experiment_name:', 'str,', 'episode:', 'str,', 'tick:', 'str)', '->', 'pd.DataFrame:', 'params', '=', "{'query':", 'f"select', '{request_column.order_header.value}', 'from', '{experiment_name}.full_on_ports', 'where', "episode='{episode}'", 'and', 'tick=\'{tick}\'",', "'count':", "'true'}", 'ori...
628,310
tobegit3hub/deep_image_model
params_ops.py
Uf
Uf
Uniformly distributed floating number.
[ "Uniformly", "distributed", "floating", "number." ]
def Uf(lo=0.0, hi=1.0): return random.uniform(lo, hi)
['def', 'Uf(lo=0.0,', 'hi=1.0):', 'return', 'random.uniform(lo,', 'hi)']
182,067
0xangelo/raylab
__init__.py
dashboard
dashboard
Launch the experiment dashboard to monitor training progress.
[ "Launch", "the", "experiment", "dashboard", "to", "monitor", "training", "progress." ]
def dashboard(paths: tuple[str, ...]): import subprocess from . import experiment_dashboard subprocess.run(['streamlit', 'run', experiment_dashboard.__file__] + list(paths), check=True)
['def', 'dashboard(paths:', 'tuple[str,', '...]):', 'import', 'subprocess', 'from', '.', 'import', 'experiment_dashboard', "subprocess.run(['streamlit',", "'run',", 'experiment_dashboard.__file__]', '+', 'list(paths),', 'check=True)']
848,281
Deci-AI/super-gradients
pretrained_models_unit_test.py
PretrainedModelsUnitTest.test_pretrained_models_load_preprocessing_params
test_pretrained_models_load_preprocessing_params
Test that checks whether preprocessing params from pretrained model load correctly.
[ "Test", "that", "checks", "whether", "preprocessing", "params", "from", "pretrained", "model", "load", "correctly." ]
def test_pretrained_models_load_preprocessing_params(self): state = {'net': models.get(Models.YOLO_NAS_S, num_classes=80).state_dict(), 'processing_params': default_yolo_nas_coco_processing_params()} with tempfile.TemporaryDirectory() as td: checkpoint_path = os.path.join(td, 'yolo_nas_s_coco.pth') ...
['def', 'test_pretrained_models_load_preprocessing_params(self):', 'state', '=', "{'net':", 'models.get(Models.YOLO_NAS_S,', 'num_classes=80).state_dict(),', "'processing_params':", 'default_yolo_nas_coco_processing_params()}', 'with', 'tempfile.TemporaryDirectory()', 'as', 'td:', 'checkpoint_path', '=', 'os.path.join(...
880,680
googleapis/python-aiplatform
test_ray_prediction.py
TestPredictionFunctionality.test_convert_checkpoint_to_tf_model_raise_exception
test_convert_checkpoint_to_tf_model_raise_exception
Test if a checkpoint is not an instance of TensflowCheckpoint should fail with exception ValueError.
[ "Test", "if", "a", "checkpoint", "is", "not", "an", "instance", "of", "TensflowCheckpoint", "should", "fail", "with", "exception", "ValueError." ]
def test_convert_checkpoint_to_tf_model_raise_exception(self, ray_checkpoint_from_dict) -> None: with pytest.raises(ValueError) as ve: prediction_tensorflow.register._get_tensorflow_model_from(ray_checkpoint_from_dict) assert ve.match(regexp='.* arg checkpoint should be a ray.train.tensorflow.Tensorflow...
['def', 'test_convert_checkpoint_to_tf_model_raise_exception(self,', 'ray_checkpoint_from_dict)', '->', 'None:', 'with', 'pytest.raises(ValueError)', 'as', 've:', 'prediction_tensorflow.register._get_tensorflow_model_from(ray_checkpoint_from_dict)', 'assert', "ve.match(regexp='.*", 'arg', 'checkpoint', 'should', 'be', ...
863,100
weimin17/Object-Detection_HelmetDetection
prep.py
words
words
Splits a line of text into tokens.
[ "Splits", "a", "line", "of", "text", "into", "tokens." ]
def words(line): return line.strip().split()
['def', 'words(line):', 'return', 'line.strip().split()']
760,023
sek788432/Waymo-2D-Object-Detection
prediction.py
split_and_pad
split_and_pad
Split and pad for interence.
[ "Split", "and", "pad", "for", "interence." ]
def split_and_pad(strategy, batch_size, x): per_replica_size = batch_size // strategy.num_replicas_in_sync def slice_fn(x, i): begin = min(x.shape[0], i * per_replica_size) end = min(x.shape[0], (i + 1) * per_replica_size) indices = tf.range(begin, end, dtype=tf.int32) return tf...
['def', 'split_and_pad(strategy,', 'batch_size,', 'x):', 'per_replica_size', '=', 'batch_size', '//', 'strategy.num_replicas_in_sync', 'def', 'slice_fn(x,', 'i):', 'begin', '=', 'min(x.shape[0],', 'i', '*', 'per_replica_size)', 'end', '=', 'min(x.shape[0],', '(i', '+', '1)', '*', 'per_replica_size)', 'indices', '=', 't...
972,786
devashish-patel/webcam-motion-detector
datetime.py
tzinfo.tzname
tzname
datetime -> string name of time zone.
[ "datetime", "->", "string", "name", "of", "time", "zone." ]
def tzname(self, dt): raise NotImplementedError('tzinfo subclass must override tzname()')
['def', 'tzname(self,', 'dt):', 'raise', "NotImplementedError('tzinfo", 'subclass', 'must', 'override', "tzname()')"]
977,740
weimin17/Object-Detection_HelmetDetection
eval.py
EnsembleLM.evaluate
evaluate
Evaluate the current ensemble.
[ "Evaluate", "the", "current", "ensemble." ]
def evaluate(self): ensembled_probs = sum(self.all_probs) / len(self.all_probs) scorings = [] for (i, sentence) in enumerate(self.sentences): correctness = self.labels[i] word_probs = ensembled_probs[i, :len(sentence)] joint_prob = np.prod(word_probs, dtype=np.float64) scorin...
['def', 'evaluate(self):', 'ensembled_probs', '=', 'sum(self.all_probs)', '/', 'len(self.all_probs)', 'scorings', '=', '[]', 'for', '(i,', 'sentence)', 'in', 'enumerate(self.sentences):', 'correctness', '=', 'self.labels[i]', 'word_probs', '=', 'ensembled_probs[i,', ':len(sentence)]', 'joint_prob', '=', 'np.prod(word_p...
763,585
intel/neural-compressor
nas.py
NASBase.search_algorithm
search_algorithm
Setter of the search algorithm.
[ "Setter", "of", "the", "search", "algorithm." ]
def search_algorithm(self, search_algorithm): self._search_algorithm = search_algorithm
['def', 'search_algorithm(self,', 'search_algorithm):', 'self._search_algorithm', '=', 'search_algorithm']
738,608
zoltanbonus/ai50
logic.py
Sentence.evaluate
evaluate
Evaluates the logical sentence.
[ "Evaluates", "the", "logical", "sentence." ]
def evaluate(self, model): raise Exception('nothing to evaluate')
['def', 'evaluate(self,', 'model):', 'raise', "Exception('nothing", 'to', "evaluate')"]
85,456
tensorflow/agents
common.py
entropy
entropy
Computes total entropy of distribution.
[ "Computes", "total", "entropy", "of", "distribution." ]
def entropy(distributions, action_spec, outer_rank=None): if outer_rank is None: nested_modes = tf.nest.map_structure(lambda d: d.mode(), distributions) outer_rank = nest_utils.get_outer_rank(nested_modes, action_spec) def _compute_entropy(single_distribution): try: entropie...
['def', 'entropy(distributions,', 'action_spec,', 'outer_rank=None):', 'if', 'outer_rank', 'is', 'None:', 'nested_modes', '=', 'tf.nest.map_structure(lambda', 'd:', 'd.mode(),', 'distributions)', 'outer_rank', '=', 'nest_utils.get_outer_rank(nested_modes,', 'action_spec)', 'def', '_compute_entropy(single_distribution):...
23,059
apeterswu/RL4NMT
common_attention.py
scatter_blocks_2d
scatter_blocks_2d
scatters blocks from x into shape with indices.
[ "scatters", "blocks", "from", "x", "into", "shape", "with", "indices." ]
def scatter_blocks_2d(x, indices, shape): x_shape = tf.shape(x) x_t = tf.transpose(tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3]) x_t_shape = tf.shape(x_t) indices = tf.reshape(indices, [-1, 1]) scattered_x = tf.scatter_nd(indices, x_t, x_t_shape) scattered_x = tf.transp...
['def', 'scatter_blocks_2d(x,', 'indices,', 'shape):', 'x_shape', '=', 'tf.shape(x)', 'x_t', '=', 'tf.transpose(tf.reshape(x,', '[x_shape[0],', 'x_shape[1],', '-1,', 'x_shape[-1]]),', '[2,', '0,', '1,', '3])', 'x_t_shape', '=', 'tf.shape(x_t)', 'indices', '=', 'tf.reshape(indices,', '[-1,', '1])', 'scattered_x', '=', '...
331,465
softwarearchitect817/Efficient-Geometry-aware-3D
util.py
get_obj_from_module
get_obj_from_module
Traverses the object name and returns the last (rightmost) python object.
[ "Traverses", "the", "object", "name", "and", "returns", "the", "last", "(rightmost)", "python", "object." ]
def get_obj_from_module(module: types.ModuleType, obj_name: str) -> Any: if obj_name == '': return module obj = module for part in obj_name.split('.'): obj = getattr(obj, part) return obj
['def', 'get_obj_from_module(module:', 'types.ModuleType,', 'obj_name:', 'str)', '->', 'Any:', 'if', 'obj_name', '==', "'':", 'return', 'module', 'obj', '=', 'module', 'for', 'part', 'in', "obj_name.split('.'):", 'obj', '=', 'getattr(obj,', 'part)', 'return', 'obj']
548,610
microsoft/maro
containers.py
delete_container
delete_container
Delete a container, aka 'docker rm'.
[ "Delete", "a", "container,", "aka", "'docker", "rm'." ]
def delete_container(container_name: str): try: DockerController.remove_container(container_name=container_name) return {} except CommandExecutionError: abort(400)
['def', 'delete_container(container_name:', 'str):', 'try:', 'DockerController.remove_container(container_name=container_name)', 'return', '{}', 'except', 'CommandExecutionError:', 'abort(400)']
628,244
zhyhan/TransPar
keypoint_dataset.py
KeypointDataset.group_accuracy
group_accuracy
Group the accuracy of K keypoints into different kinds.
[ "Group", "the", "accuracy", "of", "K", "keypoints", "into", "different", "kinds." ]
def group_accuracy(self, accuracies): grouped_accuracies = dict() for (name, keypoints) in self.keypoints_group.items(): grouped_accuracies[name] = sum([accuracies[idx] for idx in keypoints]) / len(keypoints) return grouped_accuracies
['def', 'group_accuracy(self,', 'accuracies):', 'grouped_accuracies', '=', 'dict()', 'for', '(name,', 'keypoints)', 'in', 'self.keypoints_group.items():', 'grouped_accuracies[name]', '=', 'sum([accuracies[idx]', 'for', 'idx', 'in', 'keypoints])', '/', 'len(keypoints)', 'return', 'grouped_accuracies']
356,055
suarez12138/AI-Reversi_IMP_TextDichotomy
cm.py
ScalarMappable.get_array
get_array
Return the data array.
[ "Return", "the", "data", "array." ]
def get_array(self): return self._A
['def', 'get_array(self):', 'return', 'self._A']
96,335
sktime/sktime
test_teaser.py
test_teaser_full_length
test_teaser_full_length
Test of TEASER on the full data with the default estimator.
[ "Test", "of", "TEASER", "on", "the", "full", "data", "with", "the", "default", "estimator." ]
def test_teaser_full_length(): (X_train, y_train, X_test, y_test, indices) = load_unit_data() teaser = TEASER(random_state=0, classification_points=[6, 10, 16, 24]) teaser.fit(X_train, y_train) (hm, acc, earl) = teaser.score(X_test, y_test) testing.assert_allclose(acc, 0.818, rtol=0.01) testing....
['def', 'test_teaser_full_length():', '(X_train,', 'y_train,', 'X_test,', 'y_test,', 'indices)', '=', 'load_unit_data()', 'teaser', '=', 'TEASER(random_state=0,', 'classification_points=[6,', '10,', '16,', '24])', 'teaser.fit(X_train,', 'y_train)', '(hm,', 'acc,', 'earl)', '=', 'teaser.score(X_test,', 'y_test)', 'testi...
885,982
sktime/sktime
test_all_forecasters.py
TestAllForecasters.test_y_multivariate_raises_error
test_y_multivariate_raises_error
Test that wrong y scitype raises error (uni/multivariate not supported).
[ "Test", "that", "wrong", "y", "scitype", "raises", "error", "(uni/multivariate", "not", "supported)." ]
def test_y_multivariate_raises_error(self, estimator_instance): if estimator_instance.get_tag('scitype:y') == 'multivariate': y = _make_series(n_columns=1) with pytest.raises(ValueError, match='two or more variables'): estimator_instance.fit(y, fh=FH0) if estimator_instance.get_tag('...
['def', 'test_y_multivariate_raises_error(self,', 'estimator_instance):', 'if', "estimator_instance.get_tag('scitype:y')", '==', "'multivariate':", 'y', '=', '_make_series(n_columns=1)', 'with', 'pytest.raises(ValueError,', "match='two", 'or', 'more', "variables'):", 'estimator_instance.fit(y,', 'fh=FH0)', 'if', "estim...
877,279
IceClear/MW-GAN
degradations.py
random_add_jpg_compression
random_add_jpg_compression
Randomly add JPG compression artifacts.
[ "Randomly", "add", "JPG", "compression", "artifacts." ]
def random_add_jpg_compression(img, quality_range=(90, 100)): quality = np.random.uniform(quality_range[0], quality_range[1]) return add_jpg_compression(img, quality)
['def', 'random_add_jpg_compression(img,', 'quality_range=(90,', '100)):', 'quality', '=', 'np.random.uniform(quality_range[0],', 'quality_range[1])', 'return', 'add_jpg_compression(img,', 'quality)']
651,471
Farama-Foundation/Minari
minari_dataset.py
MinariDataset.set_seed
set_seed
Set seed for random episode sampling generator.
[ "Set", "seed", "for", "random", "episode", "sampling", "generator." ]
def set_seed(self, seed: int): self._generator = np.random.default_rng(seed)
['def', 'set_seed(self,', 'seed:', 'int):', 'self._generator', '=', 'np.random.default_rng(seed)']
670,497
sek788432/Waymo-2D-Object-Detection
hourglass_network.py
HourglassNetwork.num_feature_outputs
num_feature_outputs
Ther number of feature outputs returned by the feature extractor.
[ "Ther", "number", "of", "feature", "outputs", "returned", "by", "the", "feature", "extractor." ]
def num_feature_outputs(self): return self.num_hourglasses
['def', 'num_feature_outputs(self):', 'return', 'self.num_hourglasses']
973,315
robinhenry/gym-anm
test_simulator_transitions.py
TestSimulatorTransition.test_reset
test_reset
Test reset() (and transition()) methods.
[ "Test", "reset()", "(and", "transition())", "methods." ]
def test_reset(self): baseMVA = 10 network = {'baseMVA': baseMVA, 'bus': np.array([[0, 0, 50, 1.0, 1.0], [1, 1, 50, 1.1, 0.9], [2, 1, 50, 1.1, 0.9]]), 'branch': np.array([[0, 1, 0.01, 0.1, 0.0, 30, 1, 0], [1, 2, 0.02, 0.3, 0.2, 30, 1, 0], [2, 0, 0.05, 0.2, 0.1, 30, 1, 0]]), 'device': np.array([[0, 0, 0, None, 2...
['def', 'test_reset(self):', 'baseMVA', '=', '10', 'network', '=', "{'baseMVA':", 'baseMVA,', "'bus':", 'np.array([[0,', '0,', '50,', '1.0,', '1.0],', '[1,', '1,', '50,', '1.1,', '0.9],', '[2,', '1,', '50,', '1.1,', '0.9]]),', "'branch':", 'np.array([[0,', '1,', '0.01,', '0.1,', '0.0,', '30,', '1,', '0],', '[1,', '2,',...
572,850
TuSimple/centerformer
finetune_utils.py
FrozenBatchNorm2d.convert_frozen_batchnorm
convert_frozen_batchnorm
Convert BatchNorm/SyncBatchNorm in module into FrozenBatchNorm.
[ "Convert", "BatchNorm/SyncBatchNorm", "in", "module", "into", "FrozenBatchNorm." ]
def convert_frozen_batchnorm(cls, module): bn_module = nn.modules.batchnorm bn_module = (bn_module.BatchNorm2d, bn_module.SyncBatchNorm) res = module if isinstance(module, bn_module): res = cls(module.num_features) if module.affine: res.weight.data = module.weight.data.clone(...
['def', 'convert_frozen_batchnorm(cls,', 'module):', 'bn_module', '=', 'nn.modules.batchnorm', 'bn_module', '=', '(bn_module.BatchNorm2d,', 'bn_module.SyncBatchNorm)', 'res', '=', 'module', 'if', 'isinstance(module,', 'bn_module):', 'res', '=', 'cls(module.num_features)', 'if', 'module.affine:', 'res.weight.data', '=',...
457,496
PaddlePaddle/Paddle3D
mvx_two_stage.py
MVXTwoStageDetector.with_pts_roi_head
with_pts_roi_head
bool: Whether the detector has a roi head in pts branch.
[ "bool:", "Whether", "the", "detector", "has", "a", "roi", "head", "in", "pts", "branch." ]
def with_pts_roi_head(self): return hasattr(self, 'pts_roi_head') and self.pts_roi_head is not None
['def', 'with_pts_roi_head(self):', 'return', 'hasattr(self,', "'pts_roi_head')", 'and', 'self.pts_roi_head', 'is', 'not', 'None']
777,443
hsouri/BayesianTransferLearning
pretrain_dataloader.py
prepare_n_crop_transform
prepare_n_crop_transform
Turns a single crop transformation to an N crops transformation.
[ "Turns", "a", "single", "crop", "transformation", "to", "an", "N", "crops", "transformation." ]
def prepare_n_crop_transform(transforms: List[Callable], num_crops_per_aug: List[int]) -> NCropAugmentation: assert len(transforms) == len(num_crops_per_aug) T = [] for (transform, num_crops) in zip(transforms, num_crops_per_aug): T.append(NCropAugmentation(transform, num_crops)) return FullTran...
['def', 'prepare_n_crop_transform(transforms:', 'List[Callable],', 'num_crops_per_aug:', 'List[int])', '->', 'NCropAugmentation:', 'assert', 'len(transforms)', '==', 'len(num_crops_per_aug)', 'T', '=', '[]', 'for', '(transform,', 'num_crops)', 'in', 'zip(transforms,', 'num_crops_per_aug):', 'T.append(NCropAugmentation(...
423,047
pytorch/rl
functional.py
vec_td1_advantage_estimate
vec_td1_advantage_estimate
Vectorized TD(1) advantage estimate.
[ "Vectorized", "TD(1)", "advantage", "estimate." ]
def vec_td1_advantage_estimate(gamma, state_value, next_state_value, reward, done: torch.Tensor, terminated: torch.Tensor | None=None, rolling_gamma: bool=None, time_dim: int=-2): if terminated is None: terminated = done if not next_state_value.shape == state_value.shape == reward.shape == done.shape ==...
['def', 'vec_td1_advantage_estimate(gamma,', 'state_value,', 'next_state_value,', 'reward,', 'done:', 'torch.Tensor,', 'terminated:', 'torch.Tensor', '|', 'None=None,', 'rolling_gamma:', 'bool=None,', 'time_dim:', 'int=-2):', 'if', 'terminated', 'is', 'None:', 'terminated', '=', 'done', 'if', 'not', 'next_state_value.s...
859,399
arshpreetsingh/quantopian-machinelearning
test_bundlerextension.py
TestBundlerExtensionCLI.tearDown
tearDown
Remove the test config environment.
[ "Remove", "the", "test", "config", "environment." ]
def tearDown(self): shutil.rmtree(self.test_dir, ignore_errors=True) self.patch_env.stop() self.patch_system_path.stop()
['def', 'tearDown(self):', 'shutil.rmtree(self.test_dir,', 'ignore_errors=True)', 'self.patch_env.stop()', 'self.patch_system_path.stop()']
888,502
simonmeister/pysc2-rl-agents
util.py
safe_log
safe_log
Computes a safe logarithm which returns 0 if x is zero.
[ "Computes", "a", "safe", "logarithm", "which", "returns", "0", "if", "x", "is", "zero." ]
def safe_log(x): return tf.where(tf.equal(x, 0), tf.zeros_like(x), tf.log(tf.maximum(1e-12, x)))
['def', 'safe_log(x):', 'return', 'tf.where(tf.equal(x,', '0),', 'tf.zeros_like(x),', 'tf.log(tf.maximum(1e-12,', 'x)))']
809,429
cheng052/BRNet
point_fusion.py
PointFusion.sample_single
sample_single
Sample features from single level image feature map.
[ "Sample", "features", "from", "single", "level", "image", "feature", "map." ]
def sample_single(self, img_feats, pts, img_meta): pcd_scale_factor = img_meta['pcd_scale_factor'] if 'pcd_scale_factor' in img_meta.keys() else 1 pcd_trans_factor = pts.new_tensor(img_meta['pcd_trans']) if 'pcd_trans' in img_meta.keys() else 0 pcd_rotate_mat = pts.new_tensor(img_meta['pcd_rotation']) if 'p...
['def', 'sample_single(self,', 'img_feats,', 'pts,', 'img_meta):', 'pcd_scale_factor', '=', "img_meta['pcd_scale_factor']", 'if', "'pcd_scale_factor'", 'in', 'img_meta.keys()', 'else', '1', 'pcd_trans_factor', '=', "pts.new_tensor(img_meta['pcd_trans'])", 'if', "'pcd_trans'", 'in', 'img_meta.keys()', 'else', '0', 'pcd_...
409,915
YannDubs/Invariant-Self-Supervised-Learning
img.py
ISSLImgDataset.standard_augmentations
standard_augmentations
Return the standard augmentations for the dataset.
[ "Return", "the", "standard", "augmentations", "for", "the", "dataset." ]
def standard_augmentations(self) -> list[str]: ...
['def', 'standard_augmentations(self)', '->', 'list[str]:', '...']
245,988
anuragranj/coma
utils.py
TextDataset.normalize
normalize
Normalize data to unit length.
[ "Normalize", "data", "to", "unit", "length." ]
def normalize(self, norm='l1'): data = self.data.astype(np.float64) self.data = sklearn.preprocessing.normalize(data, axis=1, norm=norm)
['def', 'normalize(self,', "norm='l1'):", 'data', '=', 'self.data.astype(np.float64)', 'self.data', '=', 'sklearn.preprocessing.normalize(data,', 'axis=1,', 'norm=norm)']
467,135
f-dangel/cockpit
mean_gsnr.py
MeanGSNR.compute
compute
Track the mean GSNR.
[ "Track", "the", "mean", "GSNR." ]
def compute(self, global_step, params, batch_loss): if self.is_active(global_step): mean_gsnr = self._compute(global_step, params, batch_loss).item() if self._verbose: print(f'[Step {global_step}] MeanGSNR: {mean_gsnr:.4f}') self.output[global_step]['mean_gsnr'] = mean_gsnr ...
['def', 'compute(self,', 'global_step,', 'params,', 'batch_loss):', 'if', 'self.is_active(global_step):', 'mean_gsnr', '=', 'self._compute(global_step,', 'params,', 'batch_loss).item()', 'if', 'self._verbose:', "print(f'[Step", '{global_step}]', 'MeanGSNR:', "{mean_gsnr:.4f}')", "self.output[global_step]['mean_gsnr']",...
493,078
palVikram/Machine-Learning-using-Python
graph.py
Apply.run_params
run_params
Returns the params for the node, or NoParams if no params is set.
[ "Returns", "the", "params", "for", "the", "node,", "or", "NoParams", "if", "no", "params", "is", "set." ]
def run_params(self): try: return self.op.get_params(self) except theano.gof.utils.MethodNotDefined: return NoParams
['def', 'run_params(self):', 'try:', 'return', 'self.op.get_params(self)', 'except', 'theano.gof.utils.MethodNotDefined:', 'return', 'NoParams']
621,345
tensorly/quantum
serializable_gate_set_test.py
SerializableGateSetTest.test_deserialize_empty_moment
test_deserialize_empty_moment
Ensure deserialize empty moment works.
[ "Ensure", "deserialize", "empty", "moment", "works." ]
def test_deserialize_empty_moment(self): circuit = cirq.Circuit([cirq.Moment()]) proto = program_pb2.Program(language=program_pb2.Language(arg_function_language='', gate_set='my_gate_set'), circuit=program_pb2.Circuit(scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT, moments=[program_pb2.Moment()])) ...
['def', 'test_deserialize_empty_moment(self):', 'circuit', '=', 'cirq.Circuit([cirq.Moment()])', 'proto', '=', "program_pb2.Program(language=program_pb2.Language(arg_function_language='',", "gate_set='my_gate_set'),", 'circuit=program_pb2.Circuit(scheduling_strategy=program_pb2.Circuit.MOMENT_BY_MOMENT,', 'moments=[pro...
834,952
clips/pattern
__init__.py
geocode
geocode
Returns a (latitude, longitude, language code, region)-tuple for the given city (mostly capitals).
[ "Returns", "a", "(latitude,", "longitude,", "language", "code,", "region)-tuple", "for", "the", "given", "city", "(mostly", "capitals)." ]
def geocode(location): if location in GEOCODE: return GEOCODE[location] for (k, v) in GEOCODE.items(): if location.lower() == k.lower(): return v
['def', 'geocode(location):', 'if', 'location', 'in', 'GEOCODE:', 'return', 'GEOCODE[location]', 'for', '(k,', 'v)', 'in', 'GEOCODE.items():', 'if', 'location.lower()', '==', 'k.lower():', 'return', 'v']
765,062
zhang614/MicroGrid
test_slsqp.py
TestSLSQP.jac
jac
This is the derivative of fun, returning a numpy array representing df/dx and df/dy.
[ "This", "is", "the", "derivative", "of", "fun,", "returning", "a", "numpy", "array", "representing", "df/dx", "and", "df/dy." ]
def jac(self, d, sign=1.0): x = d[0] y = d[1] dfdx = sign * (-2 * x + 2 * y + 2) dfdy = sign * (2 * x - 4 * y) return np.array([dfdx, dfdy], float)
['def', 'jac(self,', 'd,', 'sign=1.0):', 'x', '=', 'd[0]', 'y', '=', 'd[1]', 'dfdx', '=', 'sign', '*', '(-2', '*', 'x', '+', '2', '*', 'y', '+', '2)', 'dfdy', '=', 'sign', '*', '(2', '*', 'x', '-', '4', '*', 'y)', 'return', 'np.array([dfdx,', 'dfdy],', 'float)']
669,476
scikit-learn/scikit-learn
test_quantile.py
test_asymmetric_error
test_asymmetric_error
Test quantile regression for asymmetric distributed targets.
[ "Test", "quantile", "regression", "for", "asymmetric", "distributed", "targets." ]
def test_asymmetric_error(quantile, default_solver): n_samples = 1000 rng = np.random.RandomState(42) X = np.concatenate((np.abs(rng.randn(n_samples)[:, None]), -rng.randint(2, size=(n_samples, 1))), axis=1) intercept = 1.23 coef = np.array([0.5, -2]) assert np.min(X @ coef + intercept) > 0 ...
['def', 'test_asymmetric_error(quantile,', 'default_solver):', 'n_samples', '=', '1000', 'rng', '=', 'np.random.RandomState(42)', 'X', '=', 'np.concatenate((np.abs(rng.randn(n_samples)[:,', 'None]),', '-rng.randint(2,', 'size=(n_samples,', '1))),', 'axis=1)', 'intercept', '=', '1.23', 'coef', '=', 'np.array([0.5,', '-2...
853,565
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
image_transformer.py
imagetransformer_cifar_tpu_range
imagetransformer_cifar_tpu_range
Range of hyperparameters for vizier.
[ "Range", "of", "hyperparameters", "for", "vizier." ]
def imagetransformer_cifar_tpu_range(rhp): rhp.set_float('learning_rate', 0.01, 1.0, scale=rhp.LOG_SCALE) rhp.set_discrete('num_decoder_layers', [8, 10, 12, 14, 16]) rhp.set_discrete('hidden_size', [256, 512, 1024]) rhp.set_discrete('block_length', [128, 256, 512]) rhp.set_categorical('dec_attention...
['def', 'imagetransformer_cifar_tpu_range(rhp):', "rhp.set_float('learning_rate',", '0.01,', '1.0,', 'scale=rhp.LOG_SCALE)', "rhp.set_discrete('num_decoder_layers',", '[8,', '10,', '12,', '14,', '16])', "rhp.set_discrete('hidden_size',", '[256,', '512,', '1024])', "rhp.set_discrete('block_length',", '[128,', '256,', '5...
965,622
matsu0228/nlp-jp
test_traitlets.py
TestDirectionalLink.test_unlink
test_unlink
Verify two linked traitlets can be unlinked.
[ "Verify", "two", "linked", "traitlets", "can", "be", "unlinked." ]
def test_unlink(self): class A(HasTraits): value = Int() a = A(value=9) b = A(value=8) c = directional_link((a, 'value'), (b, 'value')) a.value = 4 c.unlink() a.value = 5 self.assertNotEqual(a.value, b.value)
['def', 'test_unlink(self):', 'class', 'A(HasTraits):', 'value', '=', 'Int()', 'a', '=', 'A(value=9)', 'b', '=', 'A(value=8)', 'c', '=', 'directional_link((a,', "'value'),", '(b,', "'value'))", 'a.value', '=', '4', 'c.unlink()', 'a.value', '=', '5', 'self.assertNotEqual(a.value,', 'b.value)']
807,634
enuguru/artificial_intelligence_and_machine_learning
execfile.py
make_code_from_py
make_code_from_py
Get source from `filename` and make a code object of it.
[ "Get", "source", "from", "`filename`", "and", "make", "a", "code", "object", "of", "it." ]
def make_code_from_py(filename): try: source = get_python_source(filename) except (IOError, NoSource): raise NoSource("No file to run: '%s'" % filename) code = compile_unicode(source, filename, 'exec') return code
['def', 'make_code_from_py(filename):', 'try:', 'source', '=', 'get_python_source(filename)', 'except', '(IOError,', 'NoSource):', 'raise', 'NoSource("No', 'file', 'to', 'run:', '\'%s\'"', '%', 'filename)', 'code', '=', 'compile_unicode(source,', 'filename,', "'exec')", 'return', 'code']
157,375
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_102a.py
bb_pad_collate
bb_pad_collate
Function that collect samples and adds padding.
[ "Function", "that", "collect", "samples", "and", "adds", "padding." ]
def bb_pad_collate(samples: BatchSamples, pad_idx: int=0, pad_first: bool=True) -> Tuple[FloatTensor, Tuple[LongTensor, LongTensor]]: max_len = max([len(s[1].data[1]) for s in samples]) bboxes = torch.zeros(len(samples), max_len, 4) labels = torch.zeros(len(samples), max_len).long() + pad_idx imgs = [] ...
['def', 'bb_pad_collate(samples:', 'BatchSamples,', 'pad_idx:', 'int=0,', 'pad_first:', 'bool=True)', '->', 'Tuple[FloatTensor,', 'Tuple[LongTensor,', 'LongTensor]]:', 'max_len', '=', 'max([len(s[1].data[1])', 'for', 's', 'in', 'samples])', 'bboxes', '=', 'torch.zeros(len(samples),', 'max_len,', '4)', 'labels', '=', 't...
81,861
scotthuang1989/object_detection_with_tensorflow
controller.py
Controller.convert_to_batched_episodes
convert_to_batched_episodes
Convert batch-major list of episodes to time-major batch of episodes.
[ "Convert", "batch-major", "list", "of", "episodes", "to", "time-major", "batch", "of", "episodes." ]
def convert_to_batched_episodes(self, episodes, max_length=None): lengths = [len(ep[-2]) for ep in episodes] max_length = max_length or max(lengths) new_episodes = [] for (ep, length) in zip(episodes, lengths): (initial, observations, actions, rewards, terminated) = ep observations = [np...
['def', 'convert_to_batched_episodes(self,', 'episodes,', 'max_length=None):', 'lengths', '=', '[len(ep[-2])', 'for', 'ep', 'in', 'episodes]', 'max_length', '=', 'max_length', 'or', 'max(lengths)', 'new_episodes', '=', '[]', 'for', '(ep,', 'length)', 'in', 'zip(episodes,', 'lengths):', '(initial,', 'observations,', 'ac...
739,464
ryu-ed/SpaceInvaders_Ros
brain_namedtuple_enum.py
infer_enum_class
infer_enum_class
Specific inference for enums.
[ "Specific", "inference", "for", "enums." ]
def infer_enum_class(node): for basename in node.basenames: if basename not in ENUM_BASE_NAMES: continue if node.root().name == 'enum': break for (local, values) in node.locals.items(): if any((not isinstance(value, nodes.AssignName) for value in values)):...
['def', 'infer_enum_class(node):', 'for', 'basename', 'in', 'node.basenames:', 'if', 'basename', 'not', 'in', 'ENUM_BASE_NAMES:', 'continue', 'if', 'node.root().name', '==', "'enum':", 'break', 'for', '(local,', 'values)', 'in', 'node.locals.items():', 'if', 'any((not', 'isinstance(value,', 'nodes.AssignName)', 'for', ...
394,562
caiiiac/Machine-Learning-with-Python
timedeltas.py
TimedeltaIndex.seconds
seconds
Number of seconds (>= 0 and less than 1 day) for each element.
[ "Number", "of", "seconds", "(>=", "0", "and", "less", "than", "1", "day)", "for", "each", "element." ]
def seconds(self): return self._get_field('seconds')
['def', 'seconds(self):', 'return', "self._get_field('seconds')"]
718,195
ADLab3Ds/TiG-BEV
h3dnet.py
H3DNet.extract_feats
extract_feats
Extract features of multiple samples.
[ "Extract", "features", "of", "multiple", "samples." ]
def extract_feats(self, points, img_metas): return [self.extract_feat(pts, img_meta) for (pts, img_meta) in zip(points, img_metas)]
['def', 'extract_feats(self,', 'points,', 'img_metas):', 'return', '[self.extract_feat(pts,', 'img_meta)', 'for', '(pts,', 'img_meta)', 'in', 'zip(points,', 'img_metas)]']
917,060
enuguru/artificial_intelligence_and_machine_learning
columns.py
TranslatingColumnReader.raw_column
raw_column
Returns the underlying column reader.
[ "Returns", "the", "underlying", "column", "reader." ]
def raw_column(self): return self._reader
['def', 'raw_column(self):', 'return', 'self._reader']
161,945
kubeflow/pipelines
utility.py
ExecutorResponse.has_error
has_error
Returns true if execution error code was not 0.
[ "Returns", "true", "if", "execution", "error", "code", "was", "not", "0." ]
def has_error(self) -> bool: return self._returncode != 0
['def', 'has_error(self)', '->', 'bool:', 'return', 'self._returncode', '!=', '0']
779,869
rudranil723/mini-main
test_util.py
SetAllPackedFields
SetAllPackedFields
Sets every field in the message to a unique value.
[ "Sets", "every", "field", "in", "the", "message", "to", "a", "unique", "value." ]
def SetAllPackedFields(message): message.packed_int32.extend([601, 701]) message.packed_int64.extend([602, 702]) message.packed_uint32.extend([603, 703]) message.packed_uint64.extend([604, 704]) message.packed_sint32.extend([605, 705]) message.packed_sint64.extend([606, 706]) message.packed_...
['def', 'SetAllPackedFields(message):', 'message.packed_int32.extend([601,', '701])', 'message.packed_int64.extend([602,', '702])', 'message.packed_uint32.extend([603,', '703])', 'message.packed_uint64.extend([604,', '704])', 'message.packed_sint32.extend([605,', '705])', 'message.packed_sint64.extend([606,', '706])', ...
318,441
YuYaoYang2333/SyntaLinker
misc.py
relative_matmul
relative_matmul
Helper function for relative positions attention.
[ "Helper", "function", "for", "relative", "positions", "attention." ]
def relative_matmul(x, z, transpose): batch_size = x.shape[0] heads = x.shape[1] length = x.shape[2] x_t = x.permute(2, 0, 1, 3) x_t_r = x_t.reshape(length, heads * batch_size, -1) if transpose: z_t = z.transpose(1, 2) x_tz_matmul = torch.matmul(x_t_r, z_t) else: x_tz...
['def', 'relative_matmul(x,', 'z,', 'transpose):', 'batch_size', '=', 'x.shape[0]', 'heads', '=', 'x.shape[1]', 'length', '=', 'x.shape[2]', 'x_t', '=', 'x.permute(2,', '0,', '1,', '3)', 'x_t_r', '=', 'x_t.reshape(length,', 'heads', '*', 'batch_size,', '-1)', 'if', 'transpose:', 'z_t', '=', 'z.transpose(1,', '2)', 'x_t...
905,977
triaquae/triaquae
query.py
Query.unref_alias
unref_alias
Decreases the reference count for this alias.
[ "Decreases", "the", "reference", "count", "for", "this", "alias." ]
def unref_alias(self, alias, amount=1): self.alias_refcount[alias] -= amount
['def', 'unref_alias(self,', 'alias,', 'amount=1):', 'self.alias_refcount[alias]', '-=', 'amount']
423,580
keyonvafa/career-code
retritask.py
RetriTask.build_dataloader
build_dataloader
called by `get_batch_iterator` in fairseqmmtask.
[ "called", "by", "`get_batch_iterator`", "in", "fairseqmmtask." ]
def build_dataloader(self): self.config.dataset.split = 'train' meta_processor = ShardedHow2MetaProcessor(self.config.dataset) video_processor = ShardedVideoProcessor(self.config.dataset) text_processor = ShardedTextProcessor(self.config.dataset) aligner = VariedLenAligner(self.config.dataset) a...
['def', 'build_dataloader(self):', 'self.config.dataset.split', '=', "'train'", 'meta_processor', '=', 'ShardedHow2MetaProcessor(self.config.dataset)', 'video_processor', '=', 'ShardedVideoProcessor(self.config.dataset)', 'text_processor', '=', 'ShardedTextProcessor(self.config.dataset)', 'aligner', '=', 'VariedLenAlig...
454,909
flow-project/flow
load.py
load_subnetwork
load_subnetwork
Load subnetwork into a dictionary and returns it.
[ "Load", "subnetwork", "into", "a", "dictionary", "and", "returns", "it." ]
def load_subnetwork(subnetwork, scenario): objs = list(subnetwork.classify_objects(scenario.id)) sections = model.find_all_by_type(objs, 'GKSection') nodes = model.find_all_by_type(objs, 'GKNode') turnings = model.find_all_by_type(objs, 'GKTurning') cen_connections = model.find_all_by_type(objs, 'GK...
['def', 'load_subnetwork(subnetwork,', 'scenario):', 'objs', '=', 'list(subnetwork.classify_objects(scenario.id))', 'sections', '=', 'model.find_all_by_type(objs,', "'GKSection')", 'nodes', '=', 'model.find_all_by_type(objs,', "'GKNode')", 'turnings', '=', 'model.find_all_by_type(objs,', "'GKTurning')", 'cen_connection...
212,364