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
bytedance/ParaGen
transformer_decoder_layer.py
TransformerDecoderLayer.forward
forward
Pass the inputs (and mask) through the decoder layer in training mode.
[ "Pass", "the", "inputs", "(and", "mask)", "through", "the", "decoder", "layer", "in", "training", "mode." ]
def forward(self, tgt: Tensor, memory: Tensor, tgt_mask: Optional[Tensor]=None, memory_mask: Optional[Tensor]=None, tgt_key_padding_mask: Optional[Tensor]=None, memory_key_padding_mask: Optional[Tensor]=None) -> Tensor: if self._mode == 'infer': tgt = tgt[-1:] (tgt_mask, tgt_key_padding_mask) = (Non...
['def', 'forward(self,', 'tgt:', 'Tensor,', 'memory:', 'Tensor,', 'tgt_mask:', 'Optional[Tensor]=None,', 'memory_mask:', 'Optional[Tensor]=None,', 'tgt_key_padding_mask:', 'Optional[Tensor]=None,', 'memory_key_padding_mask:', 'Optional[Tensor]=None)', '->', 'Tensor:', 'if', 'self._mode', '==', "'infer':", 'tgt', '=', '...
779,500
drprojects/superpoint_transformer
sparse.py
csr_to_dense
csr_to_dense
Convert a CSR matrix to its dense counterpart of a given shape.
[ "Convert", "a", "CSR", "matrix", "to", "its", "dense", "counterpart", "of", "a", "given", "shape." ]
def csr_to_dense(pointers, columns, values, shape=None): assert pointers.dim() == 1 assert columns.dim() == 1 assert values.dim() == 1 assert shape is None or len(shape) == 2 assert pointers.device == columns.device == values.device device = pointers.device shape_guess = (pointers.shape[0] -...
['def', 'csr_to_dense(pointers,', 'columns,', 'values,', 'shape=None):', 'assert', 'pointers.dim()', '==', '1', 'assert', 'columns.dim()', '==', '1', 'assert', 'values.dim()', '==', '1', 'assert', 'shape', 'is', 'None', 'or', 'len(shape)', '==', '2', 'assert', 'pointers.device', '==', 'columns.device', '==', 'values.de...
880,940
desimone/segmentation-models
download_and_convert_pascal.py
get_images_and_masks
get_images_and_masks
Returns a list of mask and image file names.
[ "Returns", "a", "list", "of", "mask", "and", "image", "file", "names." ]
def get_images_and_masks(dataset_dir): voc_root = os.path.join(dataset_dir, _VOC_ROOT) mask_root = os.path.join(voc_root, 'SegmentationClass') img_root = os.path.join(voc_root, 'JPEGImages') print('Root:%s\nMasks:%s\nImages:%s' % (voc_root, img_root, mask_root)) images = [] masks = [] for fi...
['def', 'get_images_and_masks(dataset_dir):', 'voc_root', '=', 'os.path.join(dataset_dir,', '_VOC_ROOT)', 'mask_root', '=', 'os.path.join(voc_root,', "'SegmentationClass')", 'img_root', '=', 'os.path.join(voc_root,', "'JPEGImages')", "print('Root:%s\\nMasks:%s\\nImages:%s'", '%', '(voc_root,', 'img_root,', 'mask_root))...
842,515
myothida/Supervised-Machine-Learning
spinner.py
Spinner.update
update
Updates attributes of a spinner after it has been started.
[ "Updates", "attributes", "of", "a", "spinner", "after", "it", "has", "been", "started." ]
def update(self, *, text: 'RenderableType'='', style: Optional['StyleType']=None, speed: Optional[float]=None) -> None: if text: self.text = Text.from_markup(text) if isinstance(text, str) else text if style: self.style = style if speed: self._update_speed = speed
['def', 'update(self,', '*,', 'text:', "'RenderableType'='',", 'style:', "Optional['StyleType']=None,", 'speed:', 'Optional[float]=None)', '->', 'None:', 'if', 'text:', 'self.text', '=', 'Text.from_markup(text)', 'if', 'isinstance(text,', 'str)', 'else', 'text', 'if', 'style:', 'self.style', '=', 'style', 'if', 'speed:...
445,083
keras-team/keras-cv
sam.py
SegmentAnythingModel.backbone_presets
backbone_presets
Dictionary of preset names and configurations of compatible backbones.
[ "Dictionary", "of", "preset", "names", "and", "configurations", "of", "compatible", "backbones." ]
def backbone_presets(cls): return copy.deepcopy(backbone_presets)
['def', 'backbone_presets(cls):', 'return', 'copy.deepcopy(backbone_presets)']
595,345
bfshi/TOAST
logging.py
setup_logging
setup_logging
Sets up the logging.
[ "Sets", "up", "the", "logging." ]
def setup_logging(num_gpu, num_shards, output='', name='visual_prompt', color=True): if is_master_process(num_gpu): logging.root.handlers = [] logging.basicConfig(level=logging.INFO, format=_FORMAT, stream=sys.stdout) else: _suppress_print() if name is None: name = __name__ ...
['def', 'setup_logging(num_gpu,', 'num_shards,', "output='',", "name='visual_prompt',", 'color=True):', 'if', 'is_master_process(num_gpu):', 'logging.root.handlers', '=', '[]', 'logging.basicConfig(level=logging.INFO,', 'format=_FORMAT,', 'stream=sys.stdout)', 'else:', '_suppress_print()', 'if', 'name', 'is', 'None:', ...
901,684
enuguru/artificial_intelligence_and_machine_
structfile.py
StructFile.read_pickle
read_pickle
Reads a pickled object from the wrapped file.
[ "Reads", "a", "pickled", "object", "from", "the", "wrapped", "file." ]
def read_pickle(self): return load_pickle(self.file)
['def', 'read_pickle(self):', 'return', 'load_pickle(self.file)']
162,488
xuannianz/SAPD
efficientnet.py
mb_conv_block
mb_conv_block
Mobile Inverted Residual Bottleneck.
[ "Mobile", "Inverted", "Residual", "Bottleneck." ]
def mb_conv_block(inputs, block_args, activation, drop_rate=None, prefix='', freeze_bn=False): has_se = block_args.se_ratio is not None and 0 < block_args.se_ratio <= 1 bn_axis = 3 if backend.image_data_format() == 'channels_last' else 1 Dropout = get_dropout(backend=backend, layers=layers, models=models, u...
['def', 'mb_conv_block(inputs,', 'block_args,', 'activation,', 'drop_rate=None,', "prefix='',", 'freeze_bn=False):', 'has_se', '=', 'block_args.se_ratio', 'is', 'not', 'None', 'and', '0', '<', 'block_args.se_ratio', '<=', '1', 'bn_axis', '=', '3', 'if', 'backend.image_data_format()', '==', "'channels_last'", 'else', '1...
845,372
suarez12138/AI-Reversi_IMP_TextDichotomy
test_memory.py
test_memory_integration
test_memory_integration
Simple test of memory lazy evaluation.
[ "Simple", "test", "of", "memory", "lazy", "evaluation." ]
def test_memory_integration(tmpdir): accumulator = list() def f(l): accumulator.append(1) return l check_identity_lazy(f, accumulator, tmpdir.strpath) for compress in (False, True): for mmap_mode in ('r', None): memory = Memory(location=tmpdir.strpath, verbose=10, mm...
['def', 'test_memory_integration(tmpdir):', 'accumulator', '=', 'list()', 'def', 'f(l):', 'accumulator.append(1)', 'return', 'l', 'check_identity_lazy(f,', 'accumulator,', 'tmpdir.strpath)', 'for', 'compress', 'in', '(False,', 'True):', 'for', 'mmap_mode', 'in', "('r',", 'None):', 'memory', '=', 'Memory(location=tmpdir...
95,975
enuguru/artificial_intelligence_and_machine_
models.py
PreparedRequest.prepare_cookies
prepare_cookies
Prepares the given HTTP cookie data.
[ "Prepares", "the", "given", "HTTP", "cookie", "data." ]
def prepare_cookies(self, cookies): if isinstance(cookies, cookielib.CookieJar): cookies = cookies else: cookies = cookiejar_from_dict(cookies) if 'cookie' not in self.headers: cookie_header = get_cookie_header(cookies, self) if cookie_header is not None: self.hea...
['def', 'prepare_cookies(self,', 'cookies):', 'if', 'isinstance(cookies,', 'cookielib.CookieJar):', 'cookies', '=', 'cookies', 'else:', 'cookies', '=', 'cookiejar_from_dict(cookies)', 'if', "'cookie'", 'not', 'in', 'self.headers:', 'cookie_header', '=', 'get_cookie_header(cookies,', 'self)', 'if', 'cookie_header', 'is'...
163,794
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
neural_gpu_trainer.py
get_best_beam
get_best_beam
Run beam_model, score beams, and return the best as target and in input.
[ "Run", "beam_model,", "score", "beams,", "and", "return", "the", "best", "as", "target", "and", "in", "input." ]
def get_best_beam(beam_model, sess, inp, target, batch_size, beam_size, bucket, history, p, test_mode=False): (_, output_logits, _, _) = beam_model.step(sess, inp, target, None, beam_size=FLAGS.beam_size) (new_targets, new_firsts, scores, new_inp) = ([], [], [], np.copy(inp)) for b in xrange(batch_size): ...
['def', 'get_best_beam(beam_model,', 'sess,', 'inp,', 'target,', 'batch_size,', 'beam_size,', 'bucket,', 'history,', 'p,', 'test_mode=False):', '(_,', 'output_logits,', '_,', '_)', '=', 'beam_model.step(sess,', 'inp,', 'target,', 'None,', 'beam_size=FLAGS.beam_size)', '(new_targets,', 'new_firsts,', 'scores,', 'new_inp...
50,216
ryu-ed/SpaceInvaders_Ros
python3.py
Python3Checker.visit_module
visit_module
Clear checker state after previous module.
[ "Clear", "checker", "state", "after", "previous", "module." ]
def visit_module(self, node): self._future_division = False self._future_absolute_import = False
['def', 'visit_module(self,', 'node):', 'self._future_division', '=', 'False', 'self._future_absolute_import', '=', 'False']
369,951
arnomoonens/yarll
async_knowledge_transfer.py
AKTThread.learn_Karpathy
learn_Karpathy
Learn using updates like in the Karpathy algorithm.
[ "Learn", "using", "updates", "like", "in", "the", "Karpathy", "algorithm." ]
def learn_Karpathy(self): iteration = self.start_at_iter while iteration < self.n_iter and (not self.master.stop_requested): iteration += 1 trajectory = self.task_runner.get_trajectory() reward = sum(trajectory['reward']) action_taken = trajectory['action'] discounted_epi...
['def', 'learn_Karpathy(self):', 'iteration', '=', 'self.start_at_iter', 'while', 'iteration', '<', 'self.n_iter', 'and', '(not', 'self.master.stop_requested):', 'iteration', '+=', '1', 'trajectory', '=', 'self.task_runner.get_trajectory()', 'reward', '=', "sum(trajectory['reward'])", 'action_taken', '=', "trajectory['...
374,735
googleapis/python-aiplatform
grpc_asyncio.py
VizierServiceGrpcAsyncIOTransport.create_channel
create_channel
Create and return a gRPC AsyncIO channel object.
[ "Create", "and", "return", "a", "gRPC", "AsyncIO", "channel", "object." ]
def create_channel(cls, host: str='aiplatform.googleapis.com', credentials: Optional[ga_credentials.Credentials]=None, credentials_file: Optional[str]=None, scopes: Optional[Sequence[str]]=None, quota_project_id: Optional[str]=None, **kwargs) -> aio.Channel: return grpc_helpers_async.create_channel(host, credential...
['def', 'create_channel(cls,', 'host:', "str='aiplatform.googleapis.com',", 'credentials:', 'Optional[ga_credentials.Credentials]=None,', 'credentials_file:', 'Optional[str]=None,', 'scopes:', 'Optional[Sequence[str]]=None,', 'quota_project_id:', 'Optional[str]=None,', '**kwargs)', '->', 'aio.Channel:', 'return', 'grpc...
814,345
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.skin_vert
skin_vert
vertex positions for all skin meshes (nskinvert x 3).
[ "vertex", "positions", "for", "all", "skin", "meshes", "(nskinvert", "x", "3)." ]
def skin_vert(self): return util.buf_to_npy(self._ptr.contents.skin_vert, (self.nskinvert, 3))
['def', 'skin_vert(self):', 'return', 'util.buf_to_npy(self._ptr.contents.skin_vert,', '(self.nskinvert,', '3))']
440,363
sek788432/Waymo-2D-Object-Detection
augment.py
AutoAugment.policy_simple
policy_simple
Same as `policy_v0`, except with custom ops removed.
[ "Same", "as", "`policy_v0`,", "except", "with", "custom", "ops", "removed." ]
def policy_simple(): policy = [[('Color', 0.4, 9), ('Equalize', 0.6, 3)], [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], [('Color', 0.2, 0), ('Equalize', 0.8, 8)], [('Equalize', 0.4, 8), ('SolarizeAdd', 0.8, 3)], [('Color', 0.6, 1), ('Equalize', 1.0, 2)], [('Color', 0.4,...
['def', 'policy_simple():', 'policy', '=', "[[('Color',", '0.4,', '9),', "('Equalize',", '0.6,', '3)],', "[('Solarize',", '0.8,', '3),', "('Equalize',", '0.4,', '7)],', "[('Solarize',", '0.4,', '2),', "('Solarize',", '0.6,', '2)],', "[('Color',", '0.2,', '0),', "('Equalize',", '0.8,', '8)],', "[('Equalize',", '0.4,', '...
973,706
zhang614/MicroGrid
__init__.py
get_default_fcompiler
get_default_fcompiler
Determine the default Fortran compiler to use for the given platform.
[ "Determine", "the", "default", "Fortran", "compiler", "to", "use", "for", "the", "given", "platform." ]
def get_default_fcompiler(osname=None, platform=None, requiref90=False, c_compiler=None): matching_compiler_types = available_fcompilers_for_platform(osname, platform) log.info("get_default_fcompiler: matching types: '%s'", matching_compiler_types) compiler_type = _find_existing_fcompiler(matching_compiler_...
['def', 'get_default_fcompiler(osname=None,', 'platform=None,', 'requiref90=False,', 'c_compiler=None):', 'matching_compiler_types', '=', 'available_fcompilers_for_platform(osname,', 'platform)', 'log.info("get_default_fcompiler:', 'matching', 'types:', '\'%s\'",', 'matching_compiler_types)', 'compiler_type', '=', '_fi...
667,343
stan-hua/CytoImageNet
clean_metadata.py
exists_meta
exists_meta
Return metadata dataframe if file exists.
[ "Return", "metadata", "dataframe", "if", "file", "exists." ]
def exists_meta(dir_name: str) -> Optional[pd.DataFrame]: try: return pd.read_csv(f'{annotations_dir}unclean/{dir_name}_metadata.csv') except: print('Does not exist!')
['def', 'exists_meta(dir_name:', 'str)', '->', 'Optional[pd.DataFrame]:', 'try:', 'return', "pd.read_csv(f'{annotations_dir}unclean/{dir_name}_metadata.csv')", 'except:', "print('Does", 'not', "exist!')"]
524,651
Kvatsx/Artificial-Intelligence-Assignments
datetime.py
datetime.combine
combine
Construct a datetime from a given date and a given time.
[ "Construct", "a", "datetime", "from", "a", "given", "date", "and", "a", "given", "time." ]
def combine(cls, date, time): if not isinstance(date, _date_class): raise TypeError('date argument must be a date instance') if not isinstance(time, _time_class): raise TypeError('time argument must be a time instance') return cls(date.year, date.month, date.day, time.hour, time.minute, time...
['def', 'combine(cls,', 'date,', 'time):', 'if', 'not', 'isinstance(date,', '_date_class):', 'raise', "TypeError('date", 'argument', 'must', 'be', 'a', 'date', "instance')", 'if', 'not', 'isinstance(time,', '_time_class):', 'raise', "TypeError('time", 'argument', 'must', 'be', 'a', 'time', "instance')", 'return', 'cls(...
36,646
Speedwagon13/CS-3600-Introduction-to--
ssl.py
get_default_verify_paths
get_default_verify_paths
Return paths to default cafile and capath.
[ "Return", "paths", "to", "default", "cafile", "and", "capath." ]
def get_default_verify_paths(): parts = _ssl.get_default_verify_paths() cafile = os.environ.get(parts[0], parts[1]) capath = os.environ.get(parts[2], parts[3]) return DefaultVerifyPaths(cafile if os.path.isfile(cafile) else None, capath if os.path.isdir(capath) else None, *parts)
['def', 'get_default_verify_paths():', 'parts', '=', '_ssl.get_default_verify_paths()', 'cafile', '=', 'os.environ.get(parts[0],', 'parts[1])', 'capath', '=', 'os.environ.get(parts[2],', 'parts[3])', 'return', 'DefaultVerifyPaths(cafile', 'if', 'os.path.isfile(cafile)', 'else', 'None,', 'capath', 'if', 'os.path.isdir(c...
139,952
jwwangchn/NWD
base_roi_extractor.py
BaseRoIExtractor.build_roi_layers
build_roi_layers
Build RoI operator to extract feature from each level feature map.
[ "Build", "RoI", "operator", "to", "extract", "feature", "from", "each", "level", "feature", "map." ]
def build_roi_layers(self, layer_cfg, featmap_strides): cfg = layer_cfg.copy() layer_type = cfg.pop('type') assert hasattr(ops, layer_type) layer_cls = getattr(ops, layer_type) roi_layers = nn.ModuleList([layer_cls(spatial_scale=1 / s, **cfg) for s in featmap_strides]) return roi_layers
['def', 'build_roi_layers(self,', 'layer_cfg,', 'featmap_strides):', 'cfg', '=', 'layer_cfg.copy()', 'layer_type', '=', "cfg.pop('type')", 'assert', 'hasattr(ops,', 'layer_type)', 'layer_cls', '=', 'getattr(ops,', 'layer_type)', 'roi_layers', '=', 'nn.ModuleList([layer_cls(spatial_scale=1', '/', 's,', '**cfg)', 'for', ...
725,038
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
videos_to_tfrecords.py
PrintSequencesInfo
PrintSequencesInfo
Print information about sequences and return the total number of frames.
[ "Print", "information", "about", "sequences", "and", "return", "the", "total", "number", "of", "frames." ]
def PrintSequencesInfo(sequences, prefix): tf.logging.info('') tf.logging.info(prefix) num_frames = 0 for sequence in sequences: shard_str = '' if sequence['shard']: shard_str = ' (sharding)' tf.logging.info('frames [%d, %d[\t(%d frames * %d views)%s\t%s' % (sequence[...
['def', 'PrintSequencesInfo(sequences,', 'prefix):', "tf.logging.info('')", 'tf.logging.info(prefix)', 'num_frames', '=', '0', 'for', 'sequence', 'in', 'sequences:', 'shard_str', '=', "''", 'if', "sequence['shard']:", 'shard_str', '=', "'", "(sharding)'", "tf.logging.info('frames", '[%d,', '%d[\\t(%d', 'frames', '*', '...
29,570
openai/gym
human_rendering.py
HumanRendering.close
close
Close the rendering window.
[ "Close", "the", "rendering", "window." ]
def close(self): super().close() if self.window is not None: import pygame pygame.display.quit() pygame.quit()
['def', 'close(self):', 'super().close()', 'if', 'self.window', 'is', 'not', 'None:', 'import', 'pygame', 'pygame.display.quit()', 'pygame.quit()']
234,300
eddiecorrigall/Vision
non_maximum_suppression.py
non_maximum_suppression
non_maximum_suppression
Performs non-maximum suppression, run on GPU or CPU according to boxes's device.
[ "Performs", "non-maximum", "suppression,", "run", "on", "GPU", "or", "CPU", "according", "to", "boxes's", "device." ]
def non_maximum_suppression(boxes, scores, iou_threshold: float) -> torch.Tensor: return nms_support(boxes, scores, iou_threshold)
['def', 'non_maximum_suppression(boxes,', 'scores,', 'iou_threshold:', 'float)', '->', 'torch.Tensor:', 'return', 'nms_support(boxes,', 'scores,', 'iou_threshold)']
942,515
anthonyli358/FlapPyBird-Reinforcement-Learning
flappy_rl.py
getHitmask
getHitmask
Returns a hitmask using an image's alpha.
[ "Returns", "a", "hitmask", "using", "an", "image's", "alpha." ]
def getHitmask(image): mask = [] for x in xrange(image.get_width()): mask.append([]) for y in xrange(image.get_height()): mask[x].append(bool(image.get_at((x, y))[3])) return mask
['def', 'getHitmask(image):', 'mask', '=', '[]', 'for', 'x', 'in', 'xrange(image.get_width()):', 'mask.append([])', 'for', 'y', 'in', 'xrange(image.get_height()):', 'mask[x].append(bool(image.get_at((x,', 'y))[3]))', 'return', 'mask']
584,884
weimin17/Object-Detection_HelmetDetection
model_lib.py
create_train_and_eval_specs
create_train_and_eval_specs
Creates a `TrainSpec` and `EvalSpec`s.
[ "Creates", "a", "`TrainSpec`", "and", "`EvalSpec`s." ]
def create_train_and_eval_specs(train_input_fn, eval_input_fn, eval_on_train_input_fn, predict_input_fn, train_steps, eval_steps, eval_on_train_data=False, eval_on_train_steps=None, final_exporter_name='Servo', eval_spec_name='eval'): exporter = tf.estimator.FinalExporter(name=final_exporter_name, serving_input_rec...
['def', 'create_train_and_eval_specs(train_input_fn,', 'eval_input_fn,', 'eval_on_train_input_fn,', 'predict_input_fn,', 'train_steps,', 'eval_steps,', 'eval_on_train_data=False,', 'eval_on_train_steps=None,', "final_exporter_name='Servo',", "eval_spec_name='eval'):", 'exporter', '=', 'tf.estimator.FinalExporter(name=f...
751,521
nicknochnack/RealTimeSignLanguageTFJS
pix2pix.py
upsample
upsample
Upsamples the given inputs.
[ "Upsamples", "the", "given", "inputs." ]
def upsample(net, num_outputs, kernel_size, method='nn_upsample_conv'): net_shape = tf.shape(input=net) height = net_shape[1] width = net_shape[2] if method == 'nn_upsample_conv': net = tf.image.resize(net, [kernel_size[0] * height, kernel_size[1] * width], method=tf.image.ResizeMethod.NEAREST_N...
['def', 'upsample(net,', 'num_outputs,', 'kernel_size,', "method='nn_upsample_conv'):", 'net_shape', '=', 'tf.shape(input=net)', 'height', '=', 'net_shape[1]', 'width', '=', 'net_shape[2]', 'if', 'method', '==', "'nn_upsample_conv':", 'net', '=', 'tf.image.resize(net,', '[kernel_size[0]', '*', 'height,', 'kernel_size[1...
831,272
Ruturaj123/Flowchart-Detection
tensor_util.py
TensorShapeProtoToList
TensorShapeProtoToList
Convert a TensorShape to a list.
[ "Convert", "a", "TensorShape", "to", "a", "list." ]
def TensorShapeProtoToList(shape): return [dim.size for dim in shape.dim]
['def', 'TensorShapeProtoToList(shape):', 'return', '[dim.size', 'for', 'dim', 'in', 'shape.dim]']
605,533
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
Pmf.Probs
Probs
Gets probabilities for a sequence of values.
[ "Gets", "probabilities", "for", "a", "sequence", "of", "values." ]
def Probs(self, xs): return [self.Prob(x) for x in xs]
['def', 'Probs(self,', 'xs):', 'return', '[self.Prob(x)', 'for', 'x', 'in', 'xs]']
19,582
google-research/batch-ppo
utility.py
define_batch_env
define_batch_env
Create environments and apply all desired wrappers.
[ "Create", "environments", "and", "apply", "all", "desired", "wrappers." ]
def define_batch_env(constructor, num_agents, env_processes): with tf.variable_scope('environments'): if env_processes: envs = [tools.wrappers.ExternalProcess(constructor) for _ in range(num_agents)] else: envs = [constructor() for _ in range(num_agents)] batch_env = ...
['def', 'define_batch_env(constructor,', 'num_agents,', 'env_processes):', 'with', "tf.variable_scope('environments'):", 'if', 'env_processes:', 'envs', '=', '[tools.wrappers.ExternalProcess(constructor)', 'for', '_', 'in', 'range(num_agents)]', 'else:', 'envs', '=', '[constructor()', 'for', '_', 'in', 'range(num_agent...
95,024
weimin17/Object-Detection_HelmetDetection
losses.py
cross_entropy_loss_matrix
cross_entropy_loss_matrix
Computes the cross entropy loss for G.
[ "Computes", "the", "cross", "entropy", "loss", "for", "G." ]
def cross_entropy_loss_matrix(gen_labels, gen_logits): cross_entropy_loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=gen_labels, logits=gen_logits) return cross_entropy_loss
['def', 'cross_entropy_loss_matrix(gen_labels,', 'gen_logits):', 'cross_entropy_loss', '=', 'tf.nn.sparse_softmax_cross_entropy_with_logits(labels=gen_labels,', 'logits=gen_logits)', 'return', 'cross_entropy_loss']
763,624
evanbrumley/django-report-tools
gviz_api.py
DataTable.columns
columns
Returns the parsed table description.
[ "Returns", "the", "parsed", "table", "description." ]
def columns(self): return self.__columns
['def', 'columns(self):', 'return', 'self.__columns']
164,796
arshpreetsingh/quantopian-machinelearning
wildcard.py
list_namespace
list_namespace
Return dictionary of all objects in a namespace dictionary that match type_pattern and filter.
[ "Return", "dictionary", "of", "all", "objects", "in", "a", "namespace", "dictionary", "that", "match", "type_pattern", "and", "filter." ]
def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): pattern_list = filter.split('.') if len(pattern_list) == 1: return filter_ns(namespace, name_pattern=pattern_list[0], type_pattern=type_pattern, ignore_case=ignore_case, show_all=show_all) else: filtered ...
['def', 'list_namespace(namespace,', 'type_pattern,', 'filter,', 'ignore_case=False,', 'show_all=False):', 'pattern_list', '=', "filter.split('.')", 'if', 'len(pattern_list)', '==', '1:', 'return', 'filter_ns(namespace,', 'name_pattern=pattern_list[0],', 'type_pattern=type_pattern,', 'ignore_case=ignore_case,', 'show_a...
887,137
wzpscott/SegDistill
point_head.py
PointHead.init_weights
init_weights
Initialize weights of classification layer.
[ "Initialize", "weights", "of", "classification", "layer." ]
def init_weights(self): normal_init(self.fc_seg, std=0.001)
['def', 'init_weights(self):', 'normal_init(self.fc_seg,', 'std=0.001)']
842,134
openai/gym
async_vector_env.py
AsyncVectorEnv.close_extras
close_extras
Close the environments & clean up the extra resources (processes and pipes).
[ "Close", "the", "environments", "&", "clean", "up", "the", "extra", "resources", "(processes", "and", "pipes)." ]
def close_extras(self, timeout: Optional[Union[int, float]]=None, terminate: bool=False): timeout = 0 if terminate else timeout try: if self._state != AsyncState.DEFAULT: logger.warn(f'Calling `close` while waiting for a pending call to `{self._state.value}` to complete.') functi...
['def', 'close_extras(self,', 'timeout:', 'Optional[Union[int,', 'float]]=None,', 'terminate:', 'bool=False):', 'timeout', '=', '0', 'if', 'terminate', 'else', 'timeout', 'try:', 'if', 'self._state', '!=', 'AsyncState.DEFAULT:', "logger.warn(f'Calling", '`close`', 'while', 'waiting', 'for', 'a', 'pending', 'call', 'to'...
234,253
Rock-100/MonoDet
mask_head.py
BaseMaskRCNNHead.layers
layers
Neural network layers that makes predictions from input features.
[ "Neural", "network", "layers", "that", "makes", "predictions", "from", "input", "features." ]
def layers(self, x): raise NotImplementedError
['def', 'layers(self,', 'x):', 'raise', 'NotImplementedError']
654,962
ldkong1205/LaserMix
monoflex_bbox_coder.py
MonoFlexCoder.decode_direct_depth
decode_direct_depth
Transform depth offset to directly regressed depth.
[ "Transform", "depth", "offset", "to", "directly", "regressed", "depth." ]
def decode_direct_depth(self, depth_offsets: Tensor) -> Tensor: if self.depth_mode == 'exp': direct_depth = depth_offsets.exp() elif self.depth_mode == 'linear': base_depth = depth_offsets.new_tensor(self.base_depth) direct_depth = depth_offsets * base_depth[1] + base_depth[0] elif s...
['def', 'decode_direct_depth(self,', 'depth_offsets:', 'Tensor)', '->', 'Tensor:', 'if', 'self.depth_mode', '==', "'exp':", 'direct_depth', '=', 'depth_offsets.exp()', 'elif', 'self.depth_mode', '==', "'linear':", 'base_depth', '=', 'depth_offsets.new_tensor(self.base_depth)', 'direct_depth', '=', 'depth_offsets', '*',...
624,286
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
Expression.acceptSuper
acceptSuper
Accept and process a super expression.
[ "Accept", "and", "process", "a", "super", "expression." ]
def acceptSuper(self, node, memo): cls = self.parents(lambda c: c.isClass).next() self.right = self.factory.expr(fs='super({name}, self)'.format(name=cls.name))
['def', 'acceptSuper(self,', 'node,', 'memo):', 'cls', '=', 'self.parents(lambda', 'c:', 'c.isClass).next()', 'self.right', '=', "self.factory.expr(fs='super({name},", "self)'.format(name=cls.name))"]
11,114
zhang614/MicroGrid
_policybase.py
Policy.header_store_parse
header_store_parse
Given the header name and the value provided by the application program, return the (name, value) that should be stored in the model.
[ "Given", "the", "header", "name", "and", "the", "value", "provided", "by", "the", "application", "program,", "return", "the", "(name,", "value)", "that", "should", "be", "stored", "in", "the", "model." ]
def header_store_parse(self, name, value): raise NotImplementedError
['def', 'header_store_parse(self,', 'name,', 'value):', 'raise', 'NotImplementedError']
636,224
jimtin/Stock_Comparison
test_utils.py
TestArrayEqual.test_generic_rank3
test_generic_rank3
Test rank 3 array for all dtypes.
[ "Test", "rank", "3", "array", "for", "all", "dtypes." ]
def test_generic_rank3(self): def foo(t): a = np.empty((4, 2, 3), t) a.fill(1) b = a.copy() c = a.copy() c.fill(0) self._test_equal(a, b) self._test_not_equal(c, b) for t in '?bhilqpBHILQPfdgFDG': foo(t) for t in ['S1', 'U1']: foo(t)
['def', 'test_generic_rank3(self):', 'def', 'foo(t):', 'a', '=', 'np.empty((4,', '2,', '3),', 't)', 'a.fill(1)', 'b', '=', 'a.copy()', 'c', '=', 'a.copy()', 'c.fill(0)', 'self._test_equal(a,', 'b)', 'self._test_not_equal(c,', 'b)', 'for', 't', 'in', "'?bhilqpBHILQPfdgFDG':", 'foo(t)', 'for', 't', 'in', "['S1',", "'U1']...
387,225
devashish-patel/webcam-motion-detector
inprocess.py
QtInProcessChannel.call_handlers_later
call_handlers_later
Call the message handlers later.
[ "Call", "the", "message", "handlers", "later." ]
def call_handlers_later(self, *args, **kwds): do_later = lambda : self.call_handlers(*args, **kwds) QtCore.QTimer.singleShot(0, do_later)
['def', 'call_handlers_later(self,', '*args,', '**kwds):', 'do_later', '=', 'lambda', ':', 'self.call_handlers(*args,', '**kwds)', 'QtCore.QTimer.singleShot(0,', 'do_later)']
984,436
georghess/voxel-mae
nuscenes_converter.py
post_process_coords
post_process_coords
Get the intersection of the convex hull of the reprojected bbox corners and the image canvas, return None if no intersection.
[ "Get", "the", "intersection", "of", "the", "convex", "hull", "of", "the", "reprojected", "bbox", "corners", "and", "the", "image", "canvas,", "return", "None", "if", "no", "intersection." ]
def post_process_coords(corner_coords: List, imsize: Tuple[int, int]=(1600, 900)) -> Union[Tuple[float, float, float, float], None]: polygon_from_2d_box = MultiPoint(corner_coords).convex_hull img_canvas = box(0, 0, imsize[0], imsize[1]) if polygon_from_2d_box.intersects(img_canvas): img_intersectio...
['def', 'post_process_coords(corner_coords:', 'List,', 'imsize:', 'Tuple[int,', 'int]=(1600,', '900))', '->', 'Union[Tuple[float,', 'float,', 'float,', 'float],', 'None]:', 'polygon_from_2d_box', '=', 'MultiPoint(corner_coords).convex_hull', 'img_canvas', '=', 'box(0,', '0,', 'imsize[0],', 'imsize[1])', 'if', 'polygon_...
380,824
akshitsarin/Udacity-AI-Nanodegree
search.py
depth_first_graph_search
depth_first_graph_search
Search the deepest nodes in the search tree first.
[ "Search", "the", "deepest", "nodes", "in", "the", "search", "tree", "first." ]
def depth_first_graph_search(problem): return graph_search(problem, Stack())
['def', 'depth_first_graph_search(problem):', 'return', 'graph_search(problem,', 'Stack())']
427,418
cuiziteng/ICCV_MAET
yolact.py
YOLACT.init_segm_mask_weights
init_segm_mask_weights
Initialize weights of the YOLACT semg head and YOLACT mask head.
[ "Initialize", "weights", "of", "the", "YOLACT", "semg", "head", "and", "YOLACT", "mask", "head." ]
def init_segm_mask_weights(self): self.segm_head.init_weights() self.mask_head.init_weights()
['def', 'init_segm_mask_weights(self):', 'self.segm_head.init_weights()', 'self.mask_head.init_weights()']
228,718
loicmarie/hands-detection
data_utils.py
sort_vocab_by_frequency
sort_vocab_by_frequency
Sorts vocab_freq_map by count.
[ "Sorts", "vocab_freq_map", "by", "count." ]
def sort_vocab_by_frequency(vocab_freq_map): return sorted(vocab_freq_map.items(), key=operator.itemgetter(1), reverse=True)
['def', 'sort_vocab_by_frequency(vocab_freq_map):', 'return', 'sorted(vocab_freq_map.items(),', 'key=operator.itemgetter(1),', 'reverse=True)']
574,401
enuguru/artificial_intelligence_and_machine_
scoring.py
WeightingModel.idf
idf
Returns the inverse document frequency of the given term.
[ "Returns", "the", "inverse", "document", "frequency", "of", "the", "given", "term." ]
def idf(self, searcher, fieldname, text): parent = searcher.get_parent() n = parent.doc_frequency(fieldname, text) dc = parent.doc_count_all() return log(dc / (n + 1)) + 1
['def', 'idf(self,', 'searcher,', 'fieldname,', 'text):', 'parent', '=', 'searcher.get_parent()', 'n', '=', 'parent.doc_frequency(fieldname,', 'text)', 'dc', '=', 'parent.doc_count_all()', 'return', 'log(dc', '/', '(n', '+', '1))', '+', '1']
162,189
scikit-learn/scikit-learn
plot_lasso_lars_ic.py
zou_et_al_criterion_rescaling
zou_et_al_criterion_rescaling
Rescale the information criterion to follow the definition of Zou et al.
[ "Rescale", "the", "information", "criterion", "to", "follow", "the", "definition", "of", "Zou", "et", "al." ]
def zou_et_al_criterion_rescaling(criterion, n_samples, noise_variance): return criterion - n_samples * np.log(2 * np.pi * noise_variance) - n_samples
['def', 'zou_et_al_criterion_rescaling(criterion,', 'n_samples,', 'noise_variance):', 'return', 'criterion', '-', 'n_samples', '*', 'np.log(2', '*', 'np.pi', '*', 'noise_variance)', '-', 'n_samples']
848,184
PaddlePaddle/PaddleSpeech
transformer.py
TransformerLM.forward
forward
Compute LM loss value from buffer sequences.
[ "Compute", "LM", "loss", "value", "from", "buffer", "sequences." ]
def forward(self, x: paddle.Tensor, t: paddle.Tensor) -> Tuple[paddle.Tensor, paddle.Tensor, paddle.Tensor]: batch_size = paddle.shape(x)[0] xm = x != 0 xlen = xm.sum(axis=1) if self.embed_drop is not None: emb = self.embed_drop(self.embed(x)) else: emb = self.embed(x) (h, _) = s...
['def', 'forward(self,', 'x:', 'paddle.Tensor,', 't:', 'paddle.Tensor)', '->', 'Tuple[paddle.Tensor,', 'paddle.Tensor,', 'paddle.Tensor]:', 'batch_size', '=', 'paddle.shape(x)[0]', 'xm', '=', 'x', '!=', '0', 'xlen', '=', 'xm.sum(axis=1)', 'if', 'self.embed_drop', 'is', 'not', 'None:', 'emb', '=', 'self.embed_drop(self....
276,819
jamesloyys/Real-Time-Object-Detection
variables_helper.py
freeze_gradients_matching_regex
freeze_gradients_matching_regex
Freeze gradients whose variable names match a regular expression.
[ "Freeze", "gradients", "whose", "variable", "names", "match", "a", "regular", "expression." ]
def freeze_gradients_matching_regex(grads_and_vars, regex_list): variables = [pair[1] for pair in grads_and_vars] matching_vars = filter_variables(variables, regex_list, invert=True) kept_grads_and_vars = [pair for pair in grads_and_vars if pair[1] not in matching_vars] for var in matching_vars: ...
['def', 'freeze_gradients_matching_regex(grads_and_vars,', 'regex_list):', 'variables', '=', '[pair[1]', 'for', 'pair', 'in', 'grads_and_vars]', 'matching_vars', '=', 'filter_variables(variables,', 'regex_list,', 'invert=True)', 'kept_grads_and_vars', '=', '[pair', 'for', 'pair', 'in', 'grads_and_vars', 'if', 'pair[1]'...
850,063
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
traceback.py
clear_frames
clear_frames
Clear all references to local variables in the frames of a traceback.
[ "Clear", "all", "references", "to", "local", "variables", "in", "the", "frames", "of", "a", "traceback." ]
def clear_frames(tb): while tb is not None: try: tb.tb_frame.clear() except RuntimeError: pass tb = tb.tb_next
['def', 'clear_frames(tb):', 'while', 'tb', 'is', 'not', 'None:', 'try:', 'tb.tb_frame.clear()', 'except', 'RuntimeError:', 'pass', 'tb', '=', 'tb.tb_next']
429,747
liujiboy/ComputerVision
homography.py
normalize
normalize
Normalize a collection of points in homogeneous coordinates so that last row = 1.
[ "Normalize", "a", "collection", "of", "points", "in", "homogeneous", "coordinates", "so", "that", "last", "row", "=", "1." ]
def normalize(points): for row in points: row /= points[-1] return points
['def', 'normalize(points):', 'for', 'row', 'in', 'points:', 'row', '/=', 'points[-1]', 'return', 'points']
471,281
rudranil723/mini-main
patheffects.py
Stroke.draw_path
draw_path
Draw the path with updated gc.
[ "Draw", "the", "path", "with", "updated", "gc." ]
def draw_path(self, renderer, gc, tpath, affine, rgbFace): gc0 = renderer.new_gc() gc0.copy_properties(gc) gc0 = self._update_gc(gc0, self._gc) renderer.draw_path(gc0, tpath, affine + self._offset_transform(renderer), rgbFace) gc0.restore()
['def', 'draw_path(self,', 'renderer,', 'gc,', 'tpath,', 'affine,', 'rgbFace):', 'gc0', '=', 'renderer.new_gc()', 'gc0.copy_properties(gc)', 'gc0', '=', 'self._update_gc(gc0,', 'self._gc)', 'renderer.draw_path(gc0,', 'tpath,', 'affine', '+', 'self._offset_transform(renderer),', 'rgbFace)', 'gc0.restore()']
319,575
apeterswu/RL4NMT
transformer.py
transformer_base_single_gpu
transformer_base_single_gpu
HParams for transformer base model for single gpu.
[ "HParams", "for", "transformer", "base", "model", "for", "single", "gpu." ]
def transformer_base_single_gpu(): hparams = transformer_base() hparams.batch_size = 2048 hparams.learning_rate_warmup_steps = 16000 return hparams
['def', 'transformer_base_single_gpu():', 'hparams', '=', 'transformer_base()', 'hparams.batch_size', '=', '2048', 'hparams.learning_rate_warmup_steps', '=', '16000', 'return', 'hparams']
331,180
arshpreetsingh/quantopian-machinelearning
utils.py
within_delta
within_delta
Useful for comparing two datetimes that may a negilible difference to be considered equal.
[ "Useful", "for", "comparing", "two", "datetimes", "that", "may", "a", "negilible", "difference", "to", "be", "considered", "equal." ]
def within_delta(dt1, dt2, delta): delta = abs(delta) difference = dt1 - dt2 return -delta <= difference <= delta
['def', 'within_delta(dt1,', 'dt2,', 'delta):', 'delta', '=', 'abs(delta)', 'difference', '=', 'dt1', '-', 'dt2', 'return', '-delta', '<=', 'difference', '<=', 'delta']
816,718
matsu0228/nlp-jp
connection.py
MWSConnection.list_recommendations_by_next_token
list_recommendations_by_next_token
Returns the next page of recommendations using the NextToken parameter.
[ "Returns", "the", "next", "page", "of", "recommendations", "using", "the", "NextToken", "parameter." ]
def list_recommendations_by_next_token(self, request, response, **kw): return self._post_request(request, kw, response)
['def', 'list_recommendations_by_next_token(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)']
784,986
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
model.py
get_embedder
get_embedder
Returns an embedder based on config.
[ "Returns", "an", "embedder", "based", "on", "config." ]
def get_embedder(embedder_strategy, config, images, is_training, reuse=False, l2_normalize_embedding=True): if embedder_strategy == 'inception_baseline': pretrained_ckpt = config.inception_conv_ss_fc.pretrained_checkpoint return InceptionBaselineEmbedder(images, pretrained_ckpt, config.random_projec...
['def', 'get_embedder(embedder_strategy,', 'config,', 'images,', 'is_training,', 'reuse=False,', 'l2_normalize_embedding=True):', 'if', 'embedder_strategy', '==', "'inception_baseline':", 'pretrained_ckpt', '=', 'config.inception_conv_ss_fc.pretrained_checkpoint', 'return', 'InceptionBaselineEmbedder(images,', 'pretrai...
112,151
JesperChristensen89/object_detection_benchmarking
matcher.py
Match.num_unmatched_columns
num_unmatched_columns
Returns number (int32 scalar tensor) of unmatched columns.
[ "Returns", "number", "(int32", "scalar", "tensor)", "of", "unmatched", "columns." ]
def num_unmatched_columns(self): return tf.size(self.unmatched_column_indices())
['def', 'num_unmatched_columns(self):', 'return', 'tf.size(self.unmatched_column_indices())']
794,295
lijiancheng0614/tensorflow_object_detection
test_utils_test.py
TestUtilsTest.test_diagonal_gradient_image
test_diagonal_gradient_image
Tests if a good pyramid image is created.
[ "Tests", "if", "a", "good", "pyramid", "image", "is", "created." ]
def test_diagonal_gradient_image(self): pyramid_image = test_utils.create_diagonal_gradient_image(3, 4, 2) expected_first_channel = np.array([[3, 2, 1, 0], [4, 3, 2, 1], [5, 4, 3, 2]], dtype=np.float32) self.assertAllEqual(np.squeeze(pyramid_image[:, :, 0]), expected_first_channel) expected_image = np.a...
['def', 'test_diagonal_gradient_image(self):', 'pyramid_image', '=', 'test_utils.create_diagonal_gradient_image(3,', '4,', '2)', 'expected_first_channel', '=', 'np.array([[3,', '2,', '1,', '0],', '[4,', '3,', '2,', '1],', '[5,', '4,', '3,', '2]],', 'dtype=np.float32)', 'self.assertAllEqual(np.squeeze(pyramid_image[:,',...
922,834
weimin17/Object-Detection_HelmetDetection
hooks_helper.py
get_logging_metric_hook
get_logging_metric_hook
Function to get LoggingMetricHook.
[ "Function", "to", "get", "LoggingMetricHook." ]
def get_logging_metric_hook(tensors_to_log=None, every_n_secs=600, **kwargs): if tensors_to_log is None: tensors_to_log = _TENSORS_TO_LOG return metric_hook.LoggingMetricHook(tensors=tensors_to_log, metric_logger=logger.get_benchmark_logger(), every_n_secs=every_n_secs)
['def', 'get_logging_metric_hook(tensors_to_log=None,', 'every_n_secs=600,', '**kwargs):', 'if', 'tensors_to_log', 'is', 'None:', 'tensors_to_log', '=', '_TENSORS_TO_LOG', 'return', 'metric_hook.LoggingMetricHook(tensors=tensors_to_log,', 'metric_logger=logger.get_benchmark_logger(),', 'every_n_secs=every_n_secs)']
761,305
gunthercox/ChatterBot
api.py
ModelI.logprob
logprob
Evaluate the (negative) log probability of this word in this context.
[ "Evaluate", "the", "(negative)", "log", "probability", "of", "this", "word", "in", "this", "context." ]
def logprob(self, word, context): raise NotImplementedError()
['def', 'logprob(self,', 'word,', 'context):', 'raise', 'NotImplementedError()']
530,271
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
tree.py
BaseTree.hasAncestor
hasAncestor
Walk upwards looking for ancestor with this token type.
[ "Walk", "upwards", "looking", "for", "ancestor", "with", "this", "token", "type." ]
def hasAncestor(self, ttype): return self.getAncestor(ttype) is not None
['def', 'hasAncestor(self,', 'ttype):', 'return', 'self.getAncestor(ttype)', 'is', 'not', 'None']
10,126
cheng052/BRNet
box_np_ops.py
rotation_3d_in_axis
rotation_3d_in_axis
Rotate points in specific axis.
[ "Rotate", "points", "in", "specific", "axis." ]
def rotation_3d_in_axis(points, angles, axis=0): rot_sin = np.sin(angles) rot_cos = np.cos(angles) ones = np.ones_like(rot_cos) zeros = np.zeros_like(rot_cos) if axis == 1: rot_mat_T = np.stack([[rot_cos, zeros, -rot_sin], [zeros, ones, zeros], [rot_sin, zeros, rot_cos]]) elif axis == 2 ...
['def', 'rotation_3d_in_axis(points,', 'angles,', 'axis=0):', 'rot_sin', '=', 'np.sin(angles)', 'rot_cos', '=', 'np.cos(angles)', 'ones', '=', 'np.ones_like(rot_cos)', 'zeros', '=', 'np.zeros_like(rot_cos)', 'if', 'axis', '==', '1:', 'rot_mat_T', '=', 'np.stack([[rot_cos,', 'zeros,', '-rot_sin],', '[zeros,', 'ones,', '...
409,618
mlwithtf/mlwithtf
prediction_service_pb2.py
BetaPredictionServiceServicer.Predict
Predict
Predict -- provides access to loaded TensorFlow model.
[ "Predict", "--", "provides", "access", "to", "loaded", "TensorFlow", "model." ]
def Predict(self, request, context): context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)
['def', 'Predict(self,', 'request,', 'context):', 'context.code(beta_interfaces.StatusCode.UNIMPLEMENTED)']
631,163
dongliangcao/Unsupervised-Learning-of-Robust-Spectral-Shape-Matching
base_model.py
BaseModel.update_model_per_epoch
update_model_per_epoch
Update model per epoch.
[ "Update", "model", "per", "epoch." ]
def update_model_per_epoch(self): for name in self.schedulers: if isinstance(self.schedulers[name], (optim.lr_scheduler.StepLR, optim.lr_scheduler.MultiStepLR, MultiStepRestartLR, optim.lr_scheduler.ExponentialLR, optim.lr_scheduler.CosineAnnealingLR, optim.lr_scheduler.CosineAnnealingWarmRestarts)): ...
['def', 'update_model_per_epoch(self):', 'for', 'name', 'in', 'self.schedulers:', 'if', 'isinstance(self.schedulers[name],', '(optim.lr_scheduler.StepLR,', 'optim.lr_scheduler.MultiStepLR,', 'MultiStepRestartLR,', 'optim.lr_scheduler.ExponentialLR,', 'optim.lr_scheduler.CosineAnnealingLR,', 'optim.lr_scheduler.CosineAn...
353,557
intel/neural-compressor
ni.py
NeuralInsights.add_workload
add_workload
Add workload to Neural Insights.
[ "Add", "workload", "to", "Neural", "Insights." ]
def add_workload(self, workload_location: str, model_path: str, workload_mode: WorkloadModes, workload_name: str, model_summary_file: Optional[str]) -> str: if workload_mode == WorkloadModes.QUANTIZATION: workload = QuantizationWorkload() else: workload = Workload() workload.workload_name = ...
['def', 'add_workload(self,', 'workload_location:', 'str,', 'model_path:', 'str,', 'workload_mode:', 'WorkloadModes,', 'workload_name:', 'str,', 'model_summary_file:', 'Optional[str])', '->', 'str:', 'if', 'workload_mode', '==', 'WorkloadModes.QUANTIZATION:', 'workload', '=', 'QuantizationWorkload()', 'else:', 'workloa...
721,524
TonyLianLong/VAI-ReinforcementLearning
task.py
Task.should_terminate_episode
should_terminate_episode
Determines whether the episode should terminate given the physics state.
[ "Determines", "whether", "the", "episode", "should", "terminate", "given", "the", "physics", "state." ]
def should_terminate_episode(self, physics): return False
['def', 'should_terminate_episode(self,', 'physics):', 'return', 'False']
439,908
BERYLSHEEP/LayoutActionProject
message_passing_module.py
GraphPropLayer.forward
forward
Run one propagation step.
[ "Run", "one", "propagation", "step." ]
def forward(self, node_states, from_idx, to_idx, edge_features=None, node_features=None): aggregated_messages = self._compute_aggregated_messages(node_states, from_idx, to_idx, edge_features=edge_features) list_aggregated_msgs = [aggregated_messages] return self._compute_node_update(node_states, [aggregated...
['def', 'forward(self,', 'node_states,', 'from_idx,', 'to_idx,', 'edge_features=None,', 'node_features=None):', 'aggregated_messages', '=', 'self._compute_aggregated_messages(node_states,', 'from_idx,', 'to_idx,', 'edge_features=edge_features)', 'list_aggregated_msgs', '=', '[aggregated_messages]', 'return', 'self._com...
624,696
Farama-Foundation/Gymnasium
rendering.py
RenderCollectionV0.render
render
Returns the collection of frames and, if pop_frames = True, clears it.
[ "Returns", "the", "collection", "of", "frames", "and,", "if", "pop_frames", "=", "True,", "clears", "it." ]
def render(self) -> list[RenderFrame]: frames = self.frame_list if self.pop_frames: self.frame_list = [] return frames
['def', 'render(self)', '->', 'list[RenderFrame]:', 'frames', '=', 'self.frame_list', 'if', 'self.pop_frames:', 'self.frame_list', '=', '[]', 'return', 'frames']
573,181
fudan-zvg/SETR
deformable_detr_head.py
DeformableDETRHead.init_weights
init_weights
Initialize weights of the DeformDETR head.
[ "Initialize", "weights", "of", "the", "DeformDETR", "head." ]
def init_weights(self): self.transformer.init_weights() if self.loss_cls.use_sigmoid: bias_init = bias_init_with_prob(0.01) for m in self.cls_branches: nn.init.constant_(m.bias, bias_init) for m in self.reg_branches: constant_init(m[-1], 0, bias=0) nn.init.constant_(s...
['def', 'init_weights(self):', 'self.transformer.init_weights()', 'if', 'self.loss_cls.use_sigmoid:', 'bias_init', '=', 'bias_init_with_prob(0.01)', 'for', 'm', 'in', 'self.cls_branches:', 'nn.init.constant_(m.bias,', 'bias_init)', 'for', 'm', 'in', 'self.reg_branches:', 'constant_init(m[-1],', '0,', 'bias=0)', 'nn.ini...
898,117
jsyoon0823/MRNN
model_utils.py
process_batch_input_for_rnn
process_batch_input_for_rnn
Convert tensor for rnn training.
[ "Convert", "tensor", "for", "rnn", "training." ]
def process_batch_input_for_rnn(batch_input): batch_input_ = tf.transpose(batch_input, perm=[2, 0, 1]) transformed_input = tf.transpose(batch_input_) return transformed_input
['def', 'process_batch_input_for_rnn(batch_input):', 'batch_input_', '=', 'tf.transpose(batch_input,', 'perm=[2,', '0,', '1])', 'transformed_input', '=', 'tf.transpose(batch_input_)', 'return', 'transformed_input']
241,693
hgkahng/WaPIRL
classification.py
Classification.run
run
Train, evaluate and optionally test.
[ "Train,", "evaluate", "and", "optionally", "test." ]
def run(self, train_set, valid_set, epochs: int, batch_size: int, num_workers: int=0, **kwargs): logger = kwargs.get('logger', None) self.backbone.to(self.local_rank) self.classifier.to(self.local_rank) train_loader = balanced_loader(train_set, batch_size, num_workers=num_workers, shuffle=False, pin_mem...
['def', 'run(self,', 'train_set,', 'valid_set,', 'epochs:', 'int,', 'batch_size:', 'int,', 'num_workers:', 'int=0,', '**kwargs):', 'logger', '=', "kwargs.get('logger',", 'None)', 'self.backbone.to(self.local_rank)', 'self.classifier.to(self.local_rank)', 'train_loader', '=', 'balanced_loader(train_set,', 'batch_size,',...
381,152
huawei-noah/xingtian
uni_comm.py
UniComm.recv_bytes
recv_bytes
Create common recv_bytes interface.
[ "Create", "common", "recv_bytes", "interface." ]
def recv_bytes(self, block=True): return self.comm.recv_bytes(block)
['def', 'recv_bytes(self,', 'block=True):', 'return', 'self.comm.recv_bytes(block)']
962,388
loicmarie/hands-detection
model.py
Model.char_predictions
char_predictions
Returns confidence scores (softmax values) for predicted characters.
[ "Returns", "confidence", "scores", "(softmax", "values)", "for", "predicted", "characters." ]
def char_predictions(self, chars_logit): log_prob = utils.logits_to_log_prob(chars_logit) ids = tf.to_int32(tf.argmax(log_prob, dimension=2), name='predicted_chars') mask = tf.cast(slim.one_hot_encoding(ids, self._params.num_char_classes), tf.bool) all_scores = tf.nn.softmax(chars_logit) selected_sc...
['def', 'char_predictions(self,', 'chars_logit):', 'log_prob', '=', 'utils.logits_to_log_prob(chars_logit)', 'ids', '=', 'tf.to_int32(tf.argmax(log_prob,', 'dimension=2),', "name='predicted_chars')", 'mask', '=', 'tf.cast(slim.one_hot_encoding(ids,', 'self._params.num_char_classes),', 'tf.bool)', 'all_scores', '=', 'tf...
574,429
ucas-vg/PointTinyBenchmark
yolact_head.py
YOLACTSegmHead.simple_test
simple_test
Test function without test-time augmentation.
[ "Test", "function", "without", "test-time", "augmentation." ]
def simple_test(self, feats, img_metas, rescale=False): raise NotImplementedError('simple_test of YOLACTSegmHead is not implemented because this head is only evaluated during training')
['def', 'simple_test(self,', 'feats,', 'img_metas,', 'rescale=False):', 'raise', "NotImplementedError('simple_test", 'of', 'YOLACTSegmHead', 'is', 'not', 'implemented', 'because', 'this', 'head', 'is', 'only', 'evaluated', 'during', "training')"]
781,698
jianfenglihg/UnOpticalFlow
evaluate_flow.py
read_raw_calib_file
read_raw_calib_file
Read in a calibration file and parse into a dictionary.
[ "Read", "in", "a", "calibration", "file", "and", "parse", "into", "a", "dictionary." ]
def read_raw_calib_file(filepath): data = {} with open(filepath, 'r') as f: for line in f.readlines(): (key, value) = line.split(':', 1) try: data[key] = np.array([float(x) for x in value.split()]) except ValueError: pass return dat...
['def', 'read_raw_calib_file(filepath):', 'data', '=', '{}', 'with', 'open(filepath,', "'r')", 'as', 'f:', 'for', 'line', 'in', 'f.readlines():', '(key,', 'value)', '=', "line.split(':',", '1)', 'try:', 'data[key]', '=', 'np.array([float(x)', 'for', 'x', 'in', 'value.split()])', 'except', 'ValueError:', 'pass', 'return...
378,590
AbhinandanVellanki/Pacman-Artificial-
busters.py
getObservationProbability
getObservationProbability
Returns the probability P( noisyDistance | trueDistance ).
[ "Returns", "the", "probability", "P(", "noisyDistance", "|", "trueDistance", ")." ]
def getObservationProbability(noisyDistance, trueDistance): global observationDistributions if noisyDistance not in observationDistributions: distribution = util.Counter() for (error, prob) in zip(SONAR_NOISE_VALUES, SONAR_NOISE_PROBS): distribution[max(1, noisyDistance - error)] += ...
['def', 'getObservationProbability(noisyDistance,', 'trueDistance):', 'global', 'observationDistributions', 'if', 'noisyDistance', 'not', 'in', 'observationDistributions:', 'distribution', '=', 'util.Counter()', 'for', '(error,', 'prob)', 'in', 'zip(SONAR_NOISE_VALUES,', 'SONAR_NOISE_PROBS):', 'distribution[max(1,', 'n...
255,272
enyac-group/NeuralPower
conv.py
Conv2d.split_model
split_model
Split in model parallel fashion.
[ "Split", "in", "model", "parallel", "fashion." ]
def split_model(self, num_splits): self._filters[3] = self._filters[3] // num_splits
['def', 'split_model(self,', 'num_splits):', 'self._filters[3]', '=', 'self._filters[3]', '//', 'num_splits']
293,459
clvrai/spirl
base.py
MujocoEnv.find_contacts
find_contacts
Finds contact between two geom groups.
[ "Finds", "contact", "between", "two", "geom", "groups." ]
def find_contacts(self, geoms_1, geoms_2): for contact in self.sim.data.contact[0:self.sim.data.ncon]: c1_in_g1 = self.sim.model.geom_id2name(contact.geom1) in geoms_1 c2_in_g2 = self.sim.model.geom_id2name(contact.geom2) in geoms_2 c2_in_g1 = self.sim.model.geom_id2name(contact.geom2) in ge...
['def', 'find_contacts(self,', 'geoms_1,', 'geoms_2):', 'for', 'contact', 'in', 'self.sim.data.contact[0:self.sim.data.ncon]:', 'c1_in_g1', '=', 'self.sim.model.geom_id2name(contact.geom1)', 'in', 'geoms_1', 'c2_in_g2', '=', 'self.sim.model.geom_id2name(contact.geom2)', 'in', 'geoms_2', 'c2_in_g1', '=', 'self.sim.model...
896,800
rifqind/Agent-Programs-3KS1
utils.py
argmax_random_tie
argmax_random_tie
Return an element with highest fn(seq[i]) score; break ties at random.
[ "Return", "an", "element", "with", "highest", "fn(seq[i])", "score;", "break", "ties", "at", "random." ]
def argmax_random_tie(seq, key=identity): return argmax(shuffled(seq), key=key)
['def', 'argmax_random_tie(seq,', 'key=identity):', 'return', 'argmax(shuffled(seq),', 'key=key)']
22,082
howdypierce/CalendarEventNLP
testdata.py
next_day
next_day
Given the month and day, return the next such date, which might be next year.
[ "Given", "the", "month", "and", "day,", "return", "the", "next", "such", "date,", "which", "might", "be", "next", "year." ]
def next_day(mon: int, day: int) -> date: trial_date = date(today.year, mon, day) if trial_date < today: return date(today.year + 1, mon, day) return trial_date
['def', 'next_day(mon:', 'int,', 'day:', 'int)', '->', 'date:', 'trial_date', '=', 'date(today.year,', 'mon,', 'day)', 'if', 'trial_date', '<', 'today:', 'return', 'date(today.year', '+', '1,', 'mon,', 'day)', 'return', 'trial_date']
411,025
ViTAE-Transformer/ViTDet
bucketing_bbox_coder.py
bbox2bucket
bbox2bucket
Generate buckets estimation and fine regression targets.
[ "Generate", "buckets", "estimation", "and", "fine", "regression", "targets." ]
def bbox2bucket(proposals, gt, num_buckets, scale_factor, offset_topk=2, offset_upperbound=1.0, cls_ignore_neighbor=True): assert proposals.size() == gt.size() proposals = proposals.float() gt = gt.float() (bucket_w, bucket_h, l_buckets, r_buckets, t_buckets, d_buckets) = generat_buckets(proposals, num_...
['def', 'bbox2bucket(proposals,', 'gt,', 'num_buckets,', 'scale_factor,', 'offset_topk=2,', 'offset_upperbound=1.0,', 'cls_ignore_neighbor=True):', 'assert', 'proposals.size()', '==', 'gt.size()', 'proposals', '=', 'proposals.float()', 'gt', '=', 'gt.float()', '(bucket_w,', 'bucket_h,', 'l_buckets,', 'r_buckets,', 't_b...
945,257
bhateharsh/computer_vision
yacs.py
CfgNode.key_is_renamed
key_is_renamed
Test if a key is renamed.
[ "Test", "if", "a", "key", "is", "renamed." ]
def key_is_renamed(self, full_key): return full_key in self.__dict__[CfgNode.RENAMED_KEYS]
['def', 'key_is_renamed(self,', 'full_key):', 'return', 'full_key', 'in', 'self.__dict__[CfgNode.RENAMED_KEYS]']
475,699
ameet-1997/AttentionGuidance
evaluate_wmt.py
chunks
chunks
Yield successive n-sized chunks from lst.
[ "Yield", "successive", "n-sized", "chunks", "from", "lst." ]
def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n]
['def', 'chunks(lst,', 'n):', 'for', 'i', 'in', 'range(0,', 'len(lst),', 'n):', 'yield', 'lst[i:i', '+', 'n]']
92,840
TonyLianLong/VAI-ReinforcementLearning
hooks_test_utils.py
HooksTracker.before_substep
before_substep
Implements `before_substep` Composer callback.
[ "Implements", "`before_substep`", "Composer", "callback." ]
def before_substep(self, physics, *args): if self._has_super: super(HooksTracker, self).before_substep(physics, *args) if not self.tracked: return self.assertHooksCalledOnce('initialize_episode_mjcf', 'after_compile', 'initialize_episode') self.assertEqual(self._call_count['after_step'],...
['def', 'before_substep(self,', 'physics,', '*args):', 'if', 'self._has_super:', 'super(HooksTracker,', 'self).before_substep(physics,', '*args)', 'if', 'not', 'self.tracked:', 'return', "self.assertHooksCalledOnce('initialize_episode_mjcf',", "'after_compile',", "'initialize_episode')", "self.assertEqual(self._call_co...
439,883
thaines/helit
solve_shared.py
State.sample
sample
Samples the current state, storing the current estimate of the model parameters.
[ "Samples", "the", "current", "state,", "storing", "the", "current", "estimate", "of", "the", "model", "parameters." ]
def sample(self): self.model.sampleState(self)
['def', 'sample(self):', 'self.model.sampleState(self)']
591,224
gunthercox/ChatterBot
base.py
DrizzleDialect.get_table_names
get_table_names
Return a Unicode SHOW TABLES from a given schema.
[ "Return", "a", "Unicode", "SHOW", "TABLES", "from", "a", "given", "schema." ]
def get_table_names(self, connection, schema=None, **kw): if schema is not None: current_schema = schema else: current_schema = self.default_schema_name charset = 'utf8' rp = connection.execute('SHOW TABLES FROM %s' % self.identifier_preparer.quote_identifier(current_schema)) return ...
['def', 'get_table_names(self,', 'connection,', 'schema=None,', '**kw):', 'if', 'schema', 'is', 'not', 'None:', 'current_schema', '=', 'schema', 'else:', 'current_schema', '=', 'self.default_schema_name', 'charset', '=', "'utf8'", 'rp', '=', "connection.execute('SHOW", 'TABLES', 'FROM', "%s'", '%', 'self.identifier_pre...
480,962
sek788432/Waymo-2D-Object-Detection
model_lib.py
continuous_eval_generator
continuous_eval_generator
Perform continuous evaluation on checkpoints written to a model directory.
[ "Perform", "continuous", "evaluation", "on", "checkpoints", "written", "to", "a", "model", "directory." ]
def continuous_eval_generator(estimator, model_dir, input_fn, train_steps, name, max_retries=0): def terminate_eval(): tf.logging.info('Terminating eval after 180 seconds of no checkpoints') return True for ckpt in tf.train.checkpoints_iterator(model_dir, min_interval_secs=180, timeout=None, ti...
['def', 'continuous_eval_generator(estimator,', 'model_dir,', 'input_fn,', 'train_steps,', 'name,', 'max_retries=0):', 'def', 'terminate_eval():', "tf.logging.info('Terminating", 'eval', 'after', '180', 'seconds', 'of', 'no', "checkpoints')", 'return', 'True', 'for', 'ckpt', 'in', 'tf.train.checkpoints_iterator(model_d...
974,598
intel/neural-compressor
create_obj_from_config.py
get_func_from_config
get_func_from_config
Get the function or the composed function from configuration.
[ "Get", "the", "function", "or", "the", "composed", "function", "from", "configuration." ]
def get_func_from_config(func_dict, cfg, compose=True): func_list = [] for (func_name, func_value) in OrderedDict(cfg).items(): func_kwargs = {} func_args = [] if isinstance(func_value, dict): func_kwargs = func_value elif func_value is not None: func_args...
['def', 'get_func_from_config(func_dict,', 'cfg,', 'compose=True):', 'func_list', '=', '[]', 'for', '(func_name,', 'func_value)', 'in', 'OrderedDict(cfg).items():', 'func_kwargs', '=', '{}', 'func_args', '=', '[]', 'if', 'isinstance(func_value,', 'dict):', 'func_kwargs', '=', 'func_value', 'elif', 'func_value', 'is', '...
721,459
ddbourgin/numpy-ml
modules.py
SkipConnectionIdentityModule.parameters
parameters
A dictionary of the module parameters.
[ "A", "dictionary", "of", "the", "module", "parameters." ]
def parameters(self): return {'components': {'add3': self.add3.parameters, 'conv1': self.conv1.parameters, 'conv2': self.conv2.parameters, 'batchnorm1': self.batchnorm1.parameters, 'batchnorm2': self.batchnorm2.parameters}}
['def', 'parameters(self):', 'return', "{'components':", "{'add3':", 'self.add3.parameters,', "'conv1':", 'self.conv1.parameters,', "'conv2':", 'self.conv2.parameters,', "'batchnorm1':", 'self.batchnorm1.parameters,', "'batchnorm2':", 'self.batchnorm2.parameters}}']
730,243
jerrodparker20/adaptive-transformers-in-rl
monobeast_test.py
learn
learn
Performs a learning (optimization) step.
[ "Performs", "a", "learning", "(optimization)", "step." ]
def learn(flags, actor_model, model, batch, initial_agent_state, optimizer, scheduler, lock=threading.Lock()): with lock: (mems, mem_padding) = (None, None) for i in range(0, flags.unroll_length + 1, flags.chunk_size): mini_batch = {key: batch[key][i:i + flags.chunk_size] for key in batc...
['def', 'learn(flags,', 'actor_model,', 'model,', 'batch,', 'initial_agent_state,', 'optimizer,', 'scheduler,', 'lock=threading.Lock()):', 'with', 'lock:', '(mems,', 'mem_padding)', '=', '(None,', 'None)', 'for', 'i', 'in', 'range(0,', 'flags.unroll_length', '+', '1,', 'flags.chunk_size):', 'mini_batch', '=', '{key:', ...
409,378
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pydoc.py
pager
pager
The first time this is called, determine what kind of pager to use.
[ "The", "first", "time", "this", "is", "called,", "determine", "what", "kind", "of", "pager", "to", "use." ]
def pager(text): global pager pager = getpager() pager(text)
['def', 'pager(text):', 'global', 'pager', 'pager', '=', 'getpager()', 'pager(text)']
429,288
yuantn/MI-AOD
ghm_loss.py
GHMC.forward
forward
Calculate the GHM-C loss.
[ "Calculate", "the", "GHM-C", "loss." ]
def forward(self, pred, target, label_weight, *args, **kwargs): if pred.dim() != target.dim(): (target, label_weight) = _expand_onehot_labels(target, label_weight, pred.size(-1)) (target, label_weight) = (target.float(), label_weight.float()) edges = self.edges mmt = self.momentum weights = ...
['def', 'forward(self,', 'pred,', 'target,', 'label_weight,', '*args,', '**kwargs):', 'if', 'pred.dim()', '!=', 'target.dim():', '(target,', 'label_weight)', '=', '_expand_onehot_labels(target,', 'label_weight,', 'pred.size(-1))', '(target,', 'label_weight)', '=', '(target.float(),', 'label_weight.float())', 'edges', '...
635,272
cheng052/BRNet
data_augment_utils.py
points_transform_
points_transform_
Apply transforms to points and box centers.
[ "Apply", "transforms", "to", "points", "and", "box", "centers." ]
def points_transform_(points, centers, point_masks, loc_transform, rot_transform, valid_mask): num_box = centers.shape[0] num_points = points.shape[0] rot_mat_T = np.zeros((num_box, 3, 3), dtype=points.dtype) for i in range(num_box): _rotation_matrix_3d_(rot_mat_T[i], rot_transform[i], 2) fo...
['def', 'points_transform_(points,', 'centers,', 'point_masks,', 'loc_transform,', 'rot_transform,', 'valid_mask):', 'num_box', '=', 'centers.shape[0]', 'num_points', '=', 'points.shape[0]', 'rot_mat_T', '=', 'np.zeros((num_box,', '3,', '3),', 'dtype=points.dtype)', 'for', 'i', 'in', 'range(num_box):', '_rotation_matri...
409,843
intra2net/guibot
test_finder.py
FinderTest.test_feature_viewport
test_feature_viewport
Test for successful match of view-trasformed images for default feature CV backend.
[ "Test", "for", "successful", "match", "of", "view-trasformed", "images", "for", "default", "feature", "CV", "backend." ]
def test_feature_viewport(self): finder = FeatureFinder() finder.params['find']['similarity'].value = 0.4 matches = finder.find(Image('n_ibs'), Image('h_ibs_viewport')) self.assertEqual(len(matches), 1) self.assertAlmostEqual(matches[0].x, 68, delta=5) self.assertAlmostEqual(matches[0].y, 18, de...
['def', 'test_feature_viewport(self):', 'finder', '=', 'FeatureFinder()', "finder.params['find']['similarity'].value", '=', '0.4', 'matches', '=', "finder.find(Image('n_ibs'),", "Image('h_ibs_viewport'))", 'self.assertEqual(len(matches),', '1)', 'self.assertAlmostEqual(matches[0].x,', '68,', 'delta=5)', 'self.assertAlm...
572,645
myothida/Supervised-Machine-Learning
stata.py
StataWriter.write_file
write_file
Export DataFrame object to Stata dta format.
[ "Export", "DataFrame", "object", "to", "Stata", "dta", "format." ]
def write_file(self) -> None: with get_handle(self._fname, 'wb', compression=self._compression, is_text=False, storage_options=self.storage_options) as self.handles: if self.handles.compression['method'] is not None: (self._output_file, self.handles.handle) = (self.handles.handle, BytesIO()) ...
['def', 'write_file(self)', '->', 'None:', 'with', 'get_handle(self._fname,', "'wb',", 'compression=self._compression,', 'is_text=False,', 'storage_options=self.storage_options)', 'as', 'self.handles:', 'if', "self.handles.compression['method']", 'is', 'not', 'None:', '(self._output_file,', 'self.handles.handle)', '=',...
443,323
brohrer/autoencoder_visualization
nn_viz_24.py
add_filler_image
add_filler_image
Add a chunk of image as a placeholder.
[ "Add", "a", "chunk", "of", "image", "as", "a", "placeholder." ]
def add_filler_image(ax, n_im_rows, n_im_cols): fill_patch = np.random.sample(size=(n_im_rows, n_im_cols)) ax.imshow(fill_patch, cmap='inferno')
['def', 'add_filler_image(ax,', 'n_im_rows,', 'n_im_cols):', 'fill_patch', '=', 'np.random.sample(size=(n_im_rows,', 'n_im_cols))', 'ax.imshow(fill_patch,', "cmap='inferno')"]
419,827
intel/neural-compressor
graph_util.py
GraphRewriterHelper.values_from_const
values_from_const
Extracts the values from a const NodeDef as a numpy ndarray.
[ "Extracts", "the", "values", "from", "a", "const", "NodeDef", "as", "a", "numpy", "ndarray." ]
def values_from_const(node_def): assert node_def.op == 'Const', "Node named '%s' should be a Const op." % node_def.name input_tensor = node_def.attr['value'].tensor tensor_value = tensor_util.MakeNdarray(input_tensor) return tensor_value
['def', 'values_from_const(node_def):', 'assert', 'node_def.op', '==', "'Const',", '"Node', 'named', "'%s'", 'should', 'be', 'a', 'Const', 'op."', '%', 'node_def.name', 'input_tensor', '=', "node_def.attr['value'].tensor", 'tensor_value', '=', 'tensor_util.MakeNdarray(input_tensor)', 'return', 'tensor_value']
737,612
accel-brain/accel-brain-code
auto_encoder.py
AutoEncoder.get_init_deferred_flag
get_init_deferred_flag
getter for `bool` that means initialization in this class will be deferred or not.
[ "getter", "for", "`bool`", "that", "means", "initialization", "in", "this", "class", "will", "be", "deferred", "or", "not." ]
def get_init_deferred_flag(self): return self.__init_deferred_flag
['def', 'get_init_deferred_flag(self):', 'return', 'self.__init_deferred_flag']
6,986
mj-will/nessai
test_flow_utils.py
test_configure_model_flow_class
test_configure_model_flow_class
Test using a custom class of flow.
[ "Test", "using", "a", "custom", "class", "of", "flow." ]
def test_configure_model_flow_class(config): class TestFlow: def __init__(self, n_inputs, n_neurons, n_blocks, n_layers): self.n_inputs = n_inputs self.n_neurons = n_neurons self.n_blocks = n_blocks self.n_layers = n_layers def to(self, input): ...
['def', 'test_configure_model_flow_class(config):', 'class', 'TestFlow:', 'def', '__init__(self,', 'n_inputs,', 'n_neurons,', 'n_blocks,', 'n_layers):', 'self.n_inputs', '=', 'n_inputs', 'self.n_neurons', '=', 'n_neurons', 'self.n_blocks', '=', 'n_blocks', 'self.n_layers', '=', 'n_layers', 'def', 'to(self,', 'input):',...
292,554
mariacer/cl_in_rnns
preprocess_mud.py
tags2labels
tags2labels
Transform list of tags in a sentence into list of labels of the tags.
[ "Transform", "list", "of", "tags", "in", "a", "sentence", "into", "list", "of", "labels", "of", "the", "tags." ]
def tags2labels(tags_sentence, tagset): labels = [] for tag in tags_sentence: if tag in tagset: idx = tagset.index(tag) elif tag == '_': idx = '_' else: raise ValueError labels.append(idx) return labels
['def', 'tags2labels(tags_sentence,', 'tagset):', 'labels', '=', '[]', 'for', 'tag', 'in', 'tags_sentence:', 'if', 'tag', 'in', 'tagset:', 'idx', '=', 'tagset.index(tag)', 'elif', 'tag', '==', "'_':", 'idx', '=', "'_'", 'else:', 'raise', 'ValueError', 'labels.append(idx)', 'return', 'labels']
122,772