project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
weimin17/Object-Detection_HelmetDetection | coords.py | from_kgs | from_kgs | Converts from a KGS coordinate to a MiniGo coordinate. | [
"Converts",
"from",
"a",
"KGS",
"coordinate",
"to",
"a",
"MiniGo",
"coordinate."
] | def from_kgs(board_size, kgsc):
if kgsc == 'pass':
return None
kgsc = kgsc.upper()
col = _KGS_COLUMNS.index(kgsc[0])
row_from_bottom = int(kgsc[1:])
return (board_size - row_from_bottom, col) | ['def', 'from_kgs(board_size,', 'kgsc):', 'if', 'kgsc', '==', "'pass':", 'return', 'None', 'kgsc', '=', 'kgsc.upper()', 'col', '=', '_KGS_COLUMNS.index(kgsc[0])', 'row_from_bottom', '=', 'int(kgsc[1:])', 'return', '(board_size', '-', 'row_from_bottom,', 'col)'] | 758,111 |
googleapis/python-aiplatform | client.py | VizierServiceClient.parse_study_path | parse_study_path | Parses a study path into its component segments. | [
"Parses",
"a",
"study",
"path",
"into",
"its",
"component",
"segments."
] | def parse_study_path(path: str) -> Dict[str, str]:
m = re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/studies/(?P<study>.+?)$', path)
return m.groupdict() if m else {} | ['def', 'parse_study_path(path:', 'str)', '->', 'Dict[str,', 'str]:', 'm', '=', "re.match('^projects/(?P<project>.+?)/locations/(?P<location>.+?)/studies/(?P<study>.+?)$',", 'path)', 'return', 'm.groupdict()', 'if', 'm', 'else', '{}'] | 814,278 |
Farama-Foundation/Gymnasium | async_vector_env.py | AsyncVectorEnv.reset_wait | reset_wait | Waits for the calls triggered by :meth:`reset_async` to finish and returns the results. | [
"Waits",
"for",
"the",
"calls",
"triggered",
"by",
":meth:`reset_async`",
"to",
"finish",
"and",
"returns",
"the",
"results."
] | def reset_wait(self, timeout: Optional[Union[int, float]]=None, seed: Optional[int]=None, options: Optional[dict]=None) -> Union[ObsType, Tuple[ObsType, dict]]:
self._assert_is_running()
if self._state != AsyncState.WAITING_RESET:
raise NoAsyncCallError('Calling `reset_wait` without any prior call to `r... | ['def', 'reset_wait(self,', 'timeout:', 'Optional[Union[int,', 'float]]=None,', 'seed:', 'Optional[int]=None,', 'options:', 'Optional[dict]=None)', '->', 'Union[ObsType,', 'Tuple[ObsType,', 'dict]]:', 'self._assert_is_running()', 'if', 'self._state', '!=', 'AsyncState.WAITING_RESET:', 'raise', "NoAsyncCallError('Callin... | 573,326 |
sarnsdev/social-alignment-data-mining | windows.py | output_subprocess_Popen | output_subprocess_Popen | Calls subprocess_Popen, returning the output, error and exit code in a tuple. | [
"Calls",
"subprocess_Popen,",
"returning",
"the",
"output,",
"error",
"and",
"exit",
"code",
"in",
"a",
"tuple."
] | def output_subprocess_Popen(command, **params):
if 'stdout' in params or 'stderr' in params:
raise TypeError("don't use stderr or stdout with output_subprocess_Popen")
params['stdout'] = subprocess.PIPE
params['stderr'] = subprocess.PIPE
p = subprocess_Popen(command, **params)
out = p.commun... | ['def', 'output_subprocess_Popen(command,', '**params):', 'if', "'stdout'", 'in', 'params', 'or', "'stderr'", 'in', 'params:', 'raise', 'TypeError("don\'t', 'use', 'stderr', 'or', 'stdout', 'with', 'output_subprocess_Popen")', "params['stdout']", '=', 'subprocess.PIPE', "params['stderr']", '=', 'subprocess.PIPE', 'p', ... | 392,835 |
enuguru/artificial_intelligence_and_machine_ | test.py | EnvironBuilder.get_environ | get_environ | Return the built environ. | [
"Return",
"the",
"built",
"environ."
] | def get_environ(self):
input_stream = self.input_stream
content_length = self.content_length
content_type = self.content_type
if input_stream is not None:
start_pos = input_stream.tell()
input_stream.seek(0, 2)
end_pos = input_stream.tell()
input_stream.seek(start_pos)
... | ['def', 'get_environ(self):', 'input_stream', '=', 'self.input_stream', 'content_length', '=', 'self.content_length', 'content_type', '=', 'self.content_type', 'if', 'input_stream', 'is', 'not', 'None:', 'start_pos', '=', 'input_stream.tell()', 'input_stream.seek(0,', '2)', 'end_pos', '=', 'input_stream.tell()', 'input... | 132,374 |
43Carrig/recurrent_neural_networks_practice | gen_dataset_ops.py | tensor_slice_dataset | tensor_slice_dataset | Creates a dataset that emits each dim-0 slice of `components` once. | [
"Creates",
"a",
"dataset",
"that",
"emits",
"each",
"dim-0",
"slice",
"of",
"`components`",
"once."
] | def tensor_slice_dataset(components, output_shapes, name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
if not isinstance(output_shapes, (list, tuple)):
raise TypeError("Expected list for 'output_shapes' argument to 'tensor_slice_dataset' Op, not %r." % ... | ['def', 'tensor_slice_dataset(components,', 'output_shapes,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(output_shapes,', '(list,', 'tuple)):', 'raise', 'TypeError("Expected', 'list', 'for', "'output_shapes'", 'argu... | 337,663 |
GregorKobsik/Octree-Transformer | sample_utils_test.py | TestPrepareInputForNextLayer_Spatial2.test_depth_layer_2_cuda | test_depth_layer_2_cuda | Test the input for the second input layer on the gpu. | [
"Test",
"the",
"input",
"for",
"the",
"second",
"input",
"layer",
"on",
"the",
"gpu."
] | def test_depth_layer_2_cuda(self):
self.depth_layer_2(pos_encoding='centered', device='cuda') | ['def', 'test_depth_layer_2_cuda(self):', "self.depth_layer_2(pos_encoding='centered',", "device='cuda')"] | 755,137 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | ipapp.py | TerminalIPythonApp.initialize | initialize | Do actions after construct, but before starting the app. | [
"Do",
"actions",
"after",
"construct,",
"but",
"before",
"starting",
"the",
"app."
] | def initialize(self, argv=None):
super(TerminalIPythonApp, self).initialize(argv)
if self.subapp is not None:
return
if self.extra_args and (not self.something_to_run):
self.file_to_run = self.extra_args[0]
self.init_path()
self.init_shell()
self.init_banner()
self.init_gui_p... | ['def', 'initialize(self,', 'argv=None):', 'super(TerminalIPythonApp,', 'self).initialize(argv)', 'if', 'self.subapp', 'is', 'not', 'None:', 'return', 'if', 'self.extra_args', 'and', '(not', 'self.something_to_run):', 'self.file_to_run', '=', 'self.extra_args[0]', 'self.init_path()', 'self.init_shell()', 'self.init_ban... | 448,821 |
abakan-zz/ablog | __init__.py | get_html_templates_path | get_html_templates_path | Return path to ABlog templates folder. | [
"Return",
"path",
"to",
"ABlog",
"templates",
"folder."
] | def get_html_templates_path():
pkgdir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(pkgdir, 'templates') | ['def', 'get_html_templates_path():', 'pkgdir', '=', 'os.path.abspath(os.path.dirname(__file__))', 'return', 'os.path.join(pkgdir,', "'templates')"] | 6,424 |
ryu-ed/SpaceInvaders_Ros | states.py | Line.text | text | Potential over- & underlined title. | [
"Potential",
"over-",
"&",
"underlined",
"title."
] | def text(self, match, context, next_state):
lineno = self.state_machine.abs_line_number() - 1
overline = context[0]
title = match.string
underline = ''
try:
underline = self.state_machine.next_line()
except EOFError:
blocktext = overline + '\n' + title
if len(overline.rst... | ['def', 'text(self,', 'match,', 'context,', 'next_state):', 'lineno', '=', 'self.state_machine.abs_line_number()', '-', '1', 'overline', '=', 'context[0]', 'title', '=', 'match.string', 'underline', '=', "''", 'try:', 'underline', '=', 'self.state_machine.next_line()', 'except', 'EOFError:', 'blocktext', '=', 'overline... | 394,912 |
suarez12138/AI-Reversi_IMP_TextDichotomy | build_py.py | build_py.get_package_dir | get_package_dir | Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any). | [
"Return",
"the",
"directory,",
"relative",
"to",
"the",
"top",
"of",
"the",
"source",
"distribution,",
"where",
"package",
"'package'",
"should",
"be",
"found",
"(at",
"least",
"according",
"to",
"the",
"'package_dir'",
"option,",
"if",
"any)."
] | def get_package_dir(self, package):
path = package.split('.')
if not self.package_dir:
if path:
return os.path.join(*path)
else:
return ''
else:
tail = []
while path:
try:
pdir = self.package_dir['.'.join(path)]
... | ['def', 'get_package_dir(self,', 'package):', 'path', '=', "package.split('.')", 'if', 'not', 'self.package_dir:', 'if', 'path:', 'return', 'os.path.join(*path)', 'else:', 'return', "''", 'else:', 'tail', '=', '[]', 'while', 'path:', 'try:', 'pdir', '=', "self.package_dir['.'.join(path)]", 'except', 'KeyError:', 'tail.... | 100,740 |
eddylau328/fyp-artificial-intelligence-ac-control-device | text_format.py | ParseBool | ParseBool | Parse a boolean value. | [
"Parse",
"a",
"boolean",
"value."
] | def ParseBool(text):
if text in ('true', 't', '1', 'True'):
return True
elif text in ('false', 'f', '0', 'False'):
return False
else:
raise ValueError('Expected "true" or "false".') | ['def', 'ParseBool(text):', 'if', 'text', 'in', "('true',", "'t',", "'1',", "'True'):", 'return', 'True', 'elif', 'text', 'in', "('false',", "'f',", "'0',", "'False'):", 'return', 'False', 'else:', 'raise', "ValueError('Expected", '"true"', 'or', '"false".\')'] | 215,260 |
sarnsdev/social-alignment-data-mining | _gb_losses.py | LossFunction.init_estimator | init_estimator | Default ``init`` estimator for loss function. | [
"Default",
"``init``",
"estimator",
"for",
"loss",
"function."
] | def init_estimator(self):
raise NotImplementedError() | ['def', 'init_estimator(self):', 'raise', 'NotImplementedError()'] | 391,917 |
clvrai/spirl | skill_prior_mdl.py | SkillPriorMdl.load_weights_and_freeze | load_weights_and_freeze | Optionally loads weights for components of the architecture + freezes these components. | [
"Optionally",
"loads",
"weights",
"for",
"components",
"of",
"the",
"architecture",
"+",
"freezes",
"these",
"components."
] | def load_weights_and_freeze(self):
if self._hp.embedding_checkpoint is not None:
print('Loading pre-trained embedding from {}!'.format(self._hp.embedding_checkpoint))
self.load_state_dict(load_by_key(self._hp.embedding_checkpoint, 'decoder', self.state_dict(), self.device))
self.load_state_d... | ['def', 'load_weights_and_freeze(self):', 'if', 'self._hp.embedding_checkpoint', 'is', 'not', 'None:', "print('Loading", 'pre-trained', 'embedding', 'from', "{}!'.format(self._hp.embedding_checkpoint))", 'self.load_state_dict(load_by_key(self._hp.embedding_checkpoint,', "'decoder',", 'self.state_dict(),', 'self.device)... | 896,950 |
sek788432/Waymo-2D-Object-Detection | factory.py | rpn_head_generator | rpn_head_generator | Generator function for RPN head architecture. | [
"Generator",
"function",
"for",
"RPN",
"head",
"architecture."
] | def rpn_head_generator(params):
head_params = params.rpn_head
anchors_per_location = params.anchor.num_scales * len(params.anchor.aspect_ratios)
return heads.RpnHead(params.architecture.min_level, params.architecture.max_level, anchors_per_location, head_params.num_convs, head_params.num_filters, head_param... | ['def', 'rpn_head_generator(params):', 'head_params', '=', 'params.rpn_head', 'anchors_per_location', '=', 'params.anchor.num_scales', '*', 'len(params.anchor.aspect_ratios)', 'return', 'heads.RpnHead(params.architecture.min_level,', 'params.architecture.max_level,', 'anchors_per_location,', 'head_params.num_convs,', '... | 973,519 |
aeon-toolkit/aeon | test_base.py | test__check_y | test__check_y | Test private method _check_y. | [
"Test",
"private",
"method",
"_check_y."
] | def test__check_y():
reg = _TestRegressor()
y = np.random.random(size=100)
reg._check_y(y, 100)
assert isinstance(y, np.ndarray)
y = pd.Series(y)
y = reg._check_y(y, 100)
assert isinstance(y, np.ndarray)
with pytest.raises(ValueError, match='Mismatch in number of cases'):
reg._ch... | ['def', 'test__check_y():', 'reg', '=', '_TestRegressor()', 'y', '=', 'np.random.random(size=100)', 'reg._check_y(y,', '100)', 'assert', 'isinstance(y,', 'np.ndarray)', 'y', '=', 'pd.Series(y)', 'y', '=', 'reg._check_y(y,', '100)', 'assert', 'isinstance(y,', 'np.ndarray)', 'with', 'pytest.raises(ValueError,', "match='M... | 399,835 |
netket/netket | base.py | random_state | random_state | Generates either a single or a batch of uniformly distributed random states. | [
"Generates",
"either",
"a",
"single",
"or",
"a",
"batch",
"of",
"uniformly",
"distributed",
"random",
"states."
] | def random_state(hilb, key, *, size=None, dtype=np.float32):
return random_state(hilb, key, size, dtype=dtype) | ['def', 'random_state(hilb,', 'key,', '*,', 'size=None,', 'dtype=np.float32):', 'return', 'random_state(hilb,', 'key,', 'size,', 'dtype=dtype)'] | 736,081 |
enuguru/artificial_intelligence_and_machine_learning | sqlstore.py | SQLStore.blobEncode | blobEncode | Convert a str object into the necessary object for storing in the database as a blob. | [
"Convert",
"a",
"str",
"object",
"into",
"the",
"necessary",
"object",
"for",
"storing",
"in",
"the",
"database",
"as",
"a",
"blob."
] | def blobEncode(self, s):
return s | ['def', 'blobEncode(self,', 's):', 'return', 's'] | 159,500 |
intra2net/guibot | test_fileresolver.py | FileResolverTest.test_search | test_search | Check that different :py:class:`FileResolver` instances contain the same paths. | [
"Check",
"that",
"different",
":py:class:`FileResolver`",
"instances",
"contain",
"the",
"same",
"paths."
] | def test_search(self):
self.resolver.add_path('images')
self.assertEqual(os.path.join('images', 'shape_black_box.png'), self.resolver.search('shape_black_box.png'))
new_finder = FileResolver()
self.assertEqual(os.path.join('images', 'shape_black_box.png'), new_finder.search('shape_black_box')) | ['def', 'test_search(self):', "self.resolver.add_path('images')", "self.assertEqual(os.path.join('images',", "'shape_black_box.png'),", "self.resolver.search('shape_black_box.png'))", 'new_finder', '=', 'FileResolver()', "self.assertEqual(os.path.join('images',", "'shape_black_box.png'),", "new_finder.search('shape_bla... | 572,625 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | util.py | GetFilesRecursively | GetFilesRecursively | Gets all records recursively for some topdir. | [
"Gets",
"all",
"records",
"recursively",
"for",
"some",
"topdir."
] | def GetFilesRecursively(topdir):
assert topdir
topdir = os.path.expanduser(topdir)
allpaths = []
for (path, _, leaffiles) in tf.gfile.Walk(topdir):
if leaffiles:
allpaths.extend([os.path.join(path, i) for i in leaffiles])
if not allpaths:
raise ValueError('No files found ... | ['def', 'GetFilesRecursively(topdir):', 'assert', 'topdir', 'topdir', '=', 'os.path.expanduser(topdir)', 'allpaths', '=', '[]', 'for', '(path,', '_,', 'leaffiles)', 'in', 'tf.gfile.Walk(topdir):', 'if', 'leaffiles:', 'allpaths.extend([os.path.join(path,', 'i)', 'for', 'i', 'in', 'leaffiles])', 'if', 'not', 'allpaths:',... | 29,787 |
vlukiyanov/pt-dec | test_cluster.py | TestClusterAssignment.test_forward | test_forward | Basic test to check that the calculation is equivalent to the one in the paper. | [
"Basic",
"test",
"to",
"check",
"that",
"the",
"calculation",
"is",
"equivalent",
"to",
"the",
"one",
"in",
"the",
"paper."
] | def test_forward(self):
test_tensor = torch.Tensor([-2, -2]).float().unsqueeze(0)
den = float(1) / 3 + float(1) / 19
gold = torch.Tensor([float(1) / 3 / den, float(1) / 19 / den])
output = self.ca(test_tensor).data
self.assertAlmostEqual((gold - output).numpy()[0][0], 0.0)
self.assertAlmostEqual... | ['def', 'test_forward(self):', 'test_tensor', '=', 'torch.Tensor([-2,', '-2]).float().unsqueeze(0)', 'den', '=', 'float(1)', '/', '3', '+', 'float(1)', '/', '19', 'gold', '=', 'torch.Tensor([float(1)', '/', '3', '/', 'den,', 'float(1)', '/', '19', '/', 'den])', 'output', '=', 'self.ca(test_tensor).data', 'self.assertAl... | 818,431 |
google-research/rigl | mask_updaters.py | MaskUpdater.get_vars_and_masks | get_vars_and_masks | Gets all masked variables and corresponding masks. | [
"Gets",
"all",
"masked",
"variables",
"and",
"corresponding",
"masks."
] | def get_vars_and_masks(self):
all_masks = []
all_vars = []
for layer in self.get_all_pruning_layers():
for (var, mask, _) in layer.pruning_vars:
all_vars.append(var)
all_masks.append(mask)
return (all_masks, all_vars) | ['def', 'get_vars_and_masks(self):', 'all_masks', '=', '[]', 'all_vars', '=', '[]', 'for', 'layer', 'in', 'self.get_all_pruning_layers():', 'for', '(var,', 'mask,', '_)', 'in', 'layer.pruning_vars:', 'all_vars.append(var)', 'all_masks.append(mask)', 'return', '(all_masks,', 'all_vars)'] | 841,617 |
nicknochnack/RealTimeSignLanguageTFJS | imagenet_preprocessing.py | process_record_dataset | process_record_dataset | Given a Dataset with raw records, return an iterator over the records. | [
"Given",
"a",
"Dataset",
"with",
"raw",
"records,",
"return",
"an",
"iterator",
"over",
"the",
"records."
] | def process_record_dataset(dataset, is_training, batch_size, shuffle_buffer, parse_record_fn, dtype=tf.float32, datasets_num_private_threads=None, drop_remainder=False, tf_data_experimental_slack=False):
if datasets_num_private_threads:
options = tf.data.Options()
options.experimental_threading.priv... | ['def', 'process_record_dataset(dataset,', 'is_training,', 'batch_size,', 'shuffle_buffer,', 'parse_record_fn,', 'dtype=tf.float32,', 'datasets_num_private_threads=None,', 'drop_remainder=False,', 'tf_data_experimental_slack=False):', 'if', 'datasets_num_private_threads:', 'options', '=', 'tf.data.Options()', 'options.... | 851,228 |
xiaoaleiBLUE/computer_vision | cpp_lint.py | CheckAccess | CheckAccess | Checks for improper use of DISALLOW* macros. | [
"Checks",
"for",
"improper",
"use",
"of",
"DISALLOW*",
"macros."
] | def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
line = clean_lines.elided[linenum]
matched = Match('\\s*(DISALLOW_COPY_AND_ASSIGN|DISALLOW_EVIL_CONSTRUCTORS|DISALLOW_IMPLICIT_CONSTRUCTORS)', line)
if not matched:
return
if nesting_state.stack and isinstance(nesting_state.s... | ['def', 'CheckAccess(filename,', 'clean_lines,', 'linenum,', 'nesting_state,', 'error):', 'line', '=', 'clean_lines.elided[linenum]', 'matched', '=', "Match('\\\\s*(DISALLOW_COPY_AND_ASSIGN|DISALLOW_EVIL_CONSTRUCTORS|DISALLOW_IMPLICIT_CONSTRUCTORS)',", 'line)', 'if', 'not', 'matched:', 'return', 'if', 'nesting_state.st... | 473,513 |
calico/basenji | vcf.py | SNP.flip_alleles | flip_alleles | Flip reference and first alt allele. | [
"Flip",
"reference",
"and",
"first",
"alt",
"allele."
] | def flip_alleles(self):
assert len(self.alt_alleles) == 1
(self.ref_allele, self.alt_alleles[0]) = (self.alt_alleles[0], self.ref_allele)
self.alt_allele = self.alt_alleles[0]
self.flipped = True | ['def', 'flip_alleles(self):', 'assert', 'len(self.alt_alleles)', '==', '1', '(self.ref_allele,', 'self.alt_alleles[0])', '=', '(self.alt_alleles[0],', 'self.ref_allele)', 'self.alt_allele', '=', 'self.alt_alleles[0]', 'self.flipped', '=', 'True'] | 94,622 |
weimin17/Object-Detection_HelmetDetection | generate_samples.py | get_iterator | get_iterator | Return the data iterator. | [
"Return",
"the",
"data",
"iterator."
] | def get_iterator(data):
if FLAGS.data_set == 'ptb':
iterator = ptb_loader.ptb_iterator(data, FLAGS.batch_size, FLAGS.sequence_length, FLAGS.epoch_size_override)
elif FLAGS.data_set == 'imdb':
iterator = imdb_loader.imdb_iterator(data, FLAGS.batch_size, FLAGS.sequence_length)
return iterator | ['def', 'get_iterator(data):', 'if', 'FLAGS.data_set', '==', "'ptb':", 'iterator', '=', 'ptb_loader.ptb_iterator(data,', 'FLAGS.batch_size,', 'FLAGS.sequence_length,', 'FLAGS.epoch_size_override)', 'elif', 'FLAGS.data_set', '==', "'imdb':", 'iterator', '=', 'imdb_loader.imdb_iterator(data,', 'FLAGS.batch_size,', 'FLAGS... | 757,879 |
sunishsheth2009/ChatterBot | analyzers.py | RegexAnalyzer | RegexAnalyzer | Deprecated, just use a RegexTokenizer directly. | [
"Deprecated,",
"just",
"use",
"a",
"RegexTokenizer",
"directly."
] | def RegexAnalyzer(expression='\\w+(\\.?\\w+)*', gaps=False):
return RegexTokenizer(expression=expression, gaps=gaps) | ['def', "RegexAnalyzer(expression='\\\\w+(\\\\.?\\\\w+)*',", 'gaps=False):', 'return', 'RegexTokenizer(expression=expression,', 'gaps=gaps)'] | 526,555 |
sktime/sktime | test_dwt.py | check_if_dataframes_are_equal | check_if_dataframes_are_equal | Check that pandas DataFrames are equal. | [
"Check",
"that",
"pandas",
"DataFrames",
"are",
"equal."
] | def check_if_dataframes_are_equal(df1, df2):
from pandas.testing import assert_frame_equal
try:
assert_frame_equal(df1, df2)
return True
except AssertionError:
return False | ['def', 'check_if_dataframes_are_equal(df1,', 'df2):', 'from', 'pandas.testing', 'import', 'assert_frame_equal', 'try:', 'assert_frame_equal(df1,', 'df2)', 'return', 'True', 'except', 'AssertionError:', 'return', 'False'] | 877,738 |
Xianpeng919/MonoCon | yolact.py | YOLACT.init_segm_mask_weights | init_segm_mask_weights | Initialize weights of the YOLACT segm head and YOLACT mask head. | [
"Initialize",
"weights",
"of",
"the",
"YOLACT",
"segm",
"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()'] | 654,016 |
CAMeL-Lab/camel_tools | unfactored.py | _BERTFeatureTagger.predict | predict | Predict the morphosyntactic labels of a list of sentences. | [
"Predict",
"the",
"morphosyntactic",
"labels",
"of",
"a",
"list",
"of",
"sentences."
] | def predict(self, sentences, batch_size=32, max_seq_length=512):
if len(sentences) == 0:
return []
sorted_sentences = list(enumerate(sentences))
sorted_sentences = sorted(sorted_sentences, key=lambda x: len(x[1]))
sorted_sentences_idx = [i[0] for i in sorted_sentences]
sorted_sentences_text ... | ['def', 'predict(self,', 'sentences,', 'batch_size=32,', 'max_seq_length=512):', 'if', 'len(sentences)', '==', '0:', 'return', '[]', 'sorted_sentences', '=', 'list(enumerate(sentences))', 'sorted_sentences', '=', 'sorted(sorted_sentences,', 'key=lambda', 'x:', 'len(x[1]))', 'sorted_sentences_idx', '=', '[i[0]', 'for', ... | 411,118 |
MycroftAI/mycroft-core | tts.py | TTS.execute | execute | Convert sentence to speech, preprocessing out unsupported ssml The method caches results if possible using the hash of the sentence. | [
"Convert",
"sentence",
"to",
"speech,",
"preprocessing",
"out",
"unsupported",
"ssml",
"The",
"method",
"caches",
"results",
"if",
"possible",
"using",
"the",
"hash",
"of",
"the",
"sentence."
] | def execute(self, sentence, ident=None, listen=False):
sentence = self.validate_ssml(sentence)
create_signal('isSpeaking')
self._execute(sentence, ident, listen) | ['def', 'execute(self,', 'sentence,', 'ident=None,', 'listen=False):', 'sentence', '=', 'self.validate_ssml(sentence)', "create_signal('isSpeaking')", 'self._execute(sentence,', 'ident,', 'listen)'] | 290,712 |
bachiraoun/fullrmc | Engine.py | Engine.numberOfNames | numberOfNames | Length of atoms name set. | [
"Length",
"of",
"atoms",
"name",
"set."
] | def numberOfNames(self):
return len(self.__names) | ['def', 'numberOfNames(self):', 'return', 'len(self.__names)'] | 213,416 |
rudranil723/mini-main | fields.py | Field.get_bound_field | get_bound_field | Return a BoundField instance that will be used when accessing the form field in a template. | [
"Return",
"a",
"BoundField",
"instance",
"that",
"will",
"be",
"used",
"when",
"accessing",
"the",
"form",
"field",
"in",
"a",
"template."
] | def get_bound_field(self, form, field_name):
return BoundField(form, self, field_name) | ['def', 'get_bound_field(self,', 'form,', 'field_name):', 'return', 'BoundField(form,', 'self,', 'field_name)'] | 316,219 |
sunishsheth2009/ChatterBot | index.py | Index.is_empty | is_empty | Returns True if this index is empty (that is, it has never had any documents successfully written to it. | [
"Returns",
"True",
"if",
"this",
"index",
"is",
"empty",
"(that",
"is,",
"it",
"has",
"never",
"had",
"any",
"documents",
"successfully",
"written",
"to",
"it."
] | def is_empty(self):
raise NotImplementedError | ['def', 'is_empty(self):', 'raise', 'NotImplementedError'] | 482,880 |
DPerrySvendsen/COS30002 | logger.py | Logger.player | player | Use to set a player message to file. | [
"Use",
"to",
"set",
"a",
"player",
"message",
"to",
"file."
] | def player(self, player_id, message):
self._append_message(self._players[player_id], message) | ['def', 'player(self,', 'player_id,', 'message):', 'self._append_message(self._players[player_id],', 'message)'] | 137,528 |
PacktPublishing/Hands-On-Artificial--for-Banking | base_response.py | BaseResponse.status | status | The HTTP status code as a string. | [
"The",
"HTTP",
"status",
"code",
"as",
"a",
"string."
] | def status(self):
return self._status | ['def', 'status(self):', 'return', 'self._status'] | 205,077 |
jtuyls/feedforward_neural_network_implementation | fully_connected_layer.py | FullyConnectedLayer.bprop | bprop | Calculate input gradient (backpropagation). | [
"Calculate",
"input",
"gradient",
"(backpropagation)."
] | def bprop(self, output_grad):
n = output_grad.shape[0]
if self.activation_fun:
output_grad = self.activation_fun.bprop(output_grad)
self.dW = self.last_input.transpose().dot(output_grad) / n
self.db = np.sum(output_grad, axis=0) / n
grad_input = output_grad.dot(self.W.transpose())
return... | ['def', 'bprop(self,', 'output_grad):', 'n', '=', 'output_grad.shape[0]', 'if', 'self.activation_fun:', 'output_grad', '=', 'self.activation_fun.bprop(output_grad)', 'self.dW', '=', 'self.last_input.transpose().dot(output_grad)', '/', 'n', 'self.db', '=', 'np.sum(output_grad,', 'axis=0)', '/', 'n', 'grad_input', '=', '... | 582,384 |
openvinotoolkit/training_extensions | composed_dataloaders_hook.py | ComposedDataLoadersHook.add_dataloaders | add_dataloaders | Create data_loaders to be added into composed dataloader. | [
"Create",
"data_loaders",
"to",
"be",
"added",
"into",
"composed",
"dataloader."
] | def add_dataloaders(self, data_loaders: Union[Sequence[DataLoader], DataLoader]):
if isinstance(data_loaders, DataLoader):
data_loaders = [data_loaders]
else:
data_loaders = list(data_loaders)
self.data_loaders.extend(data_loaders)
self.composed_loader = None | ['def', 'add_dataloaders(self,', 'data_loaders:', 'Union[Sequence[DataLoader],', 'DataLoader]):', 'if', 'isinstance(data_loaders,', 'DataLoader):', 'data_loaders', '=', '[data_loaders]', 'else:', 'data_loaders', '=', 'list(data_loaders)', 'self.data_loaders.extend(data_loaders)', 'self.composed_loader', '=', 'None'] | 917,800 |
zihuitang/medical_AI_platform | codecontext.py | CodeContext.update_code_context | update_code_context | Update context information and lines visible in the context pane. | [
"Update",
"context",
"information",
"and",
"lines",
"visible",
"in",
"the",
"context",
"pane."
] | def update_code_context(self):
new_topvisible = int(self.text.index('@0,0').split('.')[0])
if self.topvisible == new_topvisible:
return
if self.topvisible < new_topvisible:
(lines, lastindent) = self.get_context(new_topvisible, self.topvisible)
while self.info[-1][1] >= lastindent:
... | ['def', 'update_code_context(self):', 'new_topvisible', '=', "int(self.text.index('@0,0').split('.')[0])", 'if', 'self.topvisible', '==', 'new_topvisible:', 'return', 'if', 'self.topvisible', '<', 'new_topvisible:', '(lines,', 'lastindent)', '=', 'self.get_context(new_topvisible,', 'self.topvisible)', 'while', 'self.in... | 282,691 |
zihuitang/medical_AI_platform | _test_multiprocessing.py | check_enough_semaphores | check_enough_semaphores | Check that the system supports enough semaphores to run the test. | [
"Check",
"that",
"the",
"system",
"supports",
"enough",
"semaphores",
"to",
"run",
"the",
"test."
] | def check_enough_semaphores():
nsems_min = 256
try:
nsems = os.sysconf('SC_SEM_NSEMS_MAX')
except (AttributeError, ValueError):
return
if nsems == -1 or nsems >= nsems_min:
return
raise unittest.SkipTest("The OS doesn't support enough semaphores to run the test (required: %d)... | ['def', 'check_enough_semaphores():', 'nsems_min', '=', '256', 'try:', 'nsems', '=', "os.sysconf('SC_SEM_NSEMS_MAX')", 'except', '(AttributeError,', 'ValueError):', 'return', 'if', 'nsems', '==', '-1', 'or', 'nsems', '>=', 'nsems_min:', 'return', 'raise', 'unittest.SkipTest("The', 'OS', "doesn't", 'support', 'enough', ... | 283,768 |
fizyr/keras-retinanet | csv_generator.py | CSVGenerator.image_path | image_path | Returns the image path for image_index. | [
"Returns",
"the",
"image",
"path",
"for",
"image_index."
] | def image_path(self, image_index):
return os.path.join(self.base_dir, self.image_names[image_index]) | ['def', 'image_path(self,', 'image_index):', 'return', 'os.path.join(self.base_dir,', 'self.image_names[image_index])'] | 595,771 |
tensorflow/agents | utils.py | SquashToSpecNormal.kl_divergence | kl_divergence | Computes the KL Divergence between two SquashToSpecNormal distributions. | [
"Computes",
"the",
"KL",
"Divergence",
"between",
"two",
"SquashToSpecNormal",
"distributions."
] | def kl_divergence(self, other, name='kl_divergence'):
if not isinstance(other, SquashToSpecNormal):
raise ValueError('other distribution should be of type SquashToSpecNormal, got {}'.format(other))
if np.any(self.action_means != other.action_means) or np.any(self.action_magnitudes != other.action_magnit... | ['def', 'kl_divergence(self,', 'other,', "name='kl_divergence'):", 'if', 'not', 'isinstance(other,', 'SquashToSpecNormal):', 'raise', "ValueError('other", 'distribution', 'should', 'be', 'of', 'type', 'SquashToSpecNormal,', 'got', "{}'.format(other))", 'if', 'np.any(self.action_means', '!=', 'other.action_means)', 'or'... | 23,389 |
Gradiant/pyodi | clustering.py | get_max_overlap | get_max_overlap | Computes max intersection-over-union between box and anchors. | [
"Computes",
"max",
"intersection-over-union",
"between",
"box",
"and",
"anchors."
] | def get_max_overlap(boxes: ndarray, anchors: ndarray) -> ndarray:
rows = boxes.shape[0]
cols = anchors.shape[0]
overlap = np.zeros(rows, dtype=np.float32)
box_areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
anchors_areas = (anchors[:, 2] - anchors[:, 0]) * (anchors[:, 3] - anchors[... | ['def', 'get_max_overlap(boxes:', 'ndarray,', 'anchors:', 'ndarray)', '->', 'ndarray:', 'rows', '=', 'boxes.shape[0]', 'cols', '=', 'anchors.shape[0]', 'overlap', '=', 'np.zeros(rows,', 'dtype=np.float32)', 'box_areas', '=', '(boxes[:,', '2]', '-', 'boxes[:,', '0])', '*', '(boxes[:,', '3]', '-', 'boxes[:,', '1])', 'anc... | 808,998 |
dellis23/disrupt | main.py | rainbow | rainbow | Changes the target terminal's text to a random color. | [
"Changes",
"the",
"target",
"terminal's",
"text",
"to",
"a",
"random",
"color."
] | def rainbow(term, verbosity):
interval = get_interval(verbosity)
dev = os.open(term, os.O_WRONLY)
while True:
for color in cycle(COLORS):
os.write(dev, color)
sleep(interval) | ['def', 'rainbow(term,', 'verbosity):', 'interval', '=', 'get_interval(verbosity)', 'dev', '=', 'os.open(term,', 'os.O_WRONLY)', 'while', 'True:', 'for', 'color', 'in', 'cycle(COLORS):', 'os.write(dev,', 'color)', 'sleep(interval)'] | 187,567 |
MushroomRL/mushroom-rl | fourier.py | FourierBasis.generate | generate | Factory method to build a set of fourier basis. | [
"Factory",
"method",
"to",
"build",
"a",
"set",
"of",
"fourier",
"basis."
] | def generate(low, high, n, dimensions=None):
if dimensions is not None:
assert len(low) == len(dimensions)
input_size = len(low)
delta = high - low
n_basis = (n + 1) ** input_size
basis_list = list()
for index in range(n_basis):
c = np.zeros(input_size)
value = index
... | ['def', 'generate(low,', 'high,', 'n,', 'dimensions=None):', 'if', 'dimensions', 'is', 'not', 'None:', 'assert', 'len(low)', '==', 'len(dimensions)', 'input_size', '=', 'len(low)', 'delta', '=', 'high', '-', 'low', 'n_basis', '=', '(n', '+', '1)', '**', 'input_size', 'basis_list', '=', 'list()', 'for', 'index', 'in', '... | 266,060 |
SamsungLabs/imvoxelnet | primitive_head.py | PrimitiveHead.get_primitive_center | get_primitive_center | Generate primitive center from predictions. | [
"Generate",
"primitive",
"center",
"from",
"predictions."
] | def get_primitive_center(self, pred_flag, center):
ind_normal = F.softmax(pred_flag, dim=1)
pred_indices = (ind_normal[:, 1, :] > self.surface_thresh).detach().float()
selected = (ind_normal[:, 1, :] <= self.surface_thresh).detach().float()
offset = torch.ones_like(center) * self.upper_thresh
center... | ['def', 'get_primitive_center(self,', 'pred_flag,', 'center):', 'ind_normal', '=', 'F.softmax(pred_flag,', 'dim=1)', 'pred_indices', '=', '(ind_normal[:,', '1,', ':]', '>', 'self.surface_thresh).detach().float()', 'selected', '=', '(ind_normal[:,', '1,', ':]', '<=', 'self.surface_thresh).detach().float()', 'offset', '=... | 612,114 |
RLE-Foundation/rllte | squashed_normal.py | SquashedNormal.sample | sample | Generates a sample_shape shaped sample or sample_shape shaped batch of samples if the distribution parameters are batched. | [
"Generates",
"a",
"sample_shape",
"shaped",
"sample",
"or",
"sample_shape",
"shaped",
"batch",
"of",
"samples",
"if",
"the",
"distribution",
"parameters",
"are",
"batched."
] | def sample(self, sample_shape: th.Size=th.Size()) -> th.Tensor:
return self.dist.sample(sample_shape) | ['def', 'sample(self,', 'sample_shape:', 'th.Size=th.Size())', '->', 'th.Tensor:', 'return', 'self.dist.sample(sample_shape)'] | 333,667 |
CarperAI/trlx | modeling_base.py | PreTrainedModelWrapper.from_config | from_config | Instantiate the pretrained pytorch model from a configuration. | [
"Instantiate",
"the",
"pretrained",
"pytorch",
"model",
"from",
"a",
"configuration."
] | def from_config(cls, config: transformers.PretrainedConfig, peft_config=None, **kwargs):
if kwargs is not None:
(wrapped_model_kwargs, from_config_kwargs) = cls._split_kwargs(kwargs)
else:
from_config_kwargs = {}
wrapped_model_kwargs = {}
base_model = cls._auto_model_parent_class.fro... | ['def', 'from_config(cls,', 'config:', 'transformers.PretrainedConfig,', 'peft_config=None,', '**kwargs):', 'if', 'kwargs', 'is', 'not', 'None:', '(wrapped_model_kwargs,', 'from_config_kwargs)', '=', 'cls._split_kwargs(kwargs)', 'else:', 'from_config_kwargs', '=', '{}', 'wrapped_model_kwargs', '=', '{}', 'base_model', ... | 426,113 |
zcablii/LSKNet | rotate_iou2d_calculator.py | rbbox_overlaps | rbbox_overlaps | Calculate overlap between two set of bboxes. | [
"Calculate",
"overlap",
"between",
"two",
"set",
"of",
"bboxes."
] | def rbbox_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False):
assert mode in ['iou', 'iof']
assert bboxes1.size(-1) == 5 or bboxes1.size(0) == 0
assert bboxes2.size(-1) == 5 or bboxes2.size(0) == 0
rows = bboxes1.size(0)
cols = bboxes2.size(0)
if is_aligned:
assert rows == cols
... | ['def', 'rbbox_overlaps(bboxes1,', 'bboxes2,', "mode='iou',", 'is_aligned=False):', 'assert', 'mode', 'in', "['iou',", "'iof']", 'assert', 'bboxes1.size(-1)', '==', '5', 'or', 'bboxes1.size(0)', '==', '0', 'assert', 'bboxes2.size(-1)', '==', '5', 'or', 'bboxes2.size(0)', '==', '0', 'rows', '=', 'bboxes1.size(0)', 'cols... | 616,059 |
zhaocq-nlp/NJUNMT-tf | decode.py | evaluate_with_attention | evaluate_with_attention | Evaluates data by loss. | [
"Evaluates",
"data",
"by",
"loss."
] | def evaluate_with_attention(sess, loss_op, eval_data, vocab_source, vocab_target, attention_op=None, output_filename_prefix=None):
losses = 0.0
weights = 0.0
num_of_samples = 0
attentions = {}
for data in eval_data:
_n_samples = len(data['feature_ids'])
parallels = data['feed_dict'].... | ['def', 'evaluate_with_attention(sess,', 'loss_op,', 'eval_data,', 'vocab_source,', 'vocab_target,', 'attention_op=None,', 'output_filename_prefix=None):', 'losses', '=', '0.0', 'weights', '=', '0.0', 'num_of_samples', '=', '0', 'attentions', '=', '{}', 'for', 'data', 'in', 'eval_data:', '_n_samples', '=', "len(data['f... | 782,848 |
befelix/safe_learning | utilities.py | compute_roa | compute_roa | Compute the largest ROA as a set of states in a discretization. | [
"Compute",
"the",
"largest",
"ROA",
"as",
"a",
"set",
"of",
"states",
"in",
"a",
"discretization."
] | def compute_roa(grid, closed_loop_dynamics, horizon=100, tol=0.001, equilibrium=None, no_traj=True):
if isinstance(grid, np.ndarray):
all_points = grid
nindex = grid.shape[0]
ndim = grid.shape[1]
else:
all_points = grid.all_points
nindex = grid.nindex
ndim = grid.... | ['def', 'compute_roa(grid,', 'closed_loop_dynamics,', 'horizon=100,', 'tol=0.001,', 'equilibrium=None,', 'no_traj=True):', 'if', 'isinstance(grid,', 'np.ndarray):', 'all_points', '=', 'grid', 'nindex', '=', 'grid.shape[0]', 'ndim', '=', 'grid.shape[1]', 'else:', 'all_points', '=', 'grid.all_points', 'nindex', '=', 'gri... | 328,115 |
replit-archive/empythoned | analyze_dxp.py | has_pairs | has_pairs | Returns True if the Python that produced the argument profile was built with -DDXPAIRS. | [
"Returns",
"True",
"if",
"the",
"Python",
"that",
"produced",
"the",
"argument",
"profile",
"was",
"built",
"with",
"-DDXPAIRS."
] | def has_pairs(profile):
return len(profile) > 0 and isinstance(profile[0], list) | ['def', 'has_pairs(profile):', 'return', 'len(profile)', '>', '0', 'and', 'isinstance(profile[0],', 'list)'] | 177,115 |
myothida/Supervised-Machine-Learning | test_forest.py | test_random_trees_embedding_feature_names_out | test_random_trees_embedding_feature_names_out | Check feature names out for Random Trees Embedding. | [
"Check",
"feature",
"names",
"out",
"for",
"Random",
"Trees",
"Embedding."
] | def test_random_trees_embedding_feature_names_out():
random_state = np.random.RandomState(0)
X = np.abs(random_state.randn(100, 4))
hasher = RandomTreesEmbedding(n_estimators=2, max_depth=2, sparse_output=False, random_state=0).fit(X)
names = hasher.get_feature_names_out()
expected_names = [f'random... | ['def', 'test_random_trees_embedding_feature_names_out():', 'random_state', '=', 'np.random.RandomState(0)', 'X', '=', 'np.abs(random_state.randn(100,', '4))', 'hasher', '=', 'RandomTreesEmbedding(n_estimators=2,', 'max_depth=2,', 'sparse_output=False,', 'random_state=0).fit(X)', 'names', '=', 'hasher.get_feature_names... | 363,785 |
tdekeyser/dentalvision | structure.py | Shape.centroid | centroid | Compute the centroid: the average of an array of coordinates. | [
"Compute",
"the",
"centroid:",
"the",
"average",
"of",
"an",
"array",
"of",
"coordinates."
] | def centroid(self):
return (np.sum(self.x) / self.x.shape, np.sum(self.y) / self.y.shape) | ['def', 'centroid(self):', 'return', '(np.sum(self.x)', '/', 'self.x.shape,', 'np.sum(self.y)', '/', 'self.y.shape)'] | 538,143 |
dmcnamee/FlexModEHC | utils.py | eig | eig | Computes eigenvectors and returns them in eigenvalue order. | [
"Computes",
"eigenvectors",
"and",
"returns",
"them",
"in",
"eigenvalue",
"order."
] | def eig(x, order='descend', sortby=signed_amp):
assert x.shape[0] == x.shape[1]
n = x.shape[0]
(evals, evecs) = np.linalg.eig(x)
ind_order = list(range(n))
ind_order = [x for (_, x) in sorted(zip(sortby(evals), ind_order))]
if order == 'descend':
ind_order = ind_order[::-1]
evals = e... | ['def', 'eig(x,', "order='descend',", 'sortby=signed_amp):', 'assert', 'x.shape[0]', '==', 'x.shape[1]', 'n', '=', 'x.shape[0]', '(evals,', 'evecs)', '=', 'np.linalg.eig(x)', 'ind_order', '=', 'list(range(n))', 'ind_order', '=', '[x', 'for', '(_,', 'x)', 'in', 'sorted(zip(sortby(evals),', 'ind_order))]', 'if', 'order',... | 585,251 |
mfbx9da4/neuron-astrocyte-networks | learning.py | LearningAgent.learn | learn | Call the learner's learn method, which has access to both module and history. | [
"Call",
"the",
"learner's",
"learn",
"method,",
"which",
"has",
"access",
"to",
"both",
"module",
"and",
"history."
] | def learn(self, episodes=1):
if self.learning:
self.learner.learnEpisodes(episodes) | ['def', 'learn(self,', 'episodes=1):', 'if', 'self.learning:', 'self.learner.learnEpisodes(episodes)'] | 722,518 |
lektor/lektor-archive | environment.py | Config.site_locale | site_locale | The locale of this project. | [
"The",
"locale",
"of",
"this",
"project."
] | def site_locale(self):
return self.values['PROJECT']['locale'] | ['def', 'site_locale(self):', 'return', "self.values['PROJECT']['locale']"] | 216,444 |
shanglianlm0525/CvPytorch | det_transforms_pil.py | GaussianBlur.get_params | get_params | Choose sigma for random gaussian blurring. | [
"Choose",
"sigma",
"for",
"random",
"gaussian",
"blurring."
] | def get_params(sigma_min: float, sigma_max: float) -> float:
return torch.empty(1).uniform_(sigma_min, sigma_max).item() | ['def', 'get_params(sigma_min:', 'float,', 'sigma_max:', 'float)', '->', 'float:', 'return', 'torch.empty(1).uniform_(sigma_min,', 'sigma_max).item()'] | 523,403 |
jariasf/GMVAE | base.py | ConditionalCategorical.condition | condition | Computes the logits of a RelaxedOneHotCategorical distribution. | [
"Computes",
"the",
"logits",
"of",
"a",
"RelaxedOneHotCategorical",
"distribution."
] | def condition(self, tensor_list, **unused_kwargs):
inputs = tf.concat(tensor_list, axis=1)
return self._fcnet(inputs) | ['def', 'condition(self,', 'tensor_list,', '**unused_kwargs):', 'inputs', '=', 'tf.concat(tensor_list,', 'axis=1)', 'return', 'self._fcnet(inputs)'] | 578,487 |
zhaocq-nlp/NJUNMT-tf | modality.py | Modality.default_params | default_params | Returns a dictionary of default parameters of this modality. | [
"Returns",
"a",
"dictionary",
"of",
"default",
"parameters",
"of",
"this",
"modality."
] | def default_params():
return {'multiply_embedding_mode': None, 'share_embedding_and_softmax_weights': False, 'dropout_logit_keep_prob': 1.0, 'initializer': None, 'loss': 'crossentropy', 'timing': None} | ['def', 'default_params():', 'return', "{'multiply_embedding_mode':", 'None,', "'share_embedding_and_softmax_weights':", 'False,', "'dropout_logit_keep_prob':", '1.0,', "'initializer':", 'None,', "'loss':", "'crossentropy',", "'timing':", 'None}'] | 782,877 |
open-mmlab/mmselfsup | maskfeat_mvit.py | MaskFeatMViT.init_weights | init_weights | Initialize mask token and cls token. | [
"Initialize",
"mask",
"token",
"and",
"cls",
"token."
] | def init_weights(self) -> None:
super().init_weights()
if isinstance(self.init_cfg, dict) and self.init_cfg['type'] == 'Pretrained':
return
nn.init.trunc_normal_(self.cls_token, std=0.02)
nn.init.trunc_normal_(self.mask_token, std=0.02) | ['def', 'init_weights(self)', '->', 'None:', 'super().init_weights()', 'if', 'isinstance(self.init_cfg,', 'dict)', 'and', "self.init_cfg['type']", '==', "'Pretrained':", 'return', 'nn.init.trunc_normal_(self.cls_token,', 'std=0.02)', 'nn.init.trunc_normal_(self.mask_token,', 'std=0.02)'] | 240,490 |
sktime/sktime | test_data_io.py | test_write_dataframe_to_ts_fail | test_write_dataframe_to_ts_fail | Tests if non-dataframes are handled correctly. | [
"Tests",
"if",
"non-dataframes",
"are",
"handled",
"correctly."
] | def test_write_dataframe_to_ts_fail(tmp_path):
with pytest.raises(ValueError, match='Data provided must be a DataFrame'):
write_dataframe_to_tsfile(data=np.random.rand(3, 2), path=str(tmp_path), problem_name='GunPoint') | ['def', 'test_write_dataframe_to_ts_fail(tmp_path):', 'with', 'pytest.raises(ValueError,', "match='Data", 'provided', 'must', 'be', 'a', "DataFrame'):", 'write_dataframe_to_tsfile(data=np.random.rand(3,', '2),', 'path=str(tmp_path),', "problem_name='GunPoint')"] | 886,109 |
Kvatsx/Artificial-Intelligence-Assignments | inputtransformer2.py | SystemAssign.find | find | Find the first system assignment (a = !foo) in the cell. | [
"Find",
"the",
"first",
"system",
"assignment",
"(a",
"=",
"!foo)",
"in",
"the",
"cell."
] | def find(cls, tokens_by_line):
for line in tokens_by_line:
assign_ix = _find_assign_op(line)
if assign_ix is not None and (not line[assign_ix].line.strip().startswith('=')) and (len(line) >= assign_ix + 2) and (line[assign_ix + 1].type == tokenize.ERRORTOKEN):
ix = assign_ix + 1
... | ['def', 'find(cls,', 'tokens_by_line):', 'for', 'line', 'in', 'tokens_by_line:', 'assign_ix', '=', '_find_assign_op(line)', 'if', 'assign_ix', 'is', 'not', 'None', 'and', '(not', "line[assign_ix].line.strip().startswith('='))", 'and', '(len(line)', '>=', 'assign_ix', '+', '2)', 'and', '(line[assign_ix', '+', '1].type',... | 38,054 |
weimin17/Object-Detection_HelmetDetection | contextual_dataset.py | ContextualDataset.get_data | get_data | Returns all (context, reward) where the action was played. | [
"Returns",
"all",
"(context,",
"reward)",
"where",
"the",
"action",
"was",
"played."
] | def get_data(self, action):
(n, _) = self.contexts.shape
ind = np.array([i for i in range(n) if self.actions[i] == action])
return (self.contexts[ind, :], self.rewards[ind, action]) | ['def', 'get_data(self,', 'action):', '(n,', '_)', '=', 'self.contexts.shape', 'ind', '=', 'np.array([i', 'for', 'i', 'in', 'range(n)', 'if', 'self.actions[i]', '==', 'action])', 'return', '(self.contexts[ind,', ':],', 'self.rewards[ind,', 'action])'] | 762,345 |
QData/deepWordBug | math2html.py | ParameterFunction.readparams | readparams | Read the params according to the template. | [
"Read",
"the",
"params",
"according",
"to",
"the",
"template."
] | def readparams(self, readtemplate, pos):
self.params = dict()
for paramdef in self.paramdefs(readtemplate):
paramdef.read(pos, self)
self.params['$' + paramdef.name] = paramdef | ['def', 'readparams(self,', 'readtemplate,', 'pos):', 'self.params', '=', 'dict()', 'for', 'paramdef', 'in', 'self.paramdefs(readtemplate):', 'paramdef.read(pos,', 'self)', "self.params['$'", '+', 'paramdef.name]', '=', 'paramdef'] | 542,634 |
rudranil723/mini-main | TupleVariation.py | TupleVariation.getCoordWidth | getCoordWidth | Return 2 if coordinates are (x, y) as in gvar, 1 if single values as in cvar, or 0 if empty. | [
"Return",
"2",
"if",
"coordinates",
"are",
"(x,",
"y)",
"as",
"in",
"gvar,",
"1",
"if",
"single",
"values",
"as",
"in",
"cvar,",
"or",
"0",
"if",
"empty."
] | def getCoordWidth(self):
firstDelta = next((c for c in self.coordinates if c is not None), None)
if firstDelta is None:
return 0
if type(firstDelta) in (int, float):
return 1
if type(firstDelta) is tuple and len(firstDelta) == 2:
return 2
raise TypeError('invalid type of delt... | ['def', 'getCoordWidth(self):', 'firstDelta', '=', 'next((c', 'for', 'c', 'in', 'self.coordinates', 'if', 'c', 'is', 'not', 'None),', 'None)', 'if', 'firstDelta', 'is', 'None:', 'return', '0', 'if', 'type(firstDelta)', 'in', '(int,', 'float):', 'return', '1', 'if', 'type(firstDelta)', 'is', 'tuple', 'and', 'len(firstDe... | 317,471 |
facebookresearch/Detectron | dataset_catalog.py | get_devkit_dir | get_devkit_dir | Retrieve the devkit dir for the dataset. | [
"Retrieve",
"the",
"devkit",
"dir",
"for",
"the",
"dataset."
] | def get_devkit_dir(name):
return _DATASETS[name][_DEVKIT_DIR] | ['def', 'get_devkit_dir(name):', 'return', '_DATASETS[name][_DEVKIT_DIR]'] | 548,860 |
fundamentalvision/BEVFormer | transform3d.py | Transform3d.stack | stack | Return a new batched Transform3d representing the batch elements from self and all the given other transforms all batched together. | [
"Return",
"a",
"new",
"batched",
"Transform3d",
"representing",
"the",
"batch",
"elements",
"from",
"self",
"and",
"all",
"the",
"given",
"other",
"transforms",
"all",
"batched",
"together."
] | def stack(self, *others: 'Transform3d') -> 'Transform3d':
transforms = [self] + list(others)
matrix = torch.cat([t.get_matrix() for t in transforms], dim=0)
out = Transform3d(dtype=self.dtype, device=self.device)
out._matrix = matrix
return out | ['def', 'stack(self,', '*others:', "'Transform3d')", '->', "'Transform3d':", 'transforms', '=', '[self]', '+', 'list(others)', 'matrix', '=', 'torch.cat([t.get_matrix()', 'for', 't', 'in', 'transforms],', 'dim=0)', 'out', '=', 'Transform3d(dtype=self.dtype,', 'device=self.device)', 'out._matrix', '=', 'matrix', 'return... | 434,340 |
tencent-ailab/TriNet | meters.py | MetersDict.get_smoothed_values | get_smoothed_values | Get all smoothed values. | [
"Get",
"all",
"smoothed",
"values."
] | def get_smoothed_values(self) -> Dict[str, float]:
return OrderedDict([(key, self.get_smoothed_value(key)) for key in self.keys() if not key.startswith('_')]) | ['def', 'get_smoothed_values(self)', '->', 'Dict[str,', 'float]:', 'return', 'OrderedDict([(key,', 'self.get_smoothed_value(key))', 'for', 'key', 'in', 'self.keys()', 'if', 'not', "key.startswith('_')])"] | 425,266 |
calico/basenji | layers.py | gamma_pdf | gamma_pdf | Gamma probability distribution function: p(x|concentration, rate). | [
"Gamma",
"probability",
"distribution",
"function:",
"p(x|concentration,",
"rate)."
] | def gamma_pdf(x, concentration, rate):
log_unnormalized_prob = tf.math.xlogy(concentration - 1.0, x) - rate * x
log_normalization = tf.math.lgamma(concentration) - concentration * tf.math.log(rate)
return tf.exp(log_unnormalized_prob - log_normalization) | ['def', 'gamma_pdf(x,', 'concentration,', 'rate):', 'log_unnormalized_prob', '=', 'tf.math.xlogy(concentration', '-', '1.0,', 'x)', '-', 'rate', '*', 'x', 'log_normalization', '=', 'tf.math.lgamma(concentration)', '-', 'concentration', '*', 'tf.math.log(rate)', 'return', 'tf.exp(log_unnormalized_prob', '-', 'log_normal... | 94,575 |
keras-team/keras-cv | vit.py | ViTH16 | ViTH16 | Instantiates the ViTH16 architecture. | [
"Instantiates",
"the",
"ViTH16",
"architecture."
] | def ViTH16(*, include_rescaling, include_top, name='ViTH16', weights=None, input_shape=(None, None, 3), input_tensor=None, pooling=None, num_classes=None, activation=keras.activations.gelu, classifier_activation='softmax', **kwargs):
return ViT(include_rescaling, include_top, name=name, weights=weights, input_shape... | ['def', 'ViTH16(*,', 'include_rescaling,', 'include_top,', "name='ViTH16',", 'weights=None,', 'input_shape=(None,', 'None,', '3),', 'input_tensor=None,', 'pooling=None,', 'num_classes=None,', 'activation=keras.activations.gelu,', "classifier_activation='softmax',", '**kwargs):', 'return', 'ViT(include_rescaling,', 'inc... | 595,295 |
PyRetri/PyRetri | misc.py | save_to_csv | save_to_csv | Save the search results in a csv format file. | [
"Save",
"the",
"search",
"results",
"in",
"a",
"csv",
"format",
"file."
] | def save_to_csv(results: List[Dict], csv_path: str) -> None:
start = ['data', 'pre_process', 'model', 'feature_map', 'aggregator', 'post_process']
for i in range(len(start)):
results = sorted(results, key=lambda result: result[start[len(start) - i - 1] + '_name'])
start.append('mAP')
start.appen... | ['def', 'save_to_csv(results:', 'List[Dict],', 'csv_path:', 'str)', '->', 'None:', 'start', '=', "['data',", "'pre_process',", "'model',", "'feature_map',", "'aggregator',", "'post_process']", 'for', 'i', 'in', 'range(len(start)):', 'results', '=', 'sorted(results,', 'key=lambda', 'result:', 'result[start[len(start)', ... | 297,234 |
jindongwang/transferlearning | ctc_aligner.py | pad_list | pad_list | Convert list of Tensors to a single Tensor with padding. | [
"Convert",
"list",
"of",
"Tensors",
"to",
"a",
"single",
"Tensor",
"with",
"padding."
] | def pad_list(xs, pad_value=0.0, pad_left=False):
bs = len(xs)
max_time = max((x.size(0) for x in xs))
xs_pad = xs[0].new_zeros(bs, max_time, *xs[0].size()[1:]).fill_(pad_value)
for b in range(bs):
if len(xs[b]) == 0:
continue
if pad_left:
xs_pad[b, -xs[b].size(0):... | ['def', 'pad_list(xs,', 'pad_value=0.0,', 'pad_left=False):', 'bs', '=', 'len(xs)', 'max_time', '=', 'max((x.size(0)', 'for', 'x', 'in', 'xs))', 'xs_pad', '=', 'xs[0].new_zeros(bs,', 'max_time,', '*xs[0].size()[1:]).fill_(pad_value)', 'for', 'b', 'in', 'range(bs):', 'if', 'len(xs[b])', '==', '0:', 'continue', 'if', 'pa... | 904,500 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | ccompiler.py | CCompiler.add_link_object | add_link_object | Add 'object' to the list of object files (or analogues, such as explicitly named library files or the output of "resource compilers") to be included in every link driven by this compiler object. | [
"Add",
"'object'",
"to",
"the",
"list",
"of",
"object",
"files",
"(or",
"analogues,",
"such",
"as",
"explicitly",
"named",
"library",
"files",
"or",
"the",
"output",
"of",
"\"resource",
"compilers\")",
"to",
"be",
"included",
"in",
"every",
"link",
"driven",
... | def add_link_object(self, object):
self.objects.append(object) | ['def', 'add_link_object(self,', 'object):', 'self.objects.append(object)'] | 430,266 |
benbenboben/matstract | token_ann_app.py | serve_macro_annotation | serve_macro_annotation | Things like experimental vs theoretical, inorganic vs organic, etc. | [
"Things",
"like",
"experimental",
"vs",
"theoretical,",
"inorganic",
"vs",
"organic,",
"etc."
] | def serve_macro_annotation(db, display):
tags = []
for tag in db.abstract_tags.find({}):
tags.append({'label': tag['tag'], 'value': tag['tag']})
return [html.Div([html.Div('Tags: ', className='two columns'), html.Div(dmi.DropdownCreatable(options=tags, id='abstract_tags', multi=True, value=''), clas... | ['def', 'serve_macro_annotation(db,', 'display):', 'tags', '=', '[]', 'for', 'tag', 'in', 'db.abstract_tags.find({}):', "tags.append({'label':", "tag['tag'],", "'value':", "tag['tag']})", 'return', "[html.Div([html.Div('Tags:", "',", "className='two", "columns'),", 'html.Div(dmi.DropdownCreatable(options=tags,', "id='a... | 646,247 |
devashish-patel/webcam-motion-detector | menus.py | MultiColumnCompletionMenuControl.mouse_handler | mouse_handler | Handle scoll and click events. | [
"Handle",
"scoll",
"and",
"click",
"events."
] | def mouse_handler(self, cli, mouse_event):
b = cli.current_buffer
def scroll_left():
b.complete_previous(count=self._rendered_rows, disable_wrap_around=True)
self.scroll = max(0, self.scroll - 1)
def scroll_right():
b.complete_next(count=self._rendered_rows, disable_wrap_around=Tru... | ['def', 'mouse_handler(self,', 'cli,', 'mouse_event):', 'b', '=', 'cli.current_buffer', 'def', 'scroll_left():', 'b.complete_previous(count=self._rendered_rows,', 'disable_wrap_around=True)', 'self.scroll', '=', 'max(0,', 'self.scroll', '-', '1)', 'def', 'scroll_right():', 'b.complete_next(count=self._rendered_rows,', ... | 984,028 |
Kvatsx/Artificial-Intelligence-Assignments | compare.py | make_test_filename | make_test_filename | Make a new filename by inserting `purpose` before the file's extension. | [
"Make",
"a",
"new",
"filename",
"by",
"inserting",
"`purpose`",
"before",
"the",
"file's",
"extension."
] | def make_test_filename(fname, purpose):
(base, ext) = os.path.splitext(fname)
return '%s-%s%s' % (base, purpose, ext) | ['def', 'make_test_filename(fname,', 'purpose):', '(base,', 'ext)', '=', 'os.path.splitext(fname)', 'return', "'%s-%s%s'", '%', '(base,', 'purpose,', 'ext)'] | 1,343 |
aws/sagemaker-python-sdk | fw_utils.py | framework_version_from_tag | framework_version_from_tag | Extract the framework version from the image tag. | [
"Extract",
"the",
"framework",
"version",
"from",
"the",
"image",
"tag."
] | def framework_version_from_tag(image_tag):
tag_pattern = re.compile('^(.*)-(cpu|gpu)-(py2|py3\\d*)$')
tag_match = tag_pattern.match(image_tag)
if tag_match is None:
short_xgboost_tag_pattern = re.compile('^(\\d\\.\\d+\\-\\d)$')
tag_match = short_xgboost_tag_pattern.match(image_tag)
retur... | ['def', 'framework_version_from_tag(image_tag):', 'tag_pattern', '=', "re.compile('^(.*)-(cpu|gpu)-(py2|py3\\\\d*)$')", 'tag_match', '=', 'tag_pattern.match(image_tag)', 'if', 'tag_match', 'is', 'None:', 'short_xgboost_tag_pattern', '=', "re.compile('^(\\\\d\\\\.\\\\d+\\\\-\\\\d)$')", 'tag_match', '=', 'short_xgboost_t... | 829,479 |
tencent-ailab/TriNet | trainer.py | Trainer.begin_epoch | begin_epoch | Called at the beginning of each epoch. | [
"Called",
"at",
"the",
"beginning",
"of",
"each",
"epoch."
] | def begin_epoch(self, epoch):
logger.info('begin training epoch {}'.format(epoch))
self.lr_step_begin_epoch(epoch)
if self.quantizer is not None:
self.quantizer.begin_epoch(epoch)
self.task.begin_epoch(epoch, self.get_model())
if self.tpu:
import torch_xla.core.xla_model as xm
... | ['def', 'begin_epoch(self,', 'epoch):', "logger.info('begin", 'training', 'epoch', "{}'.format(epoch))", 'self.lr_step_begin_epoch(epoch)', 'if', 'self.quantizer', 'is', 'not', 'None:', 'self.quantizer.begin_epoch(epoch)', 'self.task.begin_epoch(epoch,', 'self.get_model())', 'if', 'self.tpu:', 'import', 'torch_xla.core... | 425,039 |
Kvatsx/Artificial-Intelligence-Assignments | logs.py | logOnFail | logOnFail | Produce possible log-wrapped version of function function -- callable object to be wrapped log -- the log to which to log information Uses ERROR_LOGGING and FULL_LOGGING to determine whether/how to wrap the function. | [
"Produce",
"possible",
"log-wrapped",
"version",
"of",
"function",
"function",
"--",
"callable",
"object",
"to",
"be",
"wrapped",
"log",
"--",
"the",
"log",
"to",
"which",
"to",
"log",
"information",
"Uses",
"ERROR_LOGGING",
"and",
"FULL_LOGGING",
"to",
"determi... | def logOnFail(function, log):
if ERROR_LOGGING or FULL_LOGGING:
if FULL_LOGGING:
loggedFunction = _FullLoggedFunction(function, log)
else:
loggedFunction = _ErrorLoggedFunction(function, log)
return loggedFunction
else:
return function | ['def', 'logOnFail(function,', 'log):', 'if', 'ERROR_LOGGING', 'or', 'FULL_LOGGING:', 'if', 'FULL_LOGGING:', 'loggedFunction', '=', '_FullLoggedFunction(function,', 'log)', 'else:', 'loggedFunction', '=', '_ErrorLoggedFunction(function,', 'log)', 'return', 'loggedFunction', 'else:', 'return', 'function'] | 3,055 |
sunishsheth2009/ChatterBot | git.py | Git.get_refs | get_refs | Return map of named refs (branches or tags) to commit hashes. | [
"Return",
"map",
"of",
"named",
"refs",
"(branches",
"or",
"tags)",
"to",
"commit",
"hashes."
] | def get_refs(self, location):
output = call_subprocess([self.cmd, 'show-ref'], show_stdout=False, cwd=location)
rv = {}
for line in output.strip().splitlines():
(commit, ref) = line.split(' ', 1)
ref = ref.strip()
ref_name = None
if ref.startswith('refs/remotes/'):
... | ['def', 'get_refs(self,', 'location):', 'output', '=', 'call_subprocess([self.cmd,', "'show-ref'],", 'show_stdout=False,', 'cwd=location)', 'rv', '=', '{}', 'for', 'line', 'in', 'output.strip().splitlines():', '(commit,', 'ref)', '=', "line.split('", "',", '1)', 'ref', '=', 'ref.strip()', 'ref_name', '=', 'None', 'if',... | 532,949 |
arshpreetsingh/quantopian-machinelearning | _compat.py | just_warn | just_warn | We only warn on Python 3 because we are not aware of any concrete consequences of not setting the cell on Python 2. | [
"We",
"only",
"warn",
"on",
"Python",
"3",
"because",
"we",
"are",
"not",
"aware",
"of",
"any",
"concrete",
"consequences",
"of",
"not",
"setting",
"the",
"cell",
"on",
"Python",
"2."
] | def just_warn(*args, **kw):
warnings.warn('Missing ctypes. Some features like bare super() or accessing __class__ will not work with slotted classes.', RuntimeWarning, stacklevel=2) | ['def', 'just_warn(*args,', '**kw):', "warnings.warn('Missing", 'ctypes.', 'Some', 'features', 'like', 'bare', 'super()', 'or', 'accessing', '__class__', 'will', 'not', 'work', 'with', 'slotted', "classes.',", 'RuntimeWarning,', 'stacklevel=2)'] | 816,390 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | pixelda_model.py | resnet_block | resnet_block | Create a resnet block. | [
"Create",
"a",
"resnet",
"block."
] | def resnet_block(net, hparams):
net_in = net
net = slim.conv2d(net, hparams.resnet_filters, stride=1, normalizer_fn=slim.batch_norm, activation_fn=tf.nn.relu)
net = slim.conv2d(net, hparams.resnet_filters, stride=1, normalizer_fn=slim.batch_norm, activation_fn=None)
if hparams.resnet_residuals:
... | ['def', 'resnet_block(net,', 'hparams):', 'net_in', '=', 'net', 'net', '=', 'slim.conv2d(net,', 'hparams.resnet_filters,', 'stride=1,', 'normalizer_fn=slim.batch_norm,', 'activation_fn=tf.nn.relu)', 'net', '=', 'slim.conv2d(net,', 'hparams.resnet_filters,', 'stride=1,', 'normalizer_fn=slim.batch_norm,', 'activation_fn=... | 54,433 |
accel-brain/accel-brain-code | observing_media.py | ObservingMedia.extract_media | extract_media | Extracting tokens of media. | [
"Extracting",
"tokens",
"of",
"media."
] | def extract_media(self, test_mode=True):
all_data_arr = None
for (encoded_observed_arr, decoded_observed_arr, encoded_mask_arr, decoded_mask_arr, token_list) in self.transformer_iterator.generate_samples_and_noises(test_mode=test_mode):
decoded_arr = self.transformer_controller.inference(encoded_observe... | ['def', 'extract_media(self,', 'test_mode=True):', 'all_data_arr', '=', 'None', 'for', '(encoded_observed_arr,', 'decoded_observed_arr,', 'encoded_mask_arr,', 'decoded_mask_arr,', 'token_list)', 'in', 'self.transformer_iterator.generate_samples_and_noises(test_mode=test_mode):', 'decoded_arr', '=', 'self.transformer_co... | 7,143 |
shiwt03/MUSTER | class_names.py | loveda_palette | loveda_palette | LoveDA palette for external use. | [
"LoveDA",
"palette",
"for",
"external",
"use."
] | def loveda_palette():
return [[255, 255, 255], [255, 0, 0], [255, 255, 0], [0, 0, 255], [159, 129, 183], [0, 255, 0], [255, 195, 128]] | ['def', 'loveda_palette():', 'return', '[[255,', '255,', '255],', '[255,', '0,', '0],', '[255,', '255,', '0],', '[0,', '0,', '255],', '[159,', '129,', '183],', '[0,', '255,', '0],', '[255,', '195,', '128]]'] | 644,783 |
jpush/jpush-api-python-client | core.py | Device.set_deviceinfo | set_deviceinfo | Update deviceinfo with registration id. | [
"Update",
"deviceinfo",
"with",
"registration",
"id."
] | def set_deviceinfo(self, registration_id, entity):
url = common.get_url('device', self.zone) + registration_id
body = json.dumps(entity)
info = self.send('POST', url, body)
return info | ['def', 'set_deviceinfo(self,', 'registration_id,', 'entity):', 'url', '=', "common.get_url('device',", 'self.zone)', '+', 'registration_id', 'body', '=', 'json.dumps(entity)', 'info', '=', "self.send('POST',", 'url,', 'body)', 'return', 'info'] | 247,150 |
gunthercox/ChatterBot | api.py | ModelI.prob | prob | Evaluate the probability of this word in this context. | [
"Evaluate",
"the",
"probability",
"of",
"this",
"word",
"in",
"this",
"context."
] | def prob(self, word, context):
raise NotImplementedError() | ['def', 'prob(self,', 'word,', 'context):', 'raise', 'NotImplementedError()'] | 527,702 |
myothida/Supervised-Machine-Learning | info.py | TableBuilderAbstract.dtype_counts | dtype_counts | Mapping dtype - number of counts. | [
"Mapping",
"dtype",
"-",
"number",
"of",
"counts."
] | def dtype_counts(self) -> Mapping[str, int]:
return self.info.dtype_counts | ['def', 'dtype_counts(self)', '->', 'Mapping[str,', 'int]:', 'return', 'self.info.dtype_counts'] | 443,402 |
Eric3911/OpenAGI | conv.py | Conv1dCell.update_buffer | update_buffer | Shift the buffer by one step. | [
"Shift",
"the",
"buffer",
"by",
"one",
"step."
] | def update_buffer(self, x_t):
self._buffer = paddle.concat([self._buffer[:, :, 1:], paddle.unsqueeze(x_t, -1)], -1) | ['def', 'update_buffer(self,', 'x_t):', 'self._buffer', '=', 'paddle.concat([self._buffer[:,', ':,', '1:],', 'paddle.unsqueeze(x_t,', '-1)],', '-1)'] | 251,773 |
enuguru/artificial_intelligence_and_machine_learning | ax.py | FetchRequest.iterAttrs | iterAttrs | Iterate over the AttrInfo objects that are contained in this fetch_request. | [
"Iterate",
"over",
"the",
"AttrInfo",
"objects",
"that",
"are",
"contained",
"in",
"this",
"fetch_request."
] | def iterAttrs(self):
return iter(self.requested_attributes.values()) | ['def', 'iterAttrs(self):', 'return', 'iter(self.requested_attributes.values())'] | 130,164 |
matthewdargan/Stock-RNN | preprocess.py | add_vix | add_vix | Add CBOE Volatility Index to dataframe. | [
"Add",
"CBOE",
"Volatility",
"Index",
"to",
"dataframe."
] | def add_vix(df: DataFrame) -> None:
vix_data = read_csv('./data/^VIX.csv')
vix_data.rename(columns={'Date': 'timestamp'}, inplace=True)
vix_data['timestamp'] = to_datetime(vix_data['timestamp'])
vix_data.set_index('timestamp', inplace=True)
df['vix_open'] = vix_data['Open'].astype(np.float64)
df... | ['def', 'add_vix(df:', 'DataFrame)', '->', 'None:', 'vix_data', '=', "read_csv('./data/^VIX.csv')", "vix_data.rename(columns={'Date':", "'timestamp'},", 'inplace=True)', "vix_data['timestamp']", '=', "to_datetime(vix_data['timestamp'])", "vix_data.set_index('timestamp',", 'inplace=True)', "df['vix_open']", '=', "vix_da... | 384,221 |
salesforce/CodeRL | notebook.py | text_to_html_table | text_to_html_table | Put the texts in `items` in an HTML table. | [
"Put",
"the",
"texts",
"in",
"`items`",
"in",
"an",
"HTML",
"table."
] | def text_to_html_table(items):
html_code = '<table border="1" class="dataframe">\n'
html_code += ' <thead>\n <tr style="text-align: left;">\n'
for i in items[0]:
html_code += f' <th>{i}</th>\n'
html_code += ' </tr>\n </thead>\n <tbody>\n'
for line in items[1:]:
html_code +... | ['def', 'text_to_html_table(items):', 'html_code', '=', "'<table", 'border="1"', 'class="dataframe">\\n\'', 'html_code', '+=', "'", '<thead>\\n', '<tr', 'style="text-align:', 'left;">\\n\'', 'for', 'i', 'in', 'items[0]:', 'html_code', '+=', "f'", "<th>{i}</th>\\n'", 'html_code', '+=', "'", '</tr>\\n', '</thead>\\n', "<... | 495,613 |
googleinterns/ddsp-docker | ddsp_ai_platform.py | push_image | push_image | Pushes the docker image on Google Cloud Registry. | [
"Pushes",
"the",
"docker",
"image",
"on",
"Google",
"Cloud",
"Registry."
] | def push_image(args):
pushing_image = f"docker push {args['image_uri']}"
os.system(pushing_image) | ['def', 'push_image(args):', 'pushing_image', '=', 'f"docker', 'push', '{args[\'image_uri\']}"', 'os.system(pushing_image)'] | 516,403 |
rlgraph/rlgraph | ops.py | deep_tuple | deep_tuple | Converts all lists inside the input into a DataOpTuple. | [
"Converts",
"all",
"lists",
"inside",
"the",
"input",
"into",
"a",
"DataOpTuple."
] | def deep_tuple(x):
if isinstance(x, list):
return DataOpTuple(list(map(deep_tuple, x)))
elif isinstance(x, dict):
return type(x)(dict(map(lambda i: (i[0], deep_tuple(i[1])), x.items())))
else:
return x | ['def', 'deep_tuple(x):', 'if', 'isinstance(x,', 'list):', 'return', 'DataOpTuple(list(map(deep_tuple,', 'x)))', 'elif', 'isinstance(x,', 'dict):', 'return', 'type(x)(dict(map(lambda', 'i:', '(i[0],', 'deep_tuple(i[1])),', 'x.items())))', 'else:', 'return', 'x'] | 862,850 |
Gradiant/pyodi | boxes.py | get_bbox_array | get_bbox_array | Returns array with bbox coordinates. | [
"Returns",
"array",
"with",
"bbox",
"coordinates."
] | def get_bbox_array(df: pd.DataFrame, prefix: Optional[str]=None, input_bbox_format: str='coco', output_bbox_format: str='coco') -> np.ndarray:
check_bbox_formats(input_bbox_format, output_bbox_format)
columns = get_bbox_column_names(input_bbox_format, prefix=prefix)
bboxes = df[columns].to_numpy()
if in... | ['def', 'get_bbox_array(df:', 'pd.DataFrame,', 'prefix:', 'Optional[str]=None,', 'input_bbox_format:', "str='coco',", 'output_bbox_format:', "str='coco')", '->', 'np.ndarray:', 'check_bbox_formats(input_bbox_format,', 'output_bbox_format)', 'columns', '=', 'get_bbox_column_names(input_bbox_format,', 'prefix=prefix)', '... | 808,994 |
aws/sagemaker-python-sdk | base_predictor.py | Predictor.content_type | content_type | The MIME type of the data sent to the inference endpoint. | [
"The",
"MIME",
"type",
"of",
"the",
"data",
"sent",
"to",
"the",
"inference",
"endpoint."
] | def content_type(self):
return self._content_type or self.serializer.CONTENT_TYPE | ['def', 'content_type(self):', 'return', 'self._content_type', 'or', 'self.serializer.CONTENT_TYPE'] | 829,377 |
aimclub/FEDOT | synth_dataset_generator.py | regression_dataset | regression_dataset | Generates a random dataset for regression problem using scikit-learn API. | [
"Generates",
"a",
"random",
"dataset",
"for",
"regression",
"problem",
"using",
"scikit-learn",
"API."
] | def regression_dataset(samples_amount: int, features_amount: int, features_options: Dict, n_targets: int, noise: float=0.0, shuffle: bool=True):
(features, target) = datasets.make_regression(n_samples=samples_amount, n_features=features_amount, n_informative=features_options['informative'], bias=features_options['b... | ['def', 'regression_dataset(samples_amount:', 'int,', 'features_amount:', 'int,', 'features_options:', 'Dict,', 'n_targets:', 'int,', 'noise:', 'float=0.0,', 'shuffle:', 'bool=True):', '(features,', 'target)', '=', 'datasets.make_regression(n_samples=samples_amount,', 'n_features=features_amount,', "n_informative=featu... | 546,001 |
mwhoffman/pybo | methods.py | init_middle | init_middle | Initialize using a single query in the middle of the space. | [
"Initialize",
"using",
"a",
"single",
"query",
"in",
"the",
"middle",
"of",
"the",
"space."
] | def init_middle(bounds):
return np.mean(bounds, axis=1)[None, :] | ['def', 'init_middle(bounds):', 'return', 'np.mean(bounds,', 'axis=1)[None,', ':]'] | 295,889 |
datamllab/rlcard | round.py | DoudizhuRound.initiate | initiate | Call dealer to deal cards and bid landlord. | [
"Call",
"dealer",
"to",
"deal",
"cards",
"and",
"bid",
"landlord."
] | def initiate(self, players):
landlord_id = self.dealer.determine_role(players)
seen_cards = self.dealer.deck[-3:]
seen_cards.sort(key=functools.cmp_to_key(doudizhu_sort_card))
self.seen_cards = cards2str(seen_cards)
self.landlord_id = landlord_id
self.current_player = landlord_id
self.public... | ['def', 'initiate(self,', 'players):', 'landlord_id', '=', 'self.dealer.determine_role(players)', 'seen_cards', '=', 'self.dealer.deck[-3:]', 'seen_cards.sort(key=functools.cmp_to_key(doudizhu_sort_card))', 'self.seen_cards', '=', 'cards2str(seen_cards)', 'self.landlord_id', '=', 'landlord_id', 'self.current_player', '... | 332,260 |
intel/neural-compressor | onnx_model.py | ONNXModel.remove_node | remove_node | Remove a node from model. | [
"Remove",
"a",
"node",
"from",
"model."
] | def remove_node(self, node):
if node in self._model.graph.node:
self._model.graph.node.remove(node) | ['def', 'remove_node(self,', 'node):', 'if', 'node', 'in', 'self._model.graph.node:', 'self._model.graph.node.remove(node)'] | 738,874 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.