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
openvinotoolkit/training_extensions
task.py
ClassificationOpenVINOTask.evaluate
evaluate
Evaluate function of ClassificationOpenVINOTask.
[ "Evaluate", "function", "of", "ClassificationOpenVINOTask." ]
def evaluate(self, output_resultset: ResultSetEntity, evaluation_metric: Optional[str]=None): if evaluation_metric is not None: logger.warning(f'Requested to use {evaluation_metric} metric,but parameter is ignored. Use accuracy instead.') output_resultset.performance = MetricsHelper.compute_accuracy(out...
['def', 'evaluate(self,', 'output_resultset:', 'ResultSetEntity,', 'evaluation_metric:', 'Optional[str]=None):', 'if', 'evaluation_metric', 'is', 'not', 'None:', "logger.warning(f'Requested", 'to', 'use', '{evaluation_metric}', 'metric,but', 'parameter', 'is', 'ignored.', 'Use', 'accuracy', "instead.')", 'output_result...
904,102
PaddlePaddle/Paddle3D
transform.py
limit_period
limit_period
Limit the value into a period for periodic function.
[ "Limit", "the", "value", "into", "a", "period", "for", "periodic", "function." ]
def limit_period(val, offset=0.5, period=np.pi): return val - np.floor(val / period + offset) * period
['def', 'limit_period(val,', 'offset=0.5,', 'period=np.pi):', 'return', 'val', '-', 'np.floor(val', '/', 'period', '+', 'offset)', '*', 'period']
778,010
tinyvision/DAMO-YOLO
tta_aug.py
im_detect_bbox
im_detect_bbox
Performs bbox detection on the original image.
[ "Performs", "bbox", "detection", "on", "the", "original", "image." ]
def im_detect_bbox(model, images, target_scale, target_max_size, device, config): transform = T.Compose([T.Resize(target_scale, target_max_size), T.ToTensor(), T.Normalize(mean=config.dataset.input_pixel_mean, std=config.dataset.input_pixel_std, to_bgr255=config.dataset.input_to_bgr255)]) images = [transform(im...
['def', 'im_detect_bbox(model,', 'images,', 'target_scale,', 'target_max_size,', 'device,', 'config):', 'transform', '=', 'T.Compose([T.Resize(target_scale,', 'target_max_size),', 'T.ToTensor(),', 'T.Normalize(mean=config.dataset.input_pixel_mean,', 'std=config.dataset.input_pixel_std,', 'to_bgr255=config.dataset.input...
496,983
matsu0228/nlp-jp
connection.py
MWSConnection.get_feed_submission_count
get_feed_submission_count
Returns a count of the feeds submitted in the previous 90 days.
[ "Returns", "a", "count", "of", "the", "feeds", "submitted", "in", "the", "previous", "90", "days." ]
def get_feed_submission_count(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'get_feed_submission_count(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,927
google-research/rigl
mask_updaters.py
MaskUpdater.generic_mask_update
generic_mask_update
Prunes+grows connections, all tensors same shape.
[ "Prunes+grows", "connections,", "all", "tensors", "same", "shape." ]
def generic_mask_update(self, mask, var, score_drop, score_grow, drop_fraction, reinit_when_same=False): n_total = tf.size(score_drop) n_ones = tf.cast(tf.reduce_sum(mask), dtype=tf.int32) n_prune = tf.cast(tf.cast(n_ones, dtype=tf.float32) * drop_fraction, tf.int32) n_keep = n_ones - n_prune (_, so...
['def', 'generic_mask_update(self,', 'mask,', 'var,', 'score_drop,', 'score_grow,', 'drop_fraction,', 'reinit_when_same=False):', 'n_total', '=', 'tf.size(score_drop)', 'n_ones', '=', 'tf.cast(tf.reduce_sum(mask),', 'dtype=tf.int32)', 'n_prune', '=', 'tf.cast(tf.cast(n_ones,', 'dtype=tf.float32)', '*', 'drop_fraction,'...
841,618
ChenhongyiYang/PPAL
detr_head.py
DETRHead.forward_train
forward_train
Forward function for training mode.
[ "Forward", "function", "for", "training", "mode." ]
def forward_train(self, x, img_metas, gt_bboxes, gt_labels=None, gt_bboxes_ignore=None, proposal_cfg=None, **kwargs): assert proposal_cfg is None, '"proposal_cfg" must be None' outs = self(x, img_metas) if gt_labels is None: loss_inputs = outs + (gt_bboxes, img_metas) else: loss_inputs =...
['def', 'forward_train(self,', 'x,', 'img_metas,', 'gt_bboxes,', 'gt_labels=None,', 'gt_bboxes_ignore=None,', 'proposal_cfg=None,', '**kwargs):', 'assert', 'proposal_cfg', 'is', 'None,', '\'"proposal_cfg"', 'must', 'be', "None'", 'outs', '=', 'self(x,', 'img_metas)', 'if', 'gt_labels', 'is', 'None:', 'loss_inputs', '='...
821,528
ramabhadraraju/NaturalLanguageProcessing
run_pretraining.py
gather_indexes
gather_indexes
Gathers the vectors at the specific positions over a minibatch.
[ "Gathers", "the", "vectors", "at", "the", "specific", "positions", "over", "a", "minibatch." ]
def gather_indexes(sequence_tensor, positions): sequence_shape = modeling.get_shape_list(sequence_tensor, expected_rank=3) batch_size = sequence_shape[0] seq_length = sequence_shape[1] width = sequence_shape[2] flat_offsets = tf.reshape(tf.range(0, batch_size, dtype=tf.int32) * seq_length, [-1, 1]) ...
['def', 'gather_indexes(sequence_tensor,', 'positions):', 'sequence_shape', '=', 'modeling.get_shape_list(sequence_tensor,', 'expected_rank=3)', 'batch_size', '=', 'sequence_shape[0]', 'seq_length', '=', 'sequence_shape[1]', 'width', '=', 'sequence_shape[2]', 'flat_offsets', '=', 'tf.reshape(tf.range(0,', 'batch_size,'...
798,683
tinyvision/DAMO-YOLO
zero_head.py
ZeroHead.get_target_single
get_target_single
Compute regression, classification targets for anchors in a single image.
[ "Compute", "regression,", "classification", "targets", "for", "anchors", "in", "a", "single", "image." ]
def get_target_single(self, center_priors, cls_scores, bbox_preds, gt_bboxes, gt_labels, unmap_outputs=True, gt_bboxes_ignore=None): num_valid_center = center_priors.shape[0] labels = center_priors.new_full((num_valid_center,), self.num_classes, dtype=torch.long) label_weights = center_priors.new_zeros(num_...
['def', 'get_target_single(self,', 'center_priors,', 'cls_scores,', 'bbox_preds,', 'gt_bboxes,', 'gt_labels,', 'unmap_outputs=True,', 'gt_bboxes_ignore=None):', 'num_valid_center', '=', 'center_priors.shape[0]', 'labels', '=', 'center_priors.new_full((num_valid_center,),', 'self.num_classes,', 'dtype=torch.long)', 'lab...
496,972
myothida/Supervised-Machine-Learning
tz.py
tzical.keys
keys
Retrieves the available time zones as a list.
[ "Retrieves", "the", "available", "time", "zones", "as", "a", "list." ]
def keys(self): return list(self._vtz.keys())
['def', 'keys(self):', 'return', 'list(self._vtz.keys())']
360,682
jimtin/Stock_Comparison
ctypeslib.py
prep_array
prep_array
Given a ctypes array type, construct and attach an __array_interface__ property to it if it does not yet have one.
[ "Given", "a", "ctypes", "array", "type,", "construct", "and", "attach", "an", "__array_interface__", "property", "to", "it", "if", "it", "does", "not", "yet", "have", "one." ]
def prep_array(array_type): try: array_type.__array_interface__ except AttributeError: pass else: return shape = [] ob = array_type while type(ob) is _ARRAY_TYPE: shape.append(ob._length_) ob = ob._type_ shape = tuple(shape) ai = ob().__array_inter...
['def', 'prep_array(array_type):', 'try:', 'array_type.__array_interface__', 'except', 'AttributeError:', 'pass', 'else:', 'return', 'shape', '=', '[]', 'ob', '=', 'array_type', 'while', 'type(ob)', 'is', '_ARRAY_TYPE:', 'shape.append(ob._length_)', 'ob', '=', 'ob._type_', 'shape', '=', 'tuple(shape)', 'ai', '=', 'ob()...
386,627
enuguru/artificial_intelligence_and_machine_learning
support.py
NullTranslations.dpgettext
dpgettext
Like `pgettext()`, but look the message up in the specified `domain`.
[ "Like", "`pgettext()`,", "but", "look", "the", "message", "up", "in", "the", "specified", "`domain`." ]
def dpgettext(self, domain, context, message): return self._domains.get(domain, self).pgettext(context, message)
['def', 'dpgettext(self,', 'domain,', 'context,', 'message):', 'return', 'self._domains.get(domain,', 'self).pgettext(context,', 'message)']
157,024
triaquae/triaquae
storage.py
Storage.size
size
Returns the total size, in bytes, of the file specified by name.
[ "Returns", "the", "total", "size,", "in", "bytes,", "of", "the", "file", "specified", "by", "name." ]
def size(self, name): raise NotImplementedError()
['def', 'size(self,', 'name):', 'raise', 'NotImplementedError()']
358,287
facebookresearch/CompilerGym
random_search.py
random_search
random_search
Run a random search on the given environment.
[ "Run", "a", "random", "search", "on", "the", "given", "environment." ]
def random_search(env: LlvmEnv) -> None: patience = int(env.action_space.n * FLAGS.patience_ratio) workers = [RandomAgentWorker(make_env=lambda : gym.make('llvm-ic-v0', benchmark=env.benchmark), patience=patience) for _ in range(FLAGS.nproc)] for worker in workers: worker.start() sleep(FLAGS.sea...
['def', 'random_search(env:', 'LlvmEnv)', '->', 'None:', 'patience', '=', 'int(env.action_space.n', '*', 'FLAGS.patience_ratio)', 'workers', '=', '[RandomAgentWorker(make_env=lambda', ':', "gym.make('llvm-ic-v0',", 'benchmark=env.benchmark),', 'patience=patience)', 'for', '_', 'in', 'range(FLAGS.nproc)]', 'for', 'worke...
135,753
Eric3911/OpenAGI
topology.py
ProcessTopology.get_axis_names
get_axis_names
Return a list of the axis names in the ordering of the topology.
[ "Return", "a", "list", "of", "the", "axis", "names", "in", "the", "ordering", "of", "the", "topology." ]
def get_axis_names(self): return self.axes
['def', 'get_axis_names(self):', 'return', 'self.axes']
252,183
tobegit3hub/deep_image_model
k8s_tensorflow.py
ParamServerClusterSpecString
ParamServerClusterSpecString
Generates parameter server spec.
[ "Generates", "parameter", "server", "spec." ]
def ParamServerClusterSpecString(num_workers, num_param_servers, port): return ClusterSpecString(num_workers, num_param_servers, port)
['def', 'ParamServerClusterSpecString(num_workers,', 'num_param_servers,', 'port):', 'return', 'ClusterSpecString(num_workers,', 'num_param_servers,', 'port)']
183,503
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
MethodContent.acceptForEach
acceptForEach
Accept and process a 'for each' style statement.
[ "Accept", "and", "process", "a", "'for", "each'", "style", "statement." ]
def acceptForEach(self, node, memo): forEach = self.factory.statement('for', fs=FS.lsrc, parent=self) identExpr = forEach.expr.right = self.factory.expr(fs=FS.l + ' in ' + FS.r) identExpr.walk(node.firstChildOfType(tokens.IDENT), memo) inExpr = identExpr.right = self.factory.expr() inExpr.walk(node....
['def', 'acceptForEach(self,', 'node,', 'memo):', 'forEach', '=', "self.factory.statement('for',", 'fs=FS.lsrc,', 'parent=self)', 'identExpr', '=', 'forEach.expr.right', '=', 'self.factory.expr(fs=FS.l', '+', "'", 'in', "'", '+', 'FS.r)', 'identExpr.walk(node.firstChildOfType(tokens.IDENT),', 'memo)', 'inExpr', '=', 'i...
11,207
NovemberChopin/RL_Tutorial
TD3.py
PolicyNetwork.evaluate
evaluate
generate action with state for calculating gradients; eval_noise_scale: as the trick of target policy smoothing, for generating noisy actions.
[ "generate", "action", "with", "state", "for", "calculating", "gradients;", "eval_noise_scale:", "as", "the", "trick", "of", "target", "policy", "smoothing,", "for", "generating", "noisy", "actions." ]
def evaluate(self, state, eval_noise_scale): state = state.astype(np.float32) action = self.forward(state) action = self.action_range * action normal = Normal(0, 1) noise = normal.sample(action.shape) * eval_noise_scale eval_noise_clip = 2 * eval_noise_scale noise = tf.clip_by_value(noise, -...
['def', 'evaluate(self,', 'state,', 'eval_noise_scale):', 'state', '=', 'state.astype(np.float32)', 'action', '=', 'self.forward(state)', 'action', '=', 'self.action_range', '*', 'action', 'normal', '=', 'Normal(0,', '1)', 'noise', '=', 'normal.sample(action.shape)', '*', 'eval_noise_scale', 'eval_noise_clip', '=', '2'...
324,818
pytorch/rl
generic.py
DistributedDataCollector.update_policy_weights_
update_policy_weights_
Updates the weights of the worker nodes.
[ "Updates", "the", "weights", "of", "the", "worker", "nodes." ]
def update_policy_weights_(self, worker_rank=None) -> None: if worker_rank is not None and worker_rank < 1: raise RuntimeError('worker_rank must be greater than 1') workers = range(self.num_workers) if worker_rank is None else [worker_rank - 1] for i in workers: rank = i + 1 if self....
['def', 'update_policy_weights_(self,', 'worker_rank=None)', '->', 'None:', 'if', 'worker_rank', 'is', 'not', 'None', 'and', 'worker_rank', '<', '1:', 'raise', "RuntimeError('worker_rank", 'must', 'be', 'greater', 'than', "1')", 'workers', '=', 'range(self.num_workers)', 'if', 'worker_rank', 'is', 'None', 'else', '[wor...
858,606
chanyn/Reasoning-RCNN
bbox_head.py
BBoxHead.refine_bboxes
refine_bboxes
Refine bboxes during training.
[ "Refine", "bboxes", "during", "training." ]
def refine_bboxes(self, rois, labels, bbox_preds, pos_is_gts, img_metas): img_ids = rois[:, 0].long().unique(sorted=True) assert img_ids.numel() == len(img_metas) bboxes_list = [] for i in range(len(img_metas)): inds = torch.nonzero(rois[:, 0] == i).squeeze() num_rois = inds.numel() ...
['def', 'refine_bboxes(self,', 'rois,', 'labels,', 'bbox_preds,', 'pos_is_gts,', 'img_metas):', 'img_ids', '=', 'rois[:,', '0].long().unique(sorted=True)', 'assert', 'img_ids.numel()', '==', 'len(img_metas)', 'bboxes_list', '=', '[]', 'for', 'i', 'in', 'range(len(img_metas)):', 'inds', '=', 'torch.nonzero(rois[:,', '0]...
831,982
rudranil723/mini-main
test_json2csv_corpus.py
TestJSON2CSV.test_file_is_wrong
test_file_is_wrong
Sanity check that file comparison is not giving false positives.
[ "Sanity", "check", "that", "file", "comparison", "is", "not", "giving", "false", "positives." ]
def test_file_is_wrong(self): ref_fn = os.path.join(self.subdir, 'tweets.20150430-223406.retweet.csv.ref') with TemporaryDirectory() as tempdir: outfn = os.path.join(tempdir, 'tweets.20150430-223406.text.csv') json2csv(self.infile, outfn, ['text'], gzip_compress=False) self.assertFalse(a...
['def', 'test_file_is_wrong(self):', 'ref_fn', '=', 'os.path.join(self.subdir,', "'tweets.20150430-223406.retweet.csv.ref')", 'with', 'TemporaryDirectory()', 'as', 'tempdir:', 'outfn', '=', 'os.path.join(tempdir,', "'tweets.20150430-223406.text.csv')", 'json2csv(self.infile,', 'outfn,', "['text'],", 'gzip_compress=Fals...
321,848
famura/SimuRLacra
parameter_exploration_sampler.py
ParameterSamplingResult.mean_returns
mean_returns
Get all parameter sample means return as a N-dim vector, where N is the number of samples.
[ "Get", "all", "parameter", "sample", "means", "return", "as", "a", "N-dim", "vector,", "where", "N", "is", "the", "number", "of", "samples." ]
def mean_returns(self) -> np.ndarray: return np.array([s.mean_undiscounted_return for s in self._samples])
['def', 'mean_returns(self)', '->', 'np.ndarray:', 'return', 'np.array([s.mean_undiscounted_return', 'for', 's', 'in', 'self._samples])']
883,908
adamshamsudeen/vision.ai
datastructures.py
MultiDict.values
values
Returns an iterator of the first value on every key's value list.
[ "Returns", "an", "iterator", "of", "the", "first", "value", "on", "every", "key's", "value", "list." ]
def values(self): for values in itervalues(dict, self): yield values[0]
['def', 'values(self):', 'for', 'values', 'in', 'itervalues(dict,', 'self):', 'yield', 'values[0]']
944,369
matsu0228/nlp-jp
posix.py
PosixEventLoop.remove_reader
remove_reader
Remove read file descriptor from the event loop.
[ "Remove", "read", "file", "descriptor", "from", "the", "event", "loop." ]
def remove_reader(self, fd): fd = fd_to_int(fd) if fd in self._read_fds: del self._read_fds[fd] self.selector.unregister(fd)
['def', 'remove_reader(self,', 'fd):', 'fd', '=', 'fd_to_int(fd)', 'if', 'fd', 'in', 'self._read_fds:', 'del', 'self._read_fds[fd]', 'self.selector.unregister(fd)']
804,411
billstark/receipt-scanner
data_utils.py
FeatureIO.int64_feature
int64_feature
Wrapper for inserting int64 features into Example proto.
[ "Wrapper", "for", "inserting", "int64", "features", "into", "Example", "proto." ]
def int64_feature(value): if not isinstance(value, list): value = [value] value_tmp = [] is_int = True for val in value: if not isinstance(val, int): is_int = False value_tmp.append(int(float(val))) if is_int is False: value = value_tmp return tf.t...
['def', 'int64_feature(value):', 'if', 'not', 'isinstance(value,', 'list):', 'value', '=', '[value]', 'value_tmp', '=', '[]', 'is_int', '=', 'True', 'for', 'val', 'in', 'value:', 'if', 'not', 'isinstance(val,', 'int):', 'is_int', '=', 'False', 'value_tmp.append(int(float(val)))', 'if', 'is_int', 'is', 'False:', 'value'...
832,077
CYBERDEVILZ/artificial-
__init__.py
FCompiler.get_flags_f90
get_flags_f90
List of Fortran 90 specific flags.
[ "List", "of", "Fortran", "90", "specific", "flags." ]
def get_flags_f90(self): return self._get_command_flags('compiler_f90')
['def', 'get_flags_f90(self):', 'return', "self._get_command_flags('compiler_f90')"]
168,669
enuguru/artificial_intelligence_and_machine_
migrate_repository.py
move_file
move_file
Moves a file and prints a message.
[ "Moves", "a", "file", "and", "prints", "a", "message." ]
def move_file(src, tgt): log.info('Moving file %s to %s' % (src, tgt)) if os.path.exists(tgt): raise Exception('Cannot move file %s because target %s already exists' % (src, tgt)) os.rename(src, tgt)
['def', 'move_file(src,', 'tgt):', "log.info('Moving", 'file', '%s', 'to', "%s'", '%', '(src,', 'tgt))', 'if', 'os.path.exists(tgt):', 'raise', "Exception('Cannot", 'move', 'file', '%s', 'because', 'target', '%s', 'already', "exists'", '%', '(src,', 'tgt))', 'os.rename(src,', 'tgt)']
129,861
JonasLandman/QCNN
__init__.py
LockBase.is_locked
is_locked
Tell whether or not the file is locked.
[ "Tell", "whether", "or", "not", "the", "file", "is", "locked." ]
def is_locked(self): raise NotImplemented('implement in subclass')
['def', 'is_locked(self):', 'raise', "NotImplemented('implement", 'in', "subclass')"]
303,340
opendilab/DI-star
actions.py
Arguments.types
types
Create an Arguments of the possible Types.
[ "Create", "an", "Arguments", "of", "the", "possible", "Types." ]
def types(cls, **kwargs): named = {name: factory(Arguments._fields.index(name), name) for (name, factory) in six.iteritems(kwargs)} return cls(**named)
['def', 'types(cls,', '**kwargs):', 'named', '=', '{name:', 'factory(Arguments._fields.index(name),', 'name)', 'for', '(name,', 'factory)', 'in', 'six.iteritems(kwargs)}', 'return', 'cls(**named)']
184,672
shery322/Lunar-Lander-ANN
mixer_test.py
SoundTypeTest.test_sound
test_sound
Ensure Sound() creation with a filename works.
[ "Ensure", "Sound()", "creation", "with", "a", "filename", "works." ]
def test_sound(self): filename = example_path(os.path.join('data', 'house_lo.wav')) sound1 = mixer.Sound(filename) sound2 = mixer.Sound(file=filename) self.assertIsInstance(sound1, mixer.Sound) self.assertIsInstance(sound2, mixer.Sound)
['def', 'test_sound(self):', 'filename', '=', "example_path(os.path.join('data',", "'house_lo.wav'))", 'sound1', '=', 'mixer.Sound(filename)', 'sound2', '=', 'mixer.Sound(file=filename)', 'self.assertIsInstance(sound1,', 'mixer.Sound)', 'self.assertIsInstance(sound2,', 'mixer.Sound)']
619,091
zackmcnulty/CSE_446-Machine_Learning
pyparsing.py
ParseExpression.leaveWhitespace
leaveWhitespace
Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on all contained expressions.
[ "Extends", "``leaveWhitespace``", "defined", "in", "base", "class,", "and", "also", "invokes", "``leaveWhitespace``", "on", "all", "contained", "expressions." ]
def leaveWhitespace(self): self.skipWhitespace = False self.exprs = [e.copy() for e in self.exprs] for e in self.exprs: e.leaveWhitespace() return self
['def', 'leaveWhitespace(self):', 'self.skipWhitespace', '=', 'False', 'self.exprs', '=', '[e.copy()', 'for', 'e', 'in', 'self.exprs]', 'for', 'e', 'in', 'self.exprs:', 'e.leaveWhitespace()', 'return', 'self']
196,543
scotthuang1989/object_detection_with_tensorflow
vgslspecs.py
VGSLSpecs.Build
Build
Builds a network with input prev_layer from a VGSLSpecs description.
[ "Builds", "a", "network", "with", "input", "prev_layer", "from", "a", "VGSLSpecs", "description." ]
def Build(self, prev_layer, model_str): self.model_str = model_str (final_layer, _) = self.BuildFromString(prev_layer, 0) return final_layer
['def', 'Build(self,', 'prev_layer,', 'model_str):', 'self.model_str', '=', 'model_str', '(final_layer,', '_)', '=', 'self.BuildFromString(prev_layer,', '0)', 'return', 'final_layer']
739,728
matsu0228/nlp-jp
__init__.py
Grouper.get_siblings
get_siblings
Returns all of the items joined with *a*, including itself.
[ "Returns", "all", "of", "the", "items", "joined", "with", "*a*,", "including", "itself." ]
def get_siblings(self, a): self.clean() siblings = self._mapping.get(ref(a), [ref(a)]) return [x() for x in siblings]
['def', 'get_siblings(self,', 'a):', 'self.clean()', 'siblings', '=', 'self._mapping.get(ref(a),', '[ref(a)])', 'return', '[x()', 'for', 'x', 'in', 'siblings]']
789,767
TheCurryMan/MedicAI
runtime.py
unicode_join
unicode_join
Simple args to unicode conversion and concatenation.
[ "Simple", "args", "to", "unicode", "conversion", "and", "concatenation." ]
def unicode_join(seq): return concat(imap(text_type, seq))
['def', 'unicode_join(seq):', 'return', 'concat(imap(text_type,', 'seq))']
648,469
ludwig-ai/ludwig
llm.py
LLM.save
save
Saves the model to the given path.
[ "Saves", "the", "model", "to", "the", "given", "path." ]
def save(self, save_path): if self.config_obj.trainer.type != 'none': weights_save_path = os.path.join(save_path, MODEL_WEIGHTS_FILE_NAME) self.model.save_pretrained(weights_save_path) else: logger.info('Skipped saving LLM without weight adjustments.')
['def', 'save(self,', 'save_path):', 'if', 'self.config_obj.trainer.type', '!=', "'none':", 'weights_save_path', '=', 'os.path.join(save_path,', 'MODEL_WEIGHTS_FILE_NAME)', 'self.model.save_pretrained(weights_save_path)', 'else:', "logger.info('Skipped", 'saving', 'LLM', 'without', 'weight', "adjustments.')"]
616,879
muhanzhang/D-VAE
test_blocksparse.py
BlockSparse_Gemv_and_Outer.test_sparseblockgemvF
test_sparseblockgemvF
Test the fortan order for W (which can happen in the grad for some graphs).
[ "Test", "the", "fortan", "order", "for", "W", "(which", "can", "happen", "in", "the", "grad", "for", "some", "graphs)." ]
def test_sparseblockgemvF(self): b = tensor.fmatrix() W = tensor.ftensor4() h = tensor.ftensor3() iIdx = tensor.imatrix() oIdx = tensor.imatrix() o = self.gemv_op(b.take(oIdx, axis=0), tensor.DimShuffle((False, False, False, False), (0, 1, 3, 2))(tensor.as_tensor_variable(W)), h, iIdx, oIdx) ...
['def', 'test_sparseblockgemvF(self):', 'b', '=', 'tensor.fmatrix()', 'W', '=', 'tensor.ftensor4()', 'h', '=', 'tensor.ftensor3()', 'iIdx', '=', 'tensor.imatrix()', 'oIdx', '=', 'tensor.imatrix()', 'o', '=', 'self.gemv_op(b.take(oIdx,', 'axis=0),', 'tensor.DimShuffle((False,', 'False,', 'False,', 'False),', '(0,', '1,'...
525,725
RasaHQ/rasa
sklearn_intent_classifier.py
SklearnIntentClassifier.get_default_config
get_default_config
The component's default config (see parent class for full docstring).
[ "The", "component's", "default", "config", "(see", "parent", "class", "for", "full", "docstring)." ]
def get_default_config() -> Dict[Text, Any]: return {'C': [1, 2, 5, 10, 20, 100], 'gamma': [0.1], 'kernels': ['linear'], 'max_cross_validation_folds': 5, 'scoring_function': 'f1_weighted', 'num_threads': 1}
['def', 'get_default_config()', '->', 'Dict[Text,', 'Any]:', 'return', "{'C':", '[1,', '2,', '5,', '10,', '20,', '100],', "'gamma':", '[0.1],', "'kernels':", "['linear'],", "'max_cross_validation_folds':", '5,', "'scoring_function':", "'f1_weighted',", "'num_threads':", '1}']
837,174
dornik/reagent
environment.py
expert
expert
Get the expert action in the current state.
[ "Get", "the", "expert", "action", "in", "the", "current", "state." ]
def expert(pose_source, targets, mode='steady'): delta_t = targets[:, :3, 3] - pose_source[:, :3, 3] delta_R = targets[:, :3, :3] @ pose_source[:, :3, :3].transpose(2, 1) delta_r = tra.matrix_to_euler_angles(delta_R, 'XYZ') def _get_axis_action(axis_delta, mode='steady'): lower_idx = (torch.buc...
['def', 'expert(pose_source,', 'targets,', "mode='steady'):", 'delta_t', '=', 'targets[:,', ':3,', '3]', '-', 'pose_source[:,', ':3,', '3]', 'delta_R', '=', 'targets[:,', ':3,', ':3]', '@', 'pose_source[:,', ':3,', ':3].transpose(2,', '1)', 'delta_r', '=', 'tra.matrix_to_euler_angles(delta_R,', "'XYZ')", 'def', '_get_a...
849,264
Eric3911/OpenAGI
conv_asr.py
ConvASREncoder.input_types
input_types
Returns definitions of module input ports.
[ "Returns", "definitions", "of", "module", "input", "ports." ]
def input_types(self): return OrderedDict({'audio_signal': NeuralType(('B', 'D', 'T'), SpectrogramType()), 'length': NeuralType(tuple('B'), LengthsType())})
['def', 'input_types(self):', 'return', "OrderedDict({'audio_signal':", "NeuralType(('B',", "'D',", "'T'),", 'SpectrogramType()),', "'length':", "NeuralType(tuple('B'),", 'LengthsType())})']
272,566
tobegit3hub/deep_image_model
alexnet_benchmark.py
time_tensorflow_run
time_tensorflow_run
Run the computation to obtain the target tensor and print timing stats.
[ "Run", "the", "computation", "to", "obtain", "the", "target", "tensor", "and", "print", "timing", "stats." ]
def time_tensorflow_run(session, target, info_string): num_steps_burn_in = 10 total_duration = 0.0 total_duration_squared = 0.0 for i in xrange(FLAGS.num_batches + num_steps_burn_in): start_time = time.time() _ = session.run(target) duration = time.time() - start_time if ...
['def', 'time_tensorflow_run(session,', 'target,', 'info_string):', 'num_steps_burn_in', '=', '10', 'total_duration', '=', '0.0', 'total_duration_squared', '=', '0.0', 'for', 'i', 'in', 'xrange(FLAGS.num_batches', '+', 'num_steps_burn_in):', 'start_time', '=', 'time.time()', '_', '=', 'session.run(target)', 'duration',...
182,227
jankrepl/mildlyoverfitted
src.py
compute_loss
compute_loss
Computer average loss over a dataset.
[ "Computer", "average", "loss", "over", "a", "dataset." ]
def compute_loss(cal, net, dataloader): net.eval() all_losses = [] for (X_batch, y_batch) in dataloader: (probs, _, _) = net(X_batch) all_losses.append(cal(probs, y_batch).item()) return np.mean(all_losses)
['def', 'compute_loss(cal,', 'net,', 'dataloader):', 'net.eval()', 'all_losses', '=', '[]', 'for', '(X_batch,', 'y_batch)', 'in', 'dataloader:', '(probs,', '_,', '_)', '=', 'net(X_batch)', 'all_losses.append(cal(probs,', 'y_batch).item())', 'return', 'np.mean(all_losses)']
670,408
rudranil723/mini-main
__init__.py
intercept_channel
intercept_channel
Intercepts a channel through a set of interceptors.
[ "Intercepts", "a", "channel", "through", "a", "set", "of", "interceptors." ]
def intercept_channel(channel, *interceptors): from grpc import _interceptor return _interceptor.intercept_channel(channel, *interceptors)
['def', 'intercept_channel(channel,', '*interceptors):', 'from', 'grpc', 'import', '_interceptor', 'return', '_interceptor.intercept_channel(channel,', '*interceptors)']
318,549
StephenLouis/Reinforcement_Learning
Breakout_DQN_class.py
get_copy_var_ops
get_copy_var_ops
타겟네트워크에 메인네트워크의 Weight값을 복사.
[ "타겟네트워크에", "메인네트워크의", "Weight값을", "복사." ]
def get_copy_var_ops(*, dest_scope_name='target', src_scope_name='main'): op_holder = [] src_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name) dest_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, scope=dest_scope_name) for (src_var, dest_var) in zip(src_vars, de...
['def', 'get_copy_var_ops(*,', "dest_scope_name='target',", "src_scope_name='main'):", 'op_holder', '=', '[]', 'src_vars', '=', 'tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,', 'scope=src_scope_name)', 'dest_vars', '=', 'tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,', 'scope=dest_scope_name)', 'for', '(src_...
345,411
sek788432/Waymo-2D-Object-Detection
model_lib_tf1_test.py
ModelLibTest.test_model_fn_in_train_mode_freeze_all_included_variables
test_model_fn_in_train_mode_freeze_all_included_variables
Tests model_fn TRAIN mode with all included variables frozen.
[ "Tests", "model_fn", "TRAIN", "mode", "with", "all", "included", "variables", "frozen." ]
def test_model_fn_in_train_mode_freeze_all_included_variables(self): configs = _get_configs_for_model(MODEL_NAME_FOR_TEST) train_config = configs['train_config'] train_config.update_trainable_variables.append('FeatureExtractor') train_config.freeze_variables.append('.*') with self.assertRaisesRegexp...
['def', 'test_model_fn_in_train_mode_freeze_all_included_variables(self):', 'configs', '=', '_get_configs_for_model(MODEL_NAME_FOR_TEST)', 'train_config', '=', "configs['train_config']", "train_config.update_trainable_variables.append('FeatureExtractor')", "train_config.freeze_variables.append('.*')", 'with', 'self.ass...
974,605
darrellsilver/norc
log.py
AbstractLog.format
format
The format of all log messages.
[ "The", "format", "of", "all", "log", "messages." ]
def format(msg, prefix): return '[%s] %s: %s\n' % (timestamp(), prefix, msg)
['def', 'format(msg,', 'prefix):', 'return', "'[%s]", '%s:', "%s\\n'", '%', '(timestamp(),', 'prefix,', 'msg)']
249,493
keya-desai/Natural-Language-Processing
Sentence.py
Sentence.getCorrectSentence
getCorrectSentence
Returns a list of strings with the sentence containing all corrections.
[ "Returns", "a", "list", "of", "strings", "with", "the", "sentence", "containing", "all", "corrections." ]
def getCorrectSentence(self): correctSentence = [] for datum in self.data: correctSentence.append(datum.word) return correctSentence
['def', 'getCorrectSentence(self):', 'correctSentence', '=', '[]', 'for', 'datum', 'in', 'self.data:', 'correctSentence.append(datum.word)', 'return', 'correctSentence']
683,506
xmax1/dvae
dataloader.py
DataLoader.load_data
load_data
Load the data used for training/validation/testing.
[ "Load", "the", "data", "used", "for", "training/validation/testing." ]
def load_data(self, **kwargs): raise NotImplementedError
['def', 'load_data(self,', '**kwargs):', 'raise', 'NotImplementedError']
554,985
triaquae/triaquae
models.py
update_last_login
update_last_login
A signal receiver which updates the last_login date for the user logging in.
[ "A", "signal", "receiver", "which", "updates", "the", "last_login", "date", "for", "the", "user", "logging", "in." ]
def update_last_login(sender, user, **kwargs): user.last_login = timezone.now() user.save(update_fields=['last_login'])
['def', 'update_last_login(sender,', 'user,', '**kwargs):', 'user.last_login', '=', 'timezone.now()', "user.save(update_fields=['last_login'])"]
357,082
opendilab/DI-star
renderer_human.py
RendererHuman.select_idle_worker
select_idle_worker
Select an idle worker.
[ "Select", "an", "idle", "worker." ]
def select_idle_worker(self, ctrl, shift): action = sc_pb.Action() mod = sc_ui.ActionSelectIdleWorker if ctrl: select_worker = mod.AddAll if shift else mod.All else: select_worker = mod.Add if shift else mod.Set action.action_ui.select_idle_worker.type = select_worker return acti...
['def', 'select_idle_worker(self,', 'ctrl,', 'shift):', 'action', '=', 'sc_pb.Action()', 'mod', '=', 'sc_ui.ActionSelectIdleWorker', 'if', 'ctrl:', 'select_worker', '=', 'mod.AddAll', 'if', 'shift', 'else', 'mod.All', 'else:', 'select_worker', '=', 'mod.Add', 'if', 'shift', 'else', 'mod.Set', 'action.action_ui.select_i...
184,779
DeepLearnXMU/ABDNMT-RNMT
options.py
parse_static_args
parse_static_args
Parse the args a first time.
[ "Parse", "the", "args", "a", "first", "time." ]
def parse_static_args(parser, input_args=None): no_default_parser = get_no_default_parser(parser) (args, unknown_args) = no_default_parser.parse_known_args(input_args) defaults = get_defaults(parser) return (args, defaults, unknown_args)
['def', 'parse_static_args(parser,', 'input_args=None):', 'no_default_parser', '=', 'get_no_default_parser(parser)', '(args,', 'unknown_args)', '=', 'no_default_parser.parse_known_args(input_args)', 'defaults', '=', 'get_defaults(parser)', 'return', '(args,', 'defaults,', 'unknown_args)']
6,350
NifTK/NiftyNet
versioneer_version.py
get_config
get_config
Create, populate and return the VersioneerConfig() object.
[ "Create,", "populate", "and", "return", "the", "VersioneerConfig()", "object." ]
def get_config(): cfg = VersioneerConfig() cfg.VCS = 'git' cfg.style = 'pep440' cfg.tag_prefix = 'v' cfg.parentdir_prefix = 'None' cfg.versionfile_source = 'niftynet/utilities/versioneer_version.py' cfg.verbose = False return cfg
['def', 'get_config():', 'cfg', '=', 'VersioneerConfig()', 'cfg.VCS', '=', "'git'", 'cfg.style', '=', "'pep440'", 'cfg.tag_prefix', '=', "'v'", 'cfg.parentdir_prefix', '=', "'None'", 'cfg.versionfile_source', '=', "'niftynet/utilities/versioneer_version.py'", 'cfg.verbose', '=', 'False', 'return', 'cfg']
294,336
arshpreetsingh/quantopian-machinelearning
html.py
escape_html
escape_html
Escape &, <, > as well as single and double quotes for HTML.
[ "Escape", "&,", "<,", ">", "as", "well", "as", "single", "and", "double", "quotes", "for", "HTML." ]
def escape_html(text, table=_escape_html_table): return text.translate(table)
['def', 'escape_html(text,', 'table=_escape_html_table):', 'return', 'text.translate(table)']
892,648
zcablii/LSKNet
sam_reppoints_head.py
SAMRepPointsHead.loss
loss
Loss function of SAM RepPoints head.
[ "Loss", "function", "of", "SAM", "RepPoints", "head." ]
def loss(self, cls_scores, pts_preds_init, pts_preds_refine, gt_bboxes, gt_labels, img_metas, gt_bboxes_ignore=None): featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores] assert len(featmap_sizes) == self.prior_generator.num_levels label_channels = self.cls_out_channels if self.use_sigmoid_cls el...
['def', 'loss(self,', 'cls_scores,', 'pts_preds_init,', 'pts_preds_refine,', 'gt_bboxes,', 'gt_labels,', 'img_metas,', 'gt_bboxes_ignore=None):', 'featmap_sizes', '=', '[featmap.size()[-2:]', 'for', 'featmap', 'in', 'cls_scores]', 'assert', 'len(featmap_sizes)', '==', 'self.prior_generator.num_levels', 'label_channels'...
616,176
TrellixVulnTeam/Unsupervised_Learning_HFI7
app.py
vi_recording_macro
vi_recording_macro
When recording a Vi macro.
[ "When", "recording", "a", "Vi", "macro." ]
def vi_recording_macro() -> bool: app = get_app() if app.editing_mode != EditingMode.VI: return False return app.vi_state.recording_register is not None
['def', 'vi_recording_macro()', '->', 'bool:', 'app', '=', 'get_app()', 'if', 'app.editing_mode', '!=', 'EditingMode.VI:', 'return', 'False', 'return', 'app.vi_state.recording_register', 'is', 'not', 'None']
435,141
caiiiac/Machine-Learning-with-Python
generate_ufuncs.py
npy_cdouble_from_double_complex
npy_cdouble_from_double_complex
Cast a cython double complex to a numpy cdouble.
[ "Cast", "a", "cython", "double", "complex", "to", "a", "numpy", "cdouble." ]
def npy_cdouble_from_double_complex(var): res = '_complexstuff.npy_cdouble_from_double_complex({})'.format(var) return res
['def', 'npy_cdouble_from_double_complex(var):', 'res', '=', "'_complexstuff.npy_cdouble_from_double_complex({})'.format(var)", 'return', 'res']
719,993
westerberg-science/openscope-glo-stim
sweepstim.py
Stimulus.update
update
Updates the stimulus based on the current frame.
[ "Updates", "the", "stimulus", "based", "on", "the", "current", "frame." ]
def update(self, frame): self.current_frame = frame try: sweep_number = self.frame_list[frame] except IndexError: return if sweep_number == self._current_sweep: pass elif sweep_number == -1: return else: for (k, v) in zip(self.dimnames, self.sweep_table[sw...
['def', 'update(self,', 'frame):', 'self.current_frame', '=', 'frame', 'try:', 'sweep_number', '=', 'self.frame_list[frame]', 'except', 'IndexError:', 'return', 'if', 'sweep_number', '==', 'self._current_sweep:', 'pass', 'elif', 'sweep_number', '==', '-1:', 'return', 'else:', 'for', '(k,', 'v)', 'in', 'zip(self.dimname...
757,661
rifqind/Agent-Programs-3KS1
utils.py
Event.remove_handler
remove_handler
Remove a handler from this callback.
[ "Remove", "a", "handler", "from", "this", "callback." ]
def remove_handler(self, handler): if handler in self._handlers: self._handlers.remove(handler)
['def', 'remove_handler(self,', 'handler):', 'if', 'handler', 'in', 'self._handlers:', 'self._handlers.remove(handler)']
45,032
NLPCodebase/PTSGM
seq2seq_model_causaltimebank.py
Seq2SeqModel.predict_sep
predict_sep
Performs predictions on a list of text.
[ "Performs", "predictions", "on", "a", "list", "of", "text." ]
def predict_sep(self, to_predict, decoder_input_token_id): self._move_model_to_device() all_outputs = [] for batch in [to_predict[i:i + self.args.eval_batch_size] for i in range(0, len(to_predict), self.args.eval_batch_size)]: if self.args.model_type == 'marian': input_ids = self.encoder...
['def', 'predict_sep(self,', 'to_predict,', 'decoder_input_token_id):', 'self._move_model_to_device()', 'all_outputs', '=', '[]', 'for', 'batch', 'in', '[to_predict[i:i', '+', 'self.args.eval_batch_size]', 'for', 'i', 'in', 'range(0,', 'len(to_predict),', 'self.args.eval_batch_size)]:', 'if', 'self.args.model_type', '=...
818,540
bislara/Object-detection-GUI
autoaugment_utils.py
equalize
equalize
Implements Equalize function from PIL using TF ops.
[ "Implements", "Equalize", "function", "from", "PIL", "using", "TF", "ops." ]
def equalize(image): def scale_channel(im, c): im = tf.cast(im[:, :, c], tf.int32) histo = tf.histogram_fixed_width(im, [0, 255], nbins=256) nonzero = tf.where(tf.not_equal(histo, 0)) nonzero_histo = tf.reshape(tf.gather(histo, nonzero), [-1]) step = (tf.reduce_sum(nonzero_h...
['def', 'equalize(image):', 'def', 'scale_channel(im,', 'c):', 'im', '=', 'tf.cast(im[:,', ':,', 'c],', 'tf.int32)', 'histo', '=', 'tf.histogram_fixed_width(im,', '[0,', '255],', 'nbins=256)', 'nonzero', '=', 'tf.where(tf.not_equal(histo,', '0))', 'nonzero_histo', '=', 'tf.reshape(tf.gather(histo,', 'nonzero),', '[-1])...
726,730
sarnsdev/social-alignment-data-mining
nn.py
NeuralNetwork.is_initialized
is_initialized
Check if the neural network was setup already.
[ "Check", "if", "the", "neural", "network", "was", "setup", "already." ]
def is_initialized(self): return self._backend is not None and self._backend.is_initialized
['def', 'is_initialized(self):', 'return', 'self._backend', 'is', 'not', 'None', 'and', 'self._backend.is_initialized']
392,437
bachiraoun/fullrmc
Constraint.py
Constraint.get_constraint_value
get_constraint_value
Method must be overloaded in children classes.
[ "Method", "must", "be", "overloaded", "in", "children", "classes." ]
def get_constraint_value(self): raise Exception(LOGGER.impl("%s '%s' method must be overloaded" % (self.__class__.__name__, inspect.stack()[0][3])))
['def', 'get_constraint_value(self):', 'raise', 'Exception(LOGGER.impl("%s', "'%s'", 'method', 'must', 'be', 'overloaded"', '%', '(self.__class__.__name__,', 'inspect.stack()[0][3])))']
213,785
matsu0228/nlp-jp
connection.py
MWSConnection.list_inbound_shipments
list_inbound_shipments
Returns a list of inbound shipments based on criteria that you specify.
[ "Returns", "a", "list", "of", "inbound", "shipments", "based", "on", "criteria", "that", "you", "specify." ]
def list_inbound_shipments(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'list_inbound_shipments(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,948
flairNLP/flair
base.py
BasePlugin.mark_func_as_hook
mark_func_as_hook
Mark method as a hook triggered by the `Pluggable`.
[ "Mark", "method", "as", "a", "hook", "triggered", "by", "the", "`Pluggable`." ]
def mark_func_as_hook(cls, func: Callable, *events: EventIdenifier) -> Callable: if len(events) == 0: events = (func.__name__,) func._plugin_hook_events = events return func
['def', 'mark_func_as_hook(cls,', 'func:', 'Callable,', '*events:', 'EventIdenifier)', '->', 'Callable:', 'if', 'len(events)', '==', '0:', 'events', '=', '(func.__name__,)', 'func._plugin_hook_events', '=', 'events', 'return', 'func']
584,853
alugupta/ares
detector.py
CustomDetector.predict
predict
Predict function used to predict bboxes on input images.
[ "Predict", "function", "used", "to", "predict", "bboxes", "on", "input", "images." ]
def predict(self, batch_data): batch_data = self.data_preprocessor(batch_data) return self.detector(batch_data)
['def', 'predict(self,', 'batch_data):', 'batch_data', '=', 'self.data_preprocessor(batch_data)', 'return', 'self.detector(batch_data)']
402,120
cpnota/autonomous-learning-library
approximation.py
Approximation.no_grad
no_grad
Run a forward pass of the model in no_grad mode.
[ "Run", "a", "forward", "pass", "of", "the", "model", "in", "no_grad", "mode." ]
def no_grad(self, *inputs): with torch.no_grad(): return self.model(*inputs)
['def', 'no_grad(self,', '*inputs):', 'with', 'torch.no_grad():', 'return', 'self.model(*inputs)']
93,548
huawei-noah/xingtian
tensorflow_fn.py
softmax
softmax
Apply a softmax function.
[ "Apply", "a", "softmax", "function." ]
def softmax(input, dim=None): return tf.nn.softmax(input, dim)
['def', 'softmax(input,', 'dim=None):', 'return', 'tf.nn.softmax(input,', 'dim)']
962,831
AEProgrammer/object_detection
record_demo.py
convert_from_cls_format
convert_from_cls_format
Convert from the class boxes/segms/keyps format generated by the testing code.
[ "Convert", "from", "the", "class", "boxes/segms/keyps", "format", "generated", "by", "the", "testing", "code." ]
def convert_from_cls_format(cls_boxes, cls_segms, cls_keyps): box_list = [b for b in cls_boxes if len(b) > 0] if len(box_list) > 0: boxes = np.concatenate(box_list) else: boxes = None if cls_segms is not None: segms = [s for slist in cls_segms for s in slist] else: se...
['def', 'convert_from_cls_format(cls_boxes,', 'cls_segms,', 'cls_keyps):', 'box_list', '=', '[b', 'for', 'b', 'in', 'cls_boxes', 'if', 'len(b)', '>', '0]', 'if', 'len(box_list)', '>', '0:', 'boxes', '=', 'np.concatenate(box_list)', 'else:', 'boxes', '=', 'None', 'if', 'cls_segms', 'is', 'not', 'None:', 'segms', '=', '[...
773,776
akandykeller/NeuralWaveMachines
game_dynamics.py
ZeroSumGame.generate_trajectories
generate_trajectories
Generates trajectories of the system in phase space.
[ "Generates", "trajectories", "of", "the", "system", "in", "phase", "space." ]
def generate_trajectories(self, x0: jnp.ndarray, t0: utils.FloatArray, t_eval: jnp.ndarray) -> jnp.ndarray: if self.method == 'scipy': x0_shape = x0.shape def fun(_, y): y = y.reshape(x0_shape) y_next = np.apply_along_axis(self.dynamics, -1, y) return y_next.resh...
['def', 'generate_trajectories(self,', 'x0:', 'jnp.ndarray,', 't0:', 'utils.FloatArray,', 't_eval:', 'jnp.ndarray)', '->', 'jnp.ndarray:', 'if', 'self.method', '==', "'scipy':", 'x0_shape', '=', 'x0.shape', 'def', 'fun(_,', 'y):', 'y', '=', 'y.reshape(x0_shape)', 'y_next', '=', 'np.apply_along_axis(self.dynamics,', '-1...
293,597
palmettos/neat-autoencoders
test_config.py
test_nonexistent_config
test_nonexistent_config
Check that attempting to open a non-existent config file raises an Exception with appropriate message.
[ "Check", "that", "attempting", "to", "open", "a", "non-existent", "config", "file", "raises", "an", "Exception", "with", "appropriate", "message." ]
def test_nonexistent_config(): passed = False try: c = neat.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, 'wubba-lubba-dub-dub') except Exception as e: passed = 'No such config file' in str(e) assert passed
['def', 'test_nonexistent_config():', 'passed', '=', 'False', 'try:', 'c', '=', 'neat.Config(neat.DefaultGenome,', 'neat.DefaultReproduction,', 'neat.DefaultSpeciesSet,', 'neat.DefaultStagnation,', "'wubba-lubba-dub-dub')", 'except', 'Exception', 'as', 'e:', 'passed', '=', "'No", 'such', 'config', "file'", 'in', 'str(e...
735,223
MycroftAI/mycroft-core
skill_tester.py
temporary_handler
temporary_handler
Context manager to replace the default logger with a temporary logger.
[ "Context", "manager", "to", "replace", "the", "default", "logger", "with", "a", "temporary", "logger." ]
def temporary_handler(log, handler): old_handler = log.handler log.handler = handler yield log.handler = old_handler
['def', 'temporary_handler(log,', 'handler):', 'old_handler', '=', 'log.handler', 'log.handler', '=', 'handler', 'yield', 'log.handler', '=', 'old_handler']
290,788
Farama-Foundation/Gymnasium
frame_stack.py
FrameStack.reset
reset
Reset the environment with kwargs.
[ "Reset", "the", "environment", "with", "kwargs." ]
def reset(self, **kwargs): (obs, info) = self.env.reset(**kwargs) [self.frames.append(obs) for _ in range(self.num_stack)] return (self.observation(None), info)
['def', 'reset(self,', '**kwargs):', '(obs,', 'info)', '=', 'self.env.reset(**kwargs)', '[self.frames.append(obs)', 'for', '_', 'in', 'range(self.num_stack)]', 'return', '(self.observation(None),', 'info)']
573,377
JinliangLu96/CL_UNMT
evaluator.py
eval_moses_bleu
eval_moses_bleu
Given a file of hypothesis and reference files, evaluate the BLEU score using Moses scripts.
[ "Given", "a", "file", "of", "hypothesis", "and", "reference", "files,", "evaluate", "the", "BLEU", "score", "using", "Moses", "scripts." ]
def eval_moses_bleu(ref, hyp): assert os.path.isfile(hyp) assert os.path.isfile(BLEU_SCRIPT_PATH) command = BLEU_SCRIPT_PATH + ' %s < %s' p = subprocess.Popen(command % (ref, hyp), stdout=subprocess.PIPE, shell=True) result = p.communicate()[0].decode('utf-8') if result.startswith('BLEU'): ...
['def', 'eval_moses_bleu(ref,', 'hyp):', 'assert', 'os.path.isfile(hyp)', 'assert', 'os.path.isfile(BLEU_SCRIPT_PATH)', 'command', '=', 'BLEU_SCRIPT_PATH', '+', "'", '%s', '<', "%s'", 'p', '=', 'subprocess.Popen(command', '%', '(ref,', 'hyp),', 'stdout=subprocess.PIPE,', 'shell=True)', 'result', '=', "p.communicate()[0...
123,268
EvanWY/CARLASemSeg
tcp.py
TCPClient.disconnect
disconnect
Disconnect any active connection.
[ "Disconnect", "any", "active", "connection." ]
def disconnect(self): if self._socket is not None: logging.debug('%sdisconnecting', self._logprefix) self._socket.close() self._socket = None
['def', 'disconnect(self):', 'if', 'self._socket', 'is', 'not', 'None:', "logging.debug('%sdisconnecting',", 'self._logprefix)', 'self._socket.close()', 'self._socket', '=', 'None']
456,029
clips/pattern
__init__.py
Application.elapsed
elapsed
Yields the elapsed time since the start of the request.
[ "Yields", "the", "elapsed", "time", "since", "the", "start", "of", "the", "request." ]
def elapsed(self): return time.time() - cp.request.time
['def', 'elapsed(self):', 'return', 'time.time()', '-', 'cp.request.time']
764,717
ahthie7u/cockpit
_utils_deepobs.py
_DeepOBSRunner.training
training
Training loop for this runner.
[ "Training", "loop", "for", "this", "runner." ]
def training(self, tproblem, hyperparams, num_epochs, print_train_iter, train_log_interval, tb_log, tb_log_dir, **training_params): opt = self._optimizer_class(tproblem.net.parameters(), **hyperparams) lr_sched = training_params['lr_schedule'](num_epochs) scheduler = LambdaLR(opt, lr_lambda=lr_sched) lo...
['def', 'training(self,', 'tproblem,', 'hyperparams,', 'num_epochs,', 'print_train_iter,', 'train_log_interval,', 'tb_log,', 'tb_log_dir,', '**training_params):', 'opt', '=', 'self._optimizer_class(tproblem.net.parameters(),', '**hyperparams)', 'lr_sched', '=', "training_params['lr_schedule'](num_epochs)", 'scheduler',...
492,740
ADLab3Ds/TiG-BEV
nuscenes_mono_dataset.py
nusc_box_to_cam_box3d
nusc_box_to_cam_box3d
Convert boxes from :obj:`NuScenesBox` to :obj:`CameraInstance3DBoxes`.
[ "Convert", "boxes", "from", ":obj:`NuScenesBox`", "to", ":obj:`CameraInstance3DBoxes`." ]
def nusc_box_to_cam_box3d(boxes): locs = torch.Tensor([b.center for b in boxes]).view(-1, 3) dims = torch.Tensor([b.wlh for b in boxes]).view(-1, 3) rots = torch.Tensor([b.orientation.yaw_pitch_roll[0] for b in boxes]).view(-1, 1) velocity = torch.Tensor([b.velocity[:2] for b in boxes]).view(-1, 2) ...
['def', 'nusc_box_to_cam_box3d(boxes):', 'locs', '=', 'torch.Tensor([b.center', 'for', 'b', 'in', 'boxes]).view(-1,', '3)', 'dims', '=', 'torch.Tensor([b.wlh', 'for', 'b', 'in', 'boxes]).view(-1,', '3)', 'rots', '=', 'torch.Tensor([b.orientation.yaw_pitch_roll[0]', 'for', 'b', 'in', 'boxes]).view(-1,', '1)', 'velocity'...
916,935
NoGameNoLife00/mybolg
tbtools.py
Frame.get_annotated_lines
get_annotated_lines
Helper function that returns lines with extra information.
[ "Helper", "function", "that", "returns", "lines", "with", "extra", "information." ]
def get_annotated_lines(self): lines = [Line(idx + 1, x) for (idx, x) in enumerate(self.sourcelines)] if hasattr(self.code, 'co_firstlineno'): lineno = self.code.co_firstlineno - 1 while lineno > 0: if _funcdef_re.match(lines[lineno].code): break lineno -=...
['def', 'get_annotated_lines(self):', 'lines', '=', '[Line(idx', '+', '1,', 'x)', 'for', '(idx,', 'x)', 'in', 'enumerate(self.sourcelines)]', 'if', 'hasattr(self.code,', "'co_firstlineno'):", 'lineno', '=', 'self.code.co_firstlineno', '-', '1', 'while', 'lineno', '>', '0:', 'if', '_funcdef_re.match(lines[lineno].code):...
290,096
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data.py
plot_images
plot_images
Images should be a (N_images x pixels) matrix.
[ "Images", "should", "be", "a", "(N_images", "x", "pixels)", "matrix." ]
def plot_images(images, ax, ims_per_row=5, padding=5, digit_dimensions=(28, 28), cmap=matplotlib.cm.binary, vmin=None, vmax=None): N_images = images.shape[0] N_rows = (N_images - 1) // ims_per_row + 1 pad_value = np.min(images.ravel()) concat_images = np.full(((digit_dimensions[0] + padding) * N_rows + ...
['def', 'plot_images(images,', 'ax,', 'ims_per_row=5,', 'padding=5,', 'digit_dimensions=(28,', '28),', 'cmap=matplotlib.cm.binary,', 'vmin=None,', 'vmax=None):', 'N_images', '=', 'images.shape[0]', 'N_rows', '=', '(N_images', '-', '1)', '//', 'ims_per_row', '+', '1', 'pad_value', '=', 'np.min(images.ravel())', 'concat_...
12,204
ivanmontero/autobot
tokenization_utils_base.py
PreTrainedTokenizerBase.batch_decode
batch_decode
Convert a list of lists of token ids into a list of strings by calling decode.
[ "Convert", "a", "list", "of", "lists", "of", "token", "ids", "into", "a", "list", "of", "strings", "by", "calling", "decode." ]
def batch_decode(self, sequences: List[List[int]], skip_special_tokens: bool=False, clean_up_tokenization_spaces: bool=True) -> List[str]: return [self.decode(seq, skip_special_tokens=skip_special_tokens, clean_up_tokenization_spaces=clean_up_tokenization_spaces) for seq in sequences]
['def', 'batch_decode(self,', 'sequences:', 'List[List[int]],', 'skip_special_tokens:', 'bool=False,', 'clean_up_tokenization_spaces:', 'bool=True)', '->', 'List[str]:', 'return', '[self.decode(seq,', 'skip_special_tokens=skip_special_tokens,', 'clean_up_tokenization_spaces=clean_up_tokenization_spaces)', 'for', 'seq',...
418,414
MattZhao/cs188-projects
search_hyperparams.py
search_hyperparams
search_hyperparams
Question 8: Evaluate various setups of hyperparameter and find the best one.
[ "Question", "8:", "Evaluate", "various", "setups", "of", "hyperparameter", "and", "find", "the", "best", "one." ]
def search_hyperparams(train_data, train_labels, val_data, val_labels, learning_rates, momentums, batch_sizes, iterations, model_class, init_param_values=None, use_bn=False): hyperparams = [learning_rates, momentums, batch_sizes] for hyperparam in hyperparams: if len(hyperparam) != len(hyperparams[0]): ...
['def', 'search_hyperparams(train_data,', 'train_labels,', 'val_data,', 'val_labels,', 'learning_rates,', 'momentums,', 'batch_sizes,', 'iterations,', 'model_class,', 'init_param_values=None,', 'use_bn=False):', 'hyperparams', '=', '[learning_rates,', 'momentums,', 'batch_sizes]', 'for', 'hyperparam', 'in', 'hyperparam...
226,119
tusen-ai/SST
kitti2d_dataset.py
Kitti2DDataset.reformat_bbox
reformat_bbox
Reformat bounding boxes to KITTI 2D styles.
[ "Reformat", "bounding", "boxes", "to", "KITTI", "2D", "styles." ]
def reformat_bbox(self, outputs, out=None): from mmdet3d.core.bbox.transforms import bbox2result_kitti2d sample_idx = [info['image']['image_idx'] for info in self.data_infos] result_files = bbox2result_kitti2d(outputs, self.CLASSES, sample_idx, out) return result_files
['def', 'reformat_bbox(self,', 'outputs,', 'out=None):', 'from', 'mmdet3d.core.bbox.transforms', 'import', 'bbox2result_kitti2d', 'sample_idx', '=', "[info['image']['image_idx']", 'for', 'info', 'in', 'self.data_infos]', 'result_files', '=', 'bbox2result_kitti2d(outputs,', 'self.CLASSES,', 'sample_idx,', 'out)', 'retur...
872,369
intel/neural-compressor
patterns.py
Pattern.get_masks_local
get_masks_local
Obtain layers' local masks.
[ "Obtain", "layers'", "local", "masks." ]
def get_masks_local(self, scores, target_sparsity_ratio, pre_masks, max_sparsity_ratio_per_layer): masks = {} if isinstance(self, PatternNxM) and (not isinstance(self.block_size, dict)): self.block_size = self.get_block_size_dict(pre_masks) for key in scores.keys(): score = {key: scores[key]...
['def', 'get_masks_local(self,', 'scores,', 'target_sparsity_ratio,', 'pre_masks,', 'max_sparsity_ratio_per_layer):', 'masks', '=', '{}', 'if', 'isinstance(self,', 'PatternNxM)', 'and', '(not', 'isinstance(self.block_size,', 'dict)):', 'self.block_size', '=', 'self.get_block_size_dict(pre_masks)', 'for', 'key', 'in', '...
738,663
loicmarie/hands-detection
data_utils.py
basic_tokenizer
basic_tokenizer
Very basic tokenizer: split the sentence into a list of tokens.
[ "Very", "basic", "tokenizer:", "split", "the", "sentence", "into", "a", "list", "of", "tokens." ]
def basic_tokenizer(sentence): words = [] for space_separated_fragment in sentence.strip().split(): words.extend(_WORD_SPLIT.split(space_separated_fragment)) return [w for w in words if w]
['def', 'basic_tokenizer(sentence):', 'words', '=', '[]', 'for', 'space_separated_fragment', 'in', 'sentence.strip().split():', 'words.extend(_WORD_SPLIT.split(space_separated_fragment))', 'return', '[w', 'for', 'w', 'in', 'words', 'if', 'w]']
575,600
devashish-patel/webcam-motion-detector
script.py
ScriptMagics.killbgscripts
killbgscripts
Kill all BG processes started by %%script and its family.
[ "Kill", "all", "BG", "processes", "started", "by", "%%script", "and", "its", "family." ]
def killbgscripts(self, _nouse_=''): self.kill_bg_processes() print('All background processes were killed.')
['def', 'killbgscripts(self,', "_nouse_=''):", 'self.kill_bg_processes()', "print('All", 'background', 'processes', 'were', "killed.')"]
978,930
google-research/batch-ppo
configs.py
hopper
hopper
Configuration for MuJoCo's hopper task.
[ "Configuration", "for", "MuJoCo's", "hopper", "task." ]
def hopper(): locals().update(default()) env = 'Hopper-v2' max_length = 1000 steps = 10000000.0 update_every = 60 return locals()
['def', 'hopper():', 'locals().update(default())', 'env', '=', "'Hopper-v2'", 'max_length', '=', '1000', 'steps', '=', '10000000.0', 'update_every', '=', '60', 'return', 'locals()']
95,015
43Carrig/recurrent_neural_networks_practice
well_known_types.py
Duration.FromTimedelta
FromTimedelta
Converts timedelta to Duration.
[ "Converts", "timedelta", "to", "Duration." ]
def FromTimedelta(self, td): self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, td.microseconds * _NANOS_PER_MICROSECOND)
['def', 'FromTimedelta(self,', 'td):', 'self._NormalizeDuration(td.seconds', '+', 'td.days', '*', '_SECONDS_PER_DAY,', 'td.microseconds', '*', '_NANOS_PER_MICROSECOND)']
310,020
43Carrig/recurrent_neural_networks_practice
callbacks.py
TensorBoard.on_epoch_begin
on_epoch_begin
Add histogram op to Model test_function callbacks, reset batch count.
[ "Add", "histogram", "op", "to", "Model", "test_function", "callbacks,", "reset", "batch", "count." ]
def on_epoch_begin(self, epoch, logs=None): if self.histogram_freq and epoch % self.histogram_freq == 0: self._epoch = epoch self._current_val_batch = 0 if self.merged not in self.model.test_function.fetches: self.model.test_function.fetches.append(self.merged) self.m...
['def', 'on_epoch_begin(self,', 'epoch,', 'logs=None):', 'if', 'self.histogram_freq', 'and', 'epoch', '%', 'self.histogram_freq', '==', '0:', 'self._epoch', '=', 'epoch', 'self._current_val_batch', '=', '0', 'if', 'self.merged', 'not', 'in', 'self.model.test_function.fetches:', 'self.model.test_function.fetches.append(...
336,815
HuiGuanLab/HiCo
meters.py
TrainMeter.iter_toc
iter_toc
Stop to record time.
[ "Stop", "to", "record", "time." ]
def iter_toc(self): self.iter_timer.pause()
['def', 'iter_toc(self):', 'self.iter_timer.pause()']
206,248
myothida/Supervised-Machine-Learning
format.py
DataFrameRenderer.to_csv
to_csv
Render dataframe as comma-separated file.
[ "Render", "dataframe", "as", "comma-separated", "file." ]
def to_csv(self, path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None=None, encoding: str | None=None, sep: str=',', columns: Sequence[Hashable] | None=None, index_label: IndexLabel | None=None, mode: str='w', compression: CompressionOptions='infer', quoting: int | None=None, quotechar: str='"', lineter...
['def', 'to_csv(self,', 'path_or_buf:', 'FilePath', '|', 'WriteBuffer[bytes]', '|', 'WriteBuffer[str]', '|', 'None=None,', 'encoding:', 'str', '|', 'None=None,', 'sep:', "str=',',", 'columns:', 'Sequence[Hashable]', '|', 'None=None,', 'index_label:', 'IndexLabel', '|', 'None=None,', 'mode:', "str='w',", 'compression:',...
443,382
lord-alfred/dnlp
preprocess.py
replace_urls
replace_urls
Replace all URLs in ``text`` str with ``replace_with`` str.
[ "Replace", "all", "URLs", "in", "``text``", "str", "with", "``replace_with``", "str." ]
def replace_urls(text: str, replace_with: str='*URL*') -> str: return URL_REGEX.sub(replace_with, SHORT_URL_REGEX.sub(replace_with, text))
['def', 'replace_urls(text:', 'str,', 'replace_with:', "str='*URL*')", '->', 'str:', 'return', 'URL_REGEX.sub(replace_with,', 'SHORT_URL_REGEX.sub(replace_with,', 'text))']
522,469
rlgraph/rlgraph
test_ppo_agent_short_task_learning.py
TestPPOShortTaskLearning.test_ppo_on_lunar_lander
test_ppo_on_lunar_lander
Creates a PPO Agent and runs it via a Runner on the Pendulum env.
[ "Creates", "a", "PPO", "Agent", "and", "runs", "it", "via", "a", "Runner", "on", "the", "Pendulum", "env." ]
def test_ppo_on_lunar_lander(self): env = OpenAIGymEnv('LunarLander-v2') agent = PPOAgent.from_spec(config_from_path('configs/ppo_agent_for_pendulum.json'), state_space=env.state_space, action_space=env.action_space) worker = SingleThreadedWorker(env_spec=lambda : env, agent=agent, worker_executes_preproces...
['def', 'test_ppo_on_lunar_lander(self):', 'env', '=', "OpenAIGymEnv('LunarLander-v2')", 'agent', '=', "PPOAgent.from_spec(config_from_path('configs/ppo_agent_for_pendulum.json'),", 'state_space=env.state_space,', 'action_space=env.action_space)', 'worker', '=', 'SingleThreadedWorker(env_spec=lambda', ':', 'env,', 'age...
862,713
chinmayjog13/Computer-Vision
visualization_utils.py
draw_bounding_boxes_on_image_tensors
draw_bounding_boxes_on_image_tensors
Draws bounding boxes, masks, and keypoints on batch of image tensors.
[ "Draws", "bounding", "boxes,", "masks,", "and", "keypoints", "on", "batch", "of", "image", "tensors." ]
def draw_bounding_boxes_on_image_tensors(images, boxes, classes, scores, category_index, original_image_spatial_shape=None, true_image_shape=None, instance_masks=None, keypoints=None, track_ids=None, max_boxes_to_draw=20, min_score_thresh=0.2, use_normalized_coordinates=True): if images.shape[3] > 3: images...
['def', 'draw_bounding_boxes_on_image_tensors(images,', 'boxes,', 'classes,', 'scores,', 'category_index,', 'original_image_spatial_shape=None,', 'true_image_shape=None,', 'instance_masks=None,', 'keypoints=None,', 'track_ids=None,', 'max_boxes_to_draw=20,', 'min_score_thresh=0.2,', 'use_normalized_coordinates=True):',...
459,008
calico/basenji
layers.py
positional_features_central_mask
positional_features_central_mask
Positional features using a central mask (allow only central features).
[ "Positional", "features", "using", "a", "central", "mask", "(allow", "only", "central", "features)." ]
def positional_features_central_mask(positions: tf.Tensor, feature_size: int, seq_length: int): pow_rate = np.exp(np.log(seq_length + 1) / feature_size).astype('float32') center_widths = tf.pow(pow_rate, tf.range(1, feature_size + 1, dtype=tf.float32)) center_widths = center_widths - 1 center_widths = _...
['def', 'positional_features_central_mask(positions:', 'tf.Tensor,', 'feature_size:', 'int,', 'seq_length:', 'int):', 'pow_rate', '=', 'np.exp(np.log(seq_length', '+', '1)', '/', "feature_size).astype('float32')", 'center_widths', '=', 'tf.pow(pow_rate,', 'tf.range(1,', 'feature_size', '+', '1,', 'dtype=tf.float32))', ...
94,574
arshpreetsingh/quantopian-machinelearning
img.py
FontManager.get_char_size
get_char_size
Get the character size.
[ "Get", "the", "character", "size." ]
def get_char_size(self): return self.fonts['NORMAL'].getsize('M')
['def', 'get_char_size(self):', 'return', "self.fonts['NORMAL'].getsize('M')"]
892,652
mfbx9da4/neuron-astrocyte-networks
temp_node1.py
ProtoNode.activate
activate
This function applies the activation function to the value of the node.
[ "This", "function", "applies", "the", "activation", "function", "to", "the", "value", "of", "the", "node." ]
def activate(self): return self._activate(self._value)
['def', 'activate(self):', 'return', 'self._activate(self._value)']
722,834
TrellixVulnTeam/Unsupervised_Learning_HFI7
pygments.py
PygmentsLexer.lex_document
lex_document
Create a lexer function that takes a line number and returns the list of (style_str, text) tuples as the Pygments lexer returns for that line.
[ "Create", "a", "lexer", "function", "that", "takes", "a", "line", "number", "and", "returns", "the", "list", "of", "(style_str,", "text)", "tuples", "as", "the", "Pygments", "lexer", "returns", "for", "that", "line." ]
def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]: LineGenerator = Generator[Tuple[int, StyleAndTextTuples], None, None] cache: Dict[int, StyleAndTextTuples] = {} line_generators: Dict[LineGenerator, int] = {} def get_syntax_sync() -> SyntaxSync: if self.sync_fro...
['def', 'lex_document(self,', 'document:', 'Document)', '->', 'Callable[[int],', 'StyleAndTextTuples]:', 'LineGenerator', '=', 'Generator[Tuple[int,', 'StyleAndTextTuples],', 'None,', 'None]', 'cache:', 'Dict[int,', 'StyleAndTextTuples]', '=', '{}', 'line_generators:', 'Dict[LineGenerator,', 'int]', '=', '{}', 'def', '...
435,402
jelgun/Artificial-Intelligence
utils.py
matrix_multiplication
matrix_multiplication
Return a matrix as a matrix-multiplication of x and arbitrary number of matrices *y.
[ "Return", "a", "matrix", "as", "a", "matrix-multiplication", "of", "x", "and", "arbitrary", "number", "of", "matrices", "*y." ]
def matrix_multiplication(x, *y): result = x for _y in y: result = np.matmul(result, _y) return result
['def', 'matrix_multiplication(x,', '*y):', 'result', '=', 'x', 'for', '_y', 'in', 'y:', 'result', '=', 'np.matmul(result,', '_y)', 'return', 'result']
121,809
TrellixVulnTeam/Unsupervised_Learning_HFI7
options.py
OptionParser.print_help
print_help
Prints all the command line options to stderr (or another file).
[ "Prints", "all", "the", "command", "line", "options", "to", "stderr", "(or", "another", "file)." ]
def print_help(self, file: Optional[TextIO]=None) -> None: if file is None: file = sys.stderr print('Usage: %s [OPTIONS]' % sys.argv[0], file=file) print('\nOptions:\n', file=file) by_group = {} for option in self._options.values(): by_group.setdefault(option.group_name, []).append(o...
['def', 'print_help(self,', 'file:', 'Optional[TextIO]=None)', '->', 'None:', 'if', 'file', 'is', 'None:', 'file', '=', 'sys.stderr', "print('Usage:", '%s', "[OPTIONS]'", '%', 'sys.argv[0],', 'file=file)', "print('\\nOptions:\\n',", 'file=file)', 'by_group', '=', '{}', 'for', 'option', 'in', 'self._options.values():', ...
437,623
sithu31296/self-supervised-learning
vicreg.py
off_diagonal
off_diagonal
Returns the off-diagonal elements of a square matrix.
[ "Returns", "the", "off-diagonal", "elements", "of", "a", "square", "matrix." ]
def off_diagonal(tensor: torch.Tensor) -> torch.Tensor: (n, m) = tensor.shape assert n == m, 'Not a square tensor' return tensor.flatten()[:-1].view(n - 1, n + 1)[:, 1:].flatten()
['def', 'off_diagonal(tensor:', 'torch.Tensor)', '->', 'torch.Tensor:', '(n,', 'm)', '=', 'tensor.shape', 'assert', 'n', '==', 'm,', "'Not", 'a', 'square', "tensor'", 'return', 'tensor.flatten()[:-1].view(n', '-', '1,', 'n', '+', '1)[:,', '1:].flatten()']
342,054
chen742/PiPa
cityscapes.py
CityscapesDataset.results2img
results2img
Write the segmentation results to images.
[ "Write", "the", "segmentation", "results", "to", "images." ]
def results2img(self, results, imgfile_prefix, to_label_id): mmcv.mkdir_or_exist(imgfile_prefix) result_files = [] prog_bar = mmcv.ProgressBar(len(self)) for idx in range(len(self)): result = results[idx] if to_label_id: result = self._convert_to_label_id(result) file...
['def', 'results2img(self,', 'results,', 'imgfile_prefix,', 'to_label_id):', 'mmcv.mkdir_or_exist(imgfile_prefix)', 'result_files', '=', '[]', 'prog_bar', '=', 'mmcv.ProgressBar(len(self))', 'for', 'idx', 'in', 'range(len(self)):', 'result', '=', 'results[idx]', 'if', 'to_label_id:', 'result', '=', 'self._convert_to_la...
305,198
facebookresearch/ReAgent
oss_data_fetcher.py
misc_column_preprocessing
misc_column_preprocessing
Miscellaneous columns are step, time_diff, sequence_number, not_terminal.
[ "Miscellaneous", "columns", "are", "step,", "time_diff,", "sequence_number,", "not_terminal." ]
def misc_column_preprocessing(df, multi_steps: Optional[int]): df = df.withColumn('step', make_get_step_udf(multi_steps)('next_state_features')) next_long_udf = make_next_udf(multi_steps, LongType()) df = df.withColumn('time_diff', next_long_udf('time_diff')) df = df.withColumn('sequence_number', col('s...
['def', 'misc_column_preprocessing(df,', 'multi_steps:', 'Optional[int]):', 'df', '=', "df.withColumn('step',", "make_get_step_udf(multi_steps)('next_state_features'))", 'next_long_udf', '=', 'make_next_udf(multi_steps,', 'LongType())', 'df', '=', "df.withColumn('time_diff',", "next_long_udf('time_diff'))", 'df', '=', ...
304,497