project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
google-research/s4l | resnet.py | maybe_group_conv | maybe_group_conv | Does regular conv or (inefficient) group-conv. | [
"Does",
"regular",
"conv",
"or",
"(inefficient)",
"group-conv."
] | def maybe_group_conv(x, filters, groups, **kw):
assert filters % groups == 0, 'Filters ({}) not divisible by groups ({}).'.format(filters, groups)
assert x.shape.rank == 4, 'Only implemented for 4D inputs.'
if groups == 1:
return tf.layers.conv2d(x, filters, **kw)
outputs = []
for (i, xi) in... | ['def', 'maybe_group_conv(x,', 'filters,', 'groups,', '**kw):', 'assert', 'filters', '%', 'groups', '==', '0,', "'Filters", '({})', 'not', 'divisible', 'by', 'groups', "({}).'.format(filters,", 'groups)', 'assert', 'x.shape.rank', '==', '4,', "'Only", 'implemented', 'for', '4D', "inputs.'", 'if', 'groups', '==', '1:', ... | 328,045 |
microsoft/InnerEye-DeepLearning | test_config_helpers.py | test_fields_are_set | test_fields_are_set | Tests that expected fields are set when creating config classes. | [
"Tests",
"that",
"expected",
"fields",
"are",
"set",
"when",
"creating",
"config",
"classes."
] | def test_fields_are_set() -> None:
expected = [('hello', None), ('world', None)]
config = SegmentationModelBase(should_validate=False, ground_truth_ids=[x[0] for x in expected], largest_connected_component_foreground_classes=expected)
assert hasattr(config, CROSS_VALIDATION_SPLIT_INDEX_TAG_KEY)
assert c... | ['def', 'test_fields_are_set()', '->', 'None:', 'expected', '=', "[('hello',", 'None),', "('world',", 'None)]', 'config', '=', 'SegmentationModelBase(should_validate=False,', 'ground_truth_ids=[x[0]', 'for', 'x', 'in', 'expected],', 'largest_connected_component_foreground_classes=expected)', 'assert', 'hasattr(config,'... | 613,572 |
MycroftAI/mycroft-core | cache.py | TextToSpeechCache.clear | clear | Remove all files from the temporary cache. | [
"Remove",
"all",
"files",
"from",
"the",
"temporary",
"cache."
] | def clear(self):
for cache_file_path in self.temporary_cache_dir.iterdir():
if cache_file_path.is_dir():
for sub_path in cache_file_path.iterdir():
if sub_path.is_file():
sub_path.unlink()
elif cache_file_path.is_file():
cache_file_path.unl... | ['def', 'clear(self):', 'for', 'cache_file_path', 'in', 'self.temporary_cache_dir.iterdir():', 'if', 'cache_file_path.is_dir():', 'for', 'sub_path', 'in', 'cache_file_path.iterdir():', 'if', 'sub_path.is_file():', 'sub_path.unlink()', 'elif', 'cache_file_path.is_file():', 'cache_file_path.unlink()'] | 290,666 |
ChenhongyiYang/PPAL | embedding_rpn_head.py | EmbeddingRPNHead.forward_train | forward_train | Forward function in training stage. | [
"Forward",
"function",
"in",
"training",
"stage."
] | def forward_train(self, img, img_metas):
return self._decode_init_proposals(img, img_metas) | ['def', 'forward_train(self,', 'img,', 'img_metas):', 'return', 'self._decode_init_proposals(img,', 'img_metas)'] | 821,536 |
Farama-Foundation/Gymnasium | record_episode_statistics.py | RecordEpisodeStatisticsV0.step | step | Steps through the environment, recording the episode statistics. | [
"Steps",
"through",
"the",
"environment,",
"recording",
"the",
"episode",
"statistics."
] | def step(self, actions: ActType) -> tuple[ObsType, ArrayType, ArrayType, ArrayType, dict]:
(observations, rewards, terminations, truncations, infos) = self.env.step(actions)
assert isinstance(infos, dict), f'`info` dtype is {type(infos)} while supported dtype is `dict`. This may be due to usage of other wrapper... | ['def', 'step(self,', 'actions:', 'ActType)', '->', 'tuple[ObsType,', 'ArrayType,', 'ArrayType,', 'ArrayType,', 'dict]:', '(observations,', 'rewards,', 'terminations,', 'truncations,', 'infos)', '=', 'self.env.step(actions)', 'assert', 'isinstance(infos,', 'dict),', "f'`info`", 'dtype', 'is', '{type(infos)}', 'while', ... | 573,220 |
greydanus/pythonic_ocr | cmdline.py | CoverageScript.do_run | do_run | Implementation of 'coverage run'. | [
"Implementation",
"of",
"'coverage",
"run'."
] | def do_run(self, options, args):
if options.append and self.coverage.get_option('run:parallel'):
self.help_fn("Can't append to data files in parallel mode.")
return ERR
if not self.coverage.get_option('run:parallel'):
if not options.append:
self.coverage.erase()
self.cove... | ['def', 'do_run(self,', 'options,', 'args):', 'if', 'options.append', 'and', "self.coverage.get_option('run:parallel'):", 'self.help_fn("Can\'t', 'append', 'to', 'data', 'files', 'in', 'parallel', 'mode.")', 'return', 'ERR', 'if', 'not', "self.coverage.get_option('run:parallel'):", 'if', 'not', 'options.append:', 'self... | 298,822 |
viko-3/DiffSeqMol | api.py | RendezvousParameters.get_as_bool | get_as_bool | Returns the value for ``key`` as a ``bool``. | [
"Returns",
"the",
"value",
"for",
"``key``",
"as",
"a",
"``bool``."
] | def get_as_bool(self, key: str, default: Optional[bool]=None) -> Optional[bool]:
value = self.get(key, default)
if value is None or isinstance(value, bool):
return value
if isinstance(value, int):
if value == 1:
return True
if value == 0:
return False
elif... | ['def', 'get_as_bool(self,', 'key:', 'str,', 'default:', 'Optional[bool]=None)', '->', 'Optional[bool]:', 'value', '=', 'self.get(key,', 'default)', 'if', 'value', 'is', 'None', 'or', 'isinstance(value,', 'bool):', 'return', 'value', 'if', 'isinstance(value,', 'int):', 'if', 'value', '==', '1:', 'return', 'True', 'if',... | 551,408 |
eddylau328/fyp-artificial-intelligence-ac-control-device | site.py | execusercustomize | execusercustomize | Run custom user specific code, if available. | [
"Run",
"custom",
"user",
"specific",
"code,",
"if",
"available."
] | def execusercustomize():
try:
import usercustomize
except ImportError:
pass | ['def', 'execusercustomize():', 'try:', 'import', 'usercustomize', 'except', 'ImportError:', 'pass'] | 214,182 |
asyml/texar | ptb_reader.py | ptb_iterator | ptb_iterator | Iterates through the ptb data. | [
"Iterates",
"through",
"the",
"ptb",
"data."
] | def ptb_iterator(data, batch_size, num_steps):
data_length = len(data)
batch_length = data_length // batch_size
data = np.asarray(data[:batch_size * batch_length])
data = data.reshape([batch_size, batch_length])
epoch_size = (batch_length - 1) // num_steps
if epoch_size == 0:
raise Value... | ['def', 'ptb_iterator(data,', 'batch_size,', 'num_steps):', 'data_length', '=', 'len(data)', 'batch_length', '=', 'data_length', '//', 'batch_size', 'data', '=', 'np.asarray(data[:batch_size', '*', 'batch_length])', 'data', '=', 'data.reshape([batch_size,', 'batch_length])', 'epoch_size', '=', '(batch_length', '-', '1)... | 924,284 |
WHU-ZQH/E2S2 | token_generation_constraints.py | ConstraintNode.add_sequence | add_sequence | Adds a constraint, represented as a list of integers, to the trie. | [
"Adds",
"a",
"constraint,",
"represented",
"as",
"a",
"list",
"of",
"integers,",
"to",
"the",
"trie."
] | def add_sequence(self, sequence: List[int]):
assert len(sequence) > 0
token = int(sequence[0])
if token not in self.children:
self.children[token] = ConstraintNode(token, parent=self)
node = self.children[token]
if len(sequence) == 1:
node.terminal += 1
node.num_constraints +... | ['def', 'add_sequence(self,', 'sequence:', 'List[int]):', 'assert', 'len(sequence)', '>', '0', 'token', '=', 'int(sequence[0])', 'if', 'token', 'not', 'in', 'self.children:', 'self.children[token]', '=', 'ConstraintNode(token,', 'parent=self)', 'node', '=', 'self.children[token]', 'if', 'len(sequence)', '==', '1:', 'no... | 555,598 |
flow-project/flow | test_scenario_base_class.py | TestRandomStartPos.test_lanes_distribution | test_lanes_distribution | Tests that vehicles are only placed in the requested number of lanes. | [
"Tests",
"that",
"vehicles",
"are",
"only",
"placed",
"in",
"the",
"requested",
"number",
"of",
"lanes."
] | def test_lanes_distribution(self):
initial_config = InitialConfig(spacing='random', lanes_distribution=2)
self.setUp_gen_start_pos(initial_config)
for veh_id in self.env.k.vehicle.get_ids():
self.assertLess(self.env.k.vehicle.get_lane(veh_id), initial_config.lanes_distribution) | ['def', 'test_lanes_distribution(self):', 'initial_config', '=', "InitialConfig(spacing='random',", 'lanes_distribution=2)', 'self.setUp_gen_start_pos(initial_config)', 'for', 'veh_id', 'in', 'self.env.k.vehicle.get_ids():', 'self.assertLess(self.env.k.vehicle.get_lane(veh_id),', 'initial_config.lanes_distribution)'] | 211,994 |
PaddlePaddle/PaddleSpeech | model.py | WavLMASRTrainer.save | save | Save checkpoint (model parameters and optimizer states). | [
"Save",
"checkpoint",
"(model",
"parameters",
"and",
"optimizer",
"states)."
] | def save(self, tag=None, infos: dict=None):
infos = infos if infos else dict()
infos.update({'epoch': self.epoch, 'model_lr': self.model_optimizer.get_lr(), 'wavlm_lr': self.wavlm_optimizer.get_lr()})
checkpoint_path = os.path.join(self.checkpoint_dir, '{}'.format(self.iteration if tag is None else tag))
... | ['def', 'save(self,', 'tag=None,', 'infos:', 'dict=None):', 'infos', '=', 'infos', 'if', 'infos', 'else', 'dict()', "infos.update({'epoch':", 'self.epoch,', "'model_lr':", 'self.model_optimizer.get_lr(),', "'wavlm_lr':", 'self.wavlm_optimizer.get_lr()})', 'checkpoint_path', '=', 'os.path.join(self.checkpoint_dir,', "'{... | 276,652 |
ameet-1997/AttentionGuidance | tokenization_utils.py | PreTrainedTokenizer.truncate_sequences | truncate_sequences | Truncates a sequence pair in place to the maximum length. | [
"Truncates",
"a",
"sequence",
"pair",
"in",
"place",
"to",
"the",
"maximum",
"length."
] | def truncate_sequences(self, ids: List[int], pair_ids: Optional[List[int]]=None, num_tokens_to_remove: int=0, truncation_strategy: str='longest_first', stride: int=0) -> Tuple[List[int], List[int], List[int]]:
if num_tokens_to_remove <= 0:
return (ids, pair_ids, [])
if truncation_strategy == 'longest_fi... | ['def', 'truncate_sequences(self,', 'ids:', 'List[int],', 'pair_ids:', 'Optional[List[int]]=None,', 'num_tokens_to_remove:', 'int=0,', 'truncation_strategy:', "str='longest_first',", 'stride:', 'int=0)', '->', 'Tuple[List[int],', 'List[int],', 'List[int]]:', 'if', 'num_tokens_to_remove', '<=', '0:', 'return', '(ids,', ... | 93,187 |
supervisely/supervisely | inference.py | infer_per_pixel_scores_single_image | infer_per_pixel_scores_single_image | Performs inference with PyTorch model and resize predictions to a given size. | [
"Performs",
"inference",
"with",
"PyTorch",
"model",
"and",
"resize",
"predictions",
"to",
"a",
"given",
"size."
] | def infer_per_pixel_scores_single_image(model, raw_input, out_shape, apply_softmax=True):
model_input = torch.stack([raw_input], 0)
model_input = cuda_variable(model_input, volatile=True)
output = model(model_input)
if apply_softmax:
output = torch_functional.softmax(output, dim=1)
output = ... | ['def', 'infer_per_pixel_scores_single_image(model,', 'raw_input,', 'out_shape,', 'apply_softmax=True):', 'model_input', '=', 'torch.stack([raw_input],', '0)', 'model_input', '=', 'cuda_variable(model_input,', 'volatile=True)', 'output', '=', 'model(model_input)', 'if', 'apply_softmax:', 'output', '=', 'torch_functiona... | 881,714 |
voxel51/fiftyone | executor.py | ExecutionContext.secret | secret | Retrieves the secret with the given key. | [
"Retrieves",
"the",
"secret",
"with",
"the",
"given",
"key."
] | def secret(self, key):
return self._secrets.get(key, None) | ['def', 'secret(self,', 'key):', 'return', 'self._secrets.get(key,', 'None)'] | 583,755 |
danijar/embodied | ninjax.py | rng | rng | Split the global RNG key and return a new local key. | [
"Split",
"the",
"global",
"RNG",
"key",
"and",
"return",
"a",
"new",
"local",
"key."
] | def rng(amount=None, reserve=16):
ctx = context()
if amount:
keys = jax.random.split(ctx.rng, amount + 1)
ctx.rng = keys[0]
return keys[1:]
else:
if not ctx.reserve:
keys = jax.random.split(ctx.rng, reserve)
ctx.rng = keys[0]
ctx.reserve = ... | ['def', 'rng(amount=None,', 'reserve=16):', 'ctx', '=', 'context()', 'if', 'amount:', 'keys', '=', 'jax.random.split(ctx.rng,', 'amount', '+', '1)', 'ctx.rng', '=', 'keys[0]', 'return', 'keys[1:]', 'else:', 'if', 'not', 'ctx.reserve:', 'keys', '=', 'jax.random.split(ctx.rng,', 'reserve)', 'ctx.rng', '=', 'keys[0]', 'ct... | 561,551 |
mfbx9da4/neuron-astrocyte-networks | grammatical_evolution.py | GrammaticalEvolution.get_fitness_fail | get_fitness_fail | This function returns the value of fitness if the program is a failure. | [
"This",
"function",
"returns",
"the",
"value",
"of",
"fitness",
"if",
"the",
"program",
"is",
"a",
"failure."
] | def get_fitness_fail(self):
return self._fitness_fail | ['def', 'get_fitness_fail(self):', 'return', 'self._fitness_fail'] | 722,916 |
danamyu/hedgehog_detector | metaopt.py | run_wall_clock_test | run_wall_clock_test | Runs optimization with the given parameters and return average iter time. | [
"Runs",
"optimization",
"with",
"the",
"given",
"parameters",
"and",
"return",
"average",
"iter",
"time."
] | def run_wall_clock_test(optimizer, problem, num_steps, dataset=datasets.EMPTY_DATASET, seed=None, logdir=None, batch_size=None):
if dataset is None:
dataset = datasets.EMPTY_DATASET
batch_size = dataset.size
else:
batch_size = dataset.size if batch_size is None else batch_size
if isi... | ['def', 'run_wall_clock_test(optimizer,', 'problem,', 'num_steps,', 'dataset=datasets.EMPTY_DATASET,', 'seed=None,', 'logdir=None,', 'batch_size=None):', 'if', 'dataset', 'is', 'None:', 'dataset', '=', 'datasets.EMPTY_DATASET', 'batch_size', '=', 'dataset.size', 'else:', 'batch_size', '=', 'dataset.size', 'if', 'batch_... | 589,728 |
Ruturaj123/Flowchart-Detection | template.py | Template.var_scope | var_scope | Returns the variable scope object created by this Template. | [
"Returns",
"the",
"variable",
"scope",
"object",
"created",
"by",
"this",
"Template."
] | def var_scope(self):
return self._variable_scope | ['def', 'var_scope(self):', 'return', 'self._variable_scope'] | 606,143 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | metaopt.py | train_optimizer | train_optimizer | Trains the meta-parameters of this optimizer. | [
"Trains",
"the",
"meta-parameters",
"of",
"this",
"optimizer."
] | def train_optimizer(logdir, optimizer_spec, problems_and_data, num_problems, num_meta_iterations, num_unroll_func, num_partial_unroll_itrs_func, learning_rate=0.0001, gradient_clip=5.0, is_chief=False, select_random_problems=True, callbacks=None, obj_train_max_multiplier=-1, out=sys.stdout):
if select_random_proble... | ['def', 'train_optimizer(logdir,', 'optimizer_spec,', 'problems_and_data,', 'num_problems,', 'num_meta_iterations,', 'num_unroll_func,', 'num_partial_unroll_itrs_func,', 'learning_rate=0.0001,', 'gradient_clip=5.0,', 'is_chief=False,', 'select_random_problems=True,', 'callbacks=None,', 'obj_train_max_multiplier=-1,', '... | 55,443 |
srai-lab/srai | conftest.py | gdf_features | gdf_features | Get GeoDataFrame with example OSM-like features. | [
"Get",
"GeoDataFrame",
"with",
"example",
"OSM-like",
"features."
] | def gdf_features() -> gpd.GeoDataFrame:
features_gdf = gpd.GeoDataFrame({'leisure': ['playground', None, 'adult_gaming_centre', None], 'amenity': [None, 'pub', 'pub', None]}, geometry=[geometry.Polygon(shell=[(17.0360858, 51.1103927), (17.0358804, 51.1104389), (17.0357855, 51.1105503), (17.0359451, 51.1105907), (17... | ['def', 'gdf_features()', '->', 'gpd.GeoDataFrame:', 'features_gdf', '=', "gpd.GeoDataFrame({'leisure':", "['playground',", 'None,', "'adult_gaming_centre',", 'None],', "'amenity':", '[None,', "'pub',", "'pub',", 'None]},', 'geometry=[geometry.Polygon(shell=[(17.0360858,', '51.1103927),', '(17.0358804,', '51.1104389),'... | 371,929 |
instadeepai/jumanji | tree_utils_test.py | test_tree_transpose | test_tree_transpose | Validates the transposition of a list of trees. | [
"Validates",
"the",
"transposition",
"of",
"a",
"list",
"of",
"trees."
] | def test_tree_transpose() -> None:
tree_1 = {'a': 0, 'b': jnp.array([1, 2], int)}
tree_2 = {'a': 5, 'b': jnp.array([3, 4], int)}
list_of_trees = [tree_1, tree_2]
transposed_tree: chex.ArrayTree = {'a': jnp.array([0, 5], int), 'b': jnp.array([[1, 2], [3, 4]], int)}
assert_trees_are_equal(transposed_t... | ['def', 'test_tree_transpose()', '->', 'None:', 'tree_1', '=', "{'a':", '0,', "'b':", 'jnp.array([1,', '2],', 'int)}', 'tree_2', '=', "{'a':", '5,', "'b':", 'jnp.array([3,', '4],', 'int)}', 'list_of_trees', '=', '[tree_1,', 'tree_2]', 'transposed_tree:', 'chex.ArrayTree', '=', "{'a':", 'jnp.array([0,', '5],', 'int),', ... | 593,870 |
Speedwagon13/CS-3600-Introduction-to-- | genericpath.py | isdir | isdir | Return true if the pathname refers to an existing directory. | [
"Return",
"true",
"if",
"the",
"pathname",
"refers",
"to",
"an",
"existing",
"directory."
] | def isdir(s):
try:
st = os.stat(s)
except os.error:
return False
return stat.S_ISDIR(st.st_mode) | ['def', 'isdir(s):', 'try:', 'st', '=', 'os.stat(s)', 'except', 'os.error:', 'return', 'False', 'return', 'stat.S_ISDIR(st.st_mode)'] | 139,803 |
KalleHallden/InstaAutomator | api.py | EventDispatcher.event_queue | event_queue | The event queue which is populated with file system events by emitters and from which events are dispatched by a dispatcher thread. | [
"The",
"event",
"queue",
"which",
"is",
"populated",
"with",
"file",
"system",
"events",
"by",
"emitters",
"and",
"from",
"which",
"events",
"are",
"dispatched",
"by",
"a",
"dispatcher",
"thread."
] | def event_queue(self):
return self._event_queue | ['def', 'event_queue(self):', 'return', 'self._event_queue'] | 245,094 |
tudelft3d/SUMS-Semantic-Urban-Mesh--public | fusion.py | TSDFVolume.vox2world | vox2world | Convert voxel grid coordinates to world coordinates. | [
"Convert",
"voxel",
"grid",
"coordinates",
"to",
"world",
"coordinates."
] | def vox2world(vol_origin, vox_coords, vox_size):
vol_origin = vol_origin.astype(np.float32)
vox_coords = vox_coords.astype(np.float32)
cam_pts = np.empty_like(vox_coords, dtype=np.float32)
for i in prange(vox_coords.shape[0]):
for j in range(3):
cam_pts[i, j] = vol_origin[j] + vox_si... | ['def', 'vox2world(vol_origin,', 'vox_coords,', 'vox_size):', 'vol_origin', '=', 'vol_origin.astype(np.float32)', 'vox_coords', '=', 'vox_coords.astype(np.float32)', 'cam_pts', '=', 'np.empty_like(vox_coords,', 'dtype=np.float32)', 'for', 'i', 'in', 'prange(vox_coords.shape[0]):', 'for', 'j', 'in', 'range(3):', 'cam_pt... | 910,698 |
NVIDIA/semantic-segmentation | transforms.py | adjust_brightness | adjust_brightness | Adjust brightness of an Image. | [
"Adjust",
"brightness",
"of",
"an",
"Image."
] | def adjust_brightness(img, brightness_factor):
if not _is_pil_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(brightness_factor)
return img | ['def', 'adjust_brightness(img,', 'brightness_factor):', 'if', 'not', '_is_pil_image(img):', 'raise', "TypeError('img", 'should', 'be', 'PIL', 'Image.', 'Got', "{}'.format(type(img)))", 'enhancer', '=', 'ImageEnhance.Brightness(img)', 'img', '=', 'enhancer.enhance(brightness_factor)', 'return', 'img'] | 869,304 |
bachiraoun/fullrmc | Group.py | Group.name | name | groud user defined name. | [
"groud",
"user",
"defined",
"name."
] | def name(self):
return self.__name | ['def', 'name(self):', 'return', 'self.__name'] | 213,826 |
shery322/Lunar-Lander-ANN | packaging.py | get_requires_python | get_requires_python | Return the "Requires-Python" metadata for a distribution, or None if not present. | [
"Return",
"the",
"\"Requires-Python\"",
"metadata",
"for",
"a",
"distribution,",
"or",
"None",
"if",
"not",
"present."
] | def get_requires_python(dist):
pkg_info_dict = get_metadata(dist)
requires_python = pkg_info_dict.get('Requires-Python')
if requires_python is not None:
requires_python = str(requires_python)
return requires_python | ['def', 'get_requires_python(dist):', 'pkg_info_dict', '=', 'get_metadata(dist)', 'requires_python', '=', "pkg_info_dict.get('Requires-Python')", 'if', 'requires_python', 'is', 'not', 'None:', 'requires_python', '=', 'str(requires_python)', 'return', 'requires_python'] | 617,858 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | Pmf.Prob | Prob | Gets the probability associated with the value x. | [
"Gets",
"the",
"probability",
"associated",
"with",
"the",
"value",
"x."
] | def Prob(self, x, default=0):
return self.d.get(x, default) | ['def', 'Prob(self,', 'x,', 'default=0):', 'return', 'self.d.get(x,', 'default)'] | 19,581 |
RLE-Foundation/rllte | wrappers.py | ActionRepeatWrapper.step | step | Repeat the action for a given number of steps and return the accumulated reward. | [
"Repeat",
"the",
"action",
"for",
"a",
"given",
"number",
"of",
"steps",
"and",
"return",
"the",
"accumulated",
"reward."
] | def step(self, action: np.ndarray) -> dm_env.TimeStep:
reward = 0.0
discount = 1.0
for _ in range(self._num_repeats):
time_step = self._env.step(action)
reward += (time_step.reward or 0.0) * discount
discount *= time_step.discount
if time_step.last():
break
re... | ['def', 'step(self,', 'action:', 'np.ndarray)', '->', 'dm_env.TimeStep:', 'reward', '=', '0.0', 'discount', '=', '1.0', 'for', '_', 'in', 'range(self._num_repeats):', 'time_step', '=', 'self._env.step(action)', 'reward', '+=', '(time_step.reward', 'or', '0.0)', '*', 'discount', 'discount', '*=', 'time_step.discount', '... | 333,278 |
rudranil723/mini-main | io.py | WKBWriter.write_hex | write_hex | Return the HEXEWKB representation of the given geometry. | [
"Return",
"the",
"HEXEWKB",
"representation",
"of",
"the",
"given",
"geometry."
] | def write_hex(self, geom):
from django.contrib.gis.geos.polygon import Polygon
geom = self._handle_empty_point(geom)
wkb = wkb_writer_write_hex(self.ptr, geom.ptr, byref(c_size_t()))
if geos_version_tuple() < (3, 6, 1) and isinstance(geom, Polygon) and geom.empty:
wkb = wkb[:-16] + b'0' * 8
... | ['def', 'write_hex(self,', 'geom):', 'from', 'django.contrib.gis.geos.polygon', 'import', 'Polygon', 'geom', '=', 'self._handle_empty_point(geom)', 'wkb', '=', 'wkb_writer_write_hex(self.ptr,', 'geom.ptr,', 'byref(c_size_t()))', 'if', 'geos_version_tuple()', '<', '(3,', '6,', '1)', 'and', 'isinstance(geom,', 'Polygon)'... | 315,378 |
sarnsdev/social-alignment-data-mining | six.py | iteritems | iteritems | Return an iterator over the (key, value) pairs of a dictionary. | [
"Return",
"an",
"iterator",
"over",
"the",
"(key,",
"value)",
"pairs",
"of",
"a",
"dictionary."
] | def iteritems(d, **kw):
return iter(getattr(d, _iteritems)(**kw)) | ['def', 'iteritems(d,', '**kw):', 'return', 'iter(getattr(d,', '_iteritems)(**kw))'] | 391,976 |
weimin17/Object-Detection_HelmetDetection | generate_videos.py | SameSequenceVideos | SameSequenceVideos | Generate same sequence, cross-view imitation videos. | [
"Generate",
"same",
"sequence,",
"cross-view",
"imitation",
"videos."
] | def SameSequenceVideos(query_records, config, height, width):
batch_size = config.data.embed_batch_size
estimator = get_estimator(config, FLAGS.checkpointdir)
checkpointdir = FLAGS.checkpointdir
checkpoint_path = os.path.join(checkpointdir, 'model.ckpt-%s' % FLAGS.checkpoint_iter)
sequences_to_data ... | ['def', 'SameSequenceVideos(query_records,', 'config,', 'height,', 'width):', 'batch_size', '=', 'config.data.embed_batch_size', 'estimator', '=', 'get_estimator(config,', 'FLAGS.checkpointdir)', 'checkpointdir', '=', 'FLAGS.checkpointdir', 'checkpoint_path', '=', 'os.path.join(checkpointdir,', "'model.ckpt-%s'", '%', ... | 760,544 |
intel/neural-compressor | graph_transform_base.py | GraphTransformBase.generate_input_map | generate_input_map | Generate the input map. | [
"Generate",
"the",
"input",
"map."
] | def generate_input_map(self):
self.input_node_map = {}
for node in self.input_graph.node:
node_name = self.node_name_from_input(node.name)
if node_name not in self.input_node_map:
self.input_node_map[node_name] = node
else:
raise ValueError('Duplicate node names d... | ['def', 'generate_input_map(self):', 'self.input_node_map', '=', '{}', 'for', 'node', 'in', 'self.input_graph.node:', 'node_name', '=', 'self.node_name_from_input(node.name)', 'if', 'node_name', 'not', 'in', 'self.input_node_map:', 'self.input_node_map[node_name]', '=', 'node', 'else:', 'raise', "ValueError('Duplicate"... | 737,847 |
apeterswu/RL4NMT | cipher.py | generate_plaintext_random | generate_plaintext_random | Generates samples of text from the provided vocabulary. | [
"Generates",
"samples",
"of",
"text",
"from",
"the",
"provided",
"vocabulary."
] | def generate_plaintext_random(plain_vocab, distribution, train_samples, length):
if distribution is not None:
assert len(distribution) == len(plain_vocab)
train_indices = np.random.choice(range(len(plain_vocab)), (train_samples, length), p=distribution)
return train_indices | ['def', 'generate_plaintext_random(plain_vocab,', 'distribution,', 'train_samples,', 'length):', 'if', 'distribution', 'is', 'not', 'None:', 'assert', 'len(distribution)', '==', 'len(plain_vocab)', 'train_indices', '=', 'np.random.choice(range(len(plain_vocab)),', '(train_samples,', 'length),', 'p=distribution)', 'retu... | 330,875 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | _parseaddr.py | parsedate | parsedate | Convert a time string to a time tuple. | [
"Convert",
"a",
"time",
"string",
"to",
"a",
"time",
"tuple."
] | def parsedate(data):
t = parsedate_tz(data)
if isinstance(t, tuple):
return t[:9]
else:
return t | ['def', 'parsedate(data):', 't', '=', 'parsedate_tz(data)', 'if', 'isinstance(t,', 'tuple):', 'return', 't[:9]', 'else:', 'return', 't'] | 430,614 |
danamyu/hedgehog_detector | utils.py | RouletteWheel.add | add | Add one object and its weight to the roulette wheel. | [
"Add",
"one",
"object",
"and",
"its",
"weight",
"to",
"the",
"roulette",
"wheel."
] | def add(self, obj, weight, key=None):
if weight < 0:
raise ValueError('Weight must be non-negative')
if self.unique_mode:
if key is None:
raise ValueError('Hashable key required for objects when unique mode is enabled.')
if key in self.keys_to_weights:
return Fals... | ['def', 'add(self,', 'obj,', 'weight,', 'key=None):', 'if', 'weight', '<', '0:', 'raise', "ValueError('Weight", 'must', 'be', "non-negative')", 'if', 'self.unique_mode:', 'if', 'key', 'is', 'None:', 'raise', "ValueError('Hashable", 'key', 'required', 'for', 'objects', 'when', 'unique', 'mode', 'is', "enabled.')", 'if',... | 589,327 |
PacktPublishing/Hands-On-Artificial--for-Banking | base_request.py | BaseRequest.data | data | Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle. | [
"Contains",
"the",
"incoming",
"request",
"data",
"as",
"string",
"in",
"case",
"it",
"came",
"with",
"a",
"mimetype",
"Werkzeug",
"does",
"not",
"handle."
] | def data(self):
if self.disable_data_descriptor:
raise AttributeError('data descriptor is disabled')
return self.get_data(parse_form_data=True) | ['def', 'data(self):', 'if', 'self.disable_data_descriptor:', 'raise', "AttributeError('data", 'descriptor', 'is', "disabled')", 'return', 'self.get_data(parse_form_data=True)'] | 205,058 |
NJU-LHRS/official-CMID | swin_utils.py | resize_relative_position_bias_table | resize_relative_position_bias_table | Resize relative position bias table. | [
"Resize",
"relative",
"position",
"bias",
"table."
] | def resize_relative_position_bias_table(src_shape, dst_shape, table, num_head):
from scipy import interpolate
def geometric_progression(a, r, n):
return a * (1.0 - r ** n) / (1.0 - r)
(left, right) = (1.01, 1.5)
while right - left > 1e-06:
q = (left + right) / 2.0
gp = geometric... | ['def', 'resize_relative_position_bias_table(src_shape,', 'dst_shape,', 'table,', 'num_head):', 'from', 'scipy', 'import', 'interpolate', 'def', 'geometric_progression(a,', 'r,', 'n):', 'return', 'a', '*', '(1.0', '-', 'r', '**', 'n)', '/', '(1.0', '-', 'r)', '(left,', 'right)', '=', '(1.01,', '1.5)', 'while', 'right',... | 250,208 |
Qbanxiaoxu/NaturalLanguageProcessingExperiment | operator.py | truediv | truediv | Same as a / b. | [
"Same",
"as",
"a",
"/",
"b."
] | def truediv(a, b):
return a / b | ['def', 'truediv(a,', 'b):', 'return', 'a', '/', 'b'] | 801,555 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_bases.py | GraphicsContextBase.set_antialiased | set_antialiased | Set whether object should be drawn with antialiased rendering. | [
"Set",
"whether",
"object",
"should",
"be",
"drawn",
"with",
"antialiased",
"rendering."
] | def set_antialiased(self, b):
self._antialiased = int(bool(b)) | ['def', 'set_antialiased(self,', 'b):', 'self._antialiased', '=', 'int(bool(b))'] | 256,678 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | deepreload.py | ensure_fromlist | ensure_fromlist | Handle 'from module import a, b, c' imports. | [
"Handle",
"'from",
"module",
"import",
"a,",
"b,",
"c'",
"imports."
] | def ensure_fromlist(mod, fromlist, buf, recursive):
if not hasattr(mod, '__path__'):
return
for item in fromlist:
if not hasattr(item, 'rindex'):
raise TypeError("Item in ``from list'' not a string")
if item == '*':
if recursive:
continue
... | ['def', 'ensure_fromlist(mod,', 'fromlist,', 'buf,', 'recursive):', 'if', 'not', 'hasattr(mod,', "'__path__'):", 'return', 'for', 'item', 'in', 'fromlist:', 'if', 'not', 'hasattr(item,', "'rindex'):", 'raise', 'TypeError("Item', 'in', '``from', "list''", 'not', 'a', 'string")', 'if', 'item', '==', "'*':", 'if', 'recurs... | 448,684 |
man805/Diffusion-Video-Autoencoders | model_irse.py | IR_SE_152 | IR_SE_152 | Constructs a ir_se-152 model. | [
"Constructs",
"a",
"ir_se-152",
"model."
] | def IR_SE_152(input_size):
model = Backbone(input_size, num_layers=152, mode='ir_se', drop_ratio=0.4, affine=False)
return model | ['def', 'IR_SE_152(input_size):', 'model', '=', 'Backbone(input_size,', 'num_layers=152,', "mode='ir_se',", 'drop_ratio=0.4,', 'affine=False)', 'return', 'model'] | 551,748 |
DPerrySvendsen/COS30002 | entities.py | Fleet.update | update | Move the fleet (progress) by one game time step. | [
"Move",
"the",
"fleet",
"(progress)",
"by",
"one",
"game",
"time",
"step."
] | def update(self):
self.turns_remaining -= 1
src = self.src
dest = self.dest
scale = 1 - float(self.turns_remaining) / float(self.total_trip_length)
self.x = src.x + (dest.x - src.x) * scale
self.y = src.y + (dest.y - src.y) * scale
self.progress = self.total_trip_length - self.turns_remainin... | ['def', 'update(self):', 'self.turns_remaining', '-=', '1', 'src', '=', 'self.src', 'dest', '=', 'self.dest', 'scale', '=', '1', '-', 'float(self.turns_remaining)', '/', 'float(self.total_trip_length)', 'self.x', '=', 'src.x', '+', '(dest.x', '-', 'src.x)', '*', 'scale', 'self.y', '=', 'src.y', '+', '(dest.y', '-', 'sr... | 137,524 |
triaquae/triaquae | base.py | add_level_messages | add_level_messages | Adds 6 messages from different levels (including a custom one) to a storage instance. | [
"Adds",
"6",
"messages",
"from",
"different",
"levels",
"(including",
"a",
"custom",
"one)",
"to",
"a",
"storage",
"instance."
] | def add_level_messages(storage):
storage.add(constants.INFO, 'A generic info message')
storage.add(29, 'Some custom level')
storage.add(constants.DEBUG, 'A debugging message', extra_tags='extra-tag')
storage.add(constants.WARNING, 'A warning')
storage.add(constants.ERROR, 'An error')
storage.add... | ['def', 'add_level_messages(storage):', 'storage.add(constants.INFO,', "'A", 'generic', 'info', "message')", 'storage.add(29,', "'Some", 'custom', "level')", 'storage.add(constants.DEBUG,', "'A", 'debugging', "message',", "extra_tags='extra-tag')", 'storage.add(constants.WARNING,', "'A", "warning')", 'storage.add(const... | 358,123 |
Speedwagon13/CS-3600-Introduction-to-- | __init__.py | BufferingFormatter.formatFooter | formatFooter | Return the footer string for the specified records. | [
"Return",
"the",
"footer",
"string",
"for",
"the",
"specified",
"records."
] | def formatFooter(self, records):
return '' | ['def', 'formatFooter(self,', 'records):', 'return', "''"] | 219,508 |
mrubash1/RNN-Tutorial | char_rnn.py | sampling | sampling | Sample text from user provided starting characters. | [
"Sample",
"text",
"from",
"user",
"provided",
"starting",
"characters."
] | def sampling(args):
model = RecurrentLanguageModel(args.num_layers, args.num_units)
seed = tf.placeholder(tf.uint8, [None, None])
temp = tf.placeholder(tf.float32, [])
text = tf.concat([seed, model.generate(seed, args.sample_length, temp)], 1)
with initialize_session(args.logdir) as (sess, saver):
... | ['def', 'sampling(args):', 'model', '=', 'RecurrentLanguageModel(args.num_layers,', 'args.num_units)', 'seed', '=', 'tf.placeholder(tf.uint8,', '[None,', 'None])', 'temp', '=', 'tf.placeholder(tf.float32,', '[])', 'text', '=', 'tf.concat([seed,', 'model.generate(seed,', 'args.sample_length,', 'temp)],', '1)', 'with', '... | 325,391 |
arshpreetsingh/quantopian-machinelearning | traitlets.py | HasTraits.trait_metadata | trait_metadata | Get metadata values for trait by key. | [
"Get",
"metadata",
"values",
"for",
"trait",
"by",
"key."
] | def trait_metadata(self, traitname, key, default=None):
try:
trait = getattr(self.__class__, traitname)
except AttributeError:
raise TraitError('Class %s does not have a trait named %s' % (self.__class__.__name__, traitname))
metadata_name = '_' + traitname + '_metadata'
if hasattr(self,... | ['def', 'trait_metadata(self,', 'traitname,', 'key,', 'default=None):', 'try:', 'trait', '=', 'getattr(self.__class__,', 'traitname)', 'except', 'AttributeError:', 'raise', "TraitError('Class", '%s', 'does', 'not', 'have', 'a', 'trait', 'named', "%s'", '%', '(self.__class__.__name__,', 'traitname))', 'metadata_name', '... | 893,783 |
llSourcell/chatbot_tutorial | textdata.py | TextData.detokenize | detokenize | Slightly cleaner version of joining with spaces. | [
"Slightly",
"cleaner",
"version",
"of",
"joining",
"with",
"spaces."
] | def detokenize(self, tokens):
return ''.join([' ' + t if not t.startswith("'") and t not in string.punctuation else t for t in tokens]).strip().capitalize() | ['def', 'detokenize(self,', 'tokens):', 'return', "''.join(['", "'", '+', 't', 'if', 'not', 't.startswith("\'")', 'and', 't', 'not', 'in', 'string.punctuation', 'else', 't', 'for', 't', 'in', 'tokens]).strip().capitalize()'] | 104,786 |
nicknochnack/RealTimeSignLanguageTFJS | segmentation_model_test.py | SegmentationNetworkTest.test_serialize_deserialize | test_serialize_deserialize | Validate the network can be serialized and deserialized. | [
"Validate",
"the",
"network",
"can",
"be",
"serialized",
"and",
"deserialized."
] | def test_serialize_deserialize(self):
num_classes = 3
backbone = backbones.ResNet(model_id=50)
decoder = fpn.FPN(input_specs=backbone.output_specs, min_level=3, max_level=7)
head = segmentation_heads.SegmentationHead(num_classes, level=3)
model = segmentation_model.SegmentationModel(backbone=backbon... | ['def', 'test_serialize_deserialize(self):', 'num_classes', '=', '3', 'backbone', '=', 'backbones.ResNet(model_id=50)', 'decoder', '=', 'fpn.FPN(input_specs=backbone.output_specs,', 'min_level=3,', 'max_level=7)', 'head', '=', 'segmentation_heads.SegmentationHead(num_classes,', 'level=3)', 'model', '=', 'segmentation_m... | 850,788 |
lektor/lektor-archive | environment.py | Environment.new_pad | new_pad | Convenience function to create a database and pad. | [
"Convenience",
"function",
"to",
"create",
"a",
"database",
"and",
"pad."
] | def new_pad(self):
from lektor.db import Database
return Database(self).new_pad() | ['def', 'new_pad(self):', 'from', 'lektor.db', 'import', 'Database', 'return', 'Database(self).new_pad()'] | 216,458 |
renmengye/few-shot-ssl-public | prototypical.py | sq_dist_loss | sq_dist_loss | Squared distance based loss function. | [
"Squared",
"distance",
"based",
"loss",
"function."
] | def sq_dist_loss(cluster_centers, data):
min_dist = tf.reduce_min(-compute_logits(cluster_centers, data), [1])
return tf.reduce_mean(min_dist) | ['def', 'sq_dist_loss(cluster_centers,', 'data):', 'min_dist', '=', 'tf.reduce_min(-compute_logits(cluster_centers,', 'data),', '[1])', 'return', 'tf.reduce_mean(min_dist)'] | 179,989 |
eddylau328/fyp-artificial-intelligence-ac-control-device | message_test.py | MessageTest.testExtendFloatWithPythonList | testExtendFloatWithPythonList | Test extending repeated float fields with python lists. | [
"Test",
"extending",
"repeated",
"float",
"fields",
"with",
"python",
"lists."
] | def testExtendFloatWithPythonList(self, message_module):
m = message_module.TestAllTypes()
self.assertSequenceEqual([], m.repeated_float)
m.repeated_float.extend([0.0])
self.assertSequenceEqual([0.0], m.repeated_float)
m.repeated_float.extend([1.0, 2.0])
self.assertSequenceEqual([0.0, 1.0, 2.0],... | ['def', 'testExtendFloatWithPythonList(self,', 'message_module):', 'm', '=', 'message_module.TestAllTypes()', 'self.assertSequenceEqual([],', 'm.repeated_float)', 'm.repeated_float.extend([0.0])', 'self.assertSequenceEqual([0.0],', 'm.repeated_float)', 'm.repeated_float.extend([1.0,', '2.0])', 'self.assertSequenceEqual... | 215,340 |
tensorly/quantum | quantum_context.py | set_engine_mode | set_engine_mode | Set global engine mode in execution context. | [
"Set",
"global",
"engine",
"mode",
"in",
"execution",
"context."
] | def set_engine_mode(mode):
q_context()._set_engine_mode(mode) | ['def', 'set_engine_mode(mode):', 'q_context()._set_engine_mode(mode)'] | 835,087 |
rudranil723/mini-main | base.py | Operation.reduce | reduce | Return either a list of operations the actual operation should be replaced with or a boolean that indicates whether or not the specified operation can be optimized across. | [
"Return",
"either",
"a",
"list",
"of",
"operations",
"the",
"actual",
"operation",
"should",
"be",
"replaced",
"with",
"or",
"a",
"boolean",
"that",
"indicates",
"whether",
"or",
"not",
"the",
"specified",
"operation",
"can",
"be",
"optimized",
"across."
] | def reduce(self, operation, in_between, app_label=None):
if self.elidable:
return [operation]
elif operation.elidable:
return [self]
return False | ['def', 'reduce(self,', 'operation,', 'in_between,', 'app_label=None):', 'if', 'self.elidable:', 'return', '[operation]', 'elif', 'operation.elidable:', 'return', '[self]', 'return', 'False'] | 315,977 |
jxhe/unify-parameter-efficient-tuning | convert_marian_to_pytorch.py | convert_hf_name_to_opus_name | convert_hf_name_to_opus_name | Relies on the assumption that there are no language codes like pt_br in models that are not in GROUP_TO_OPUS_NAME. | [
"Relies",
"on",
"the",
"assumption",
"that",
"there",
"are",
"no",
"language",
"codes",
"like",
"pt_br",
"in",
"models",
"that",
"are",
"not",
"in",
"GROUP_TO_OPUS_NAME."
] | def convert_hf_name_to_opus_name(hf_model_name):
hf_model_name = remove_prefix(hf_model_name, ORG_NAME)
if hf_model_name in GROUP_TO_OPUS_NAME:
opus_w_prefix = GROUP_TO_OPUS_NAME[hf_model_name]
else:
opus_w_prefix = hf_model_name.replace('_', '+')
return remove_prefix(opus_w_prefix, 'opu... | ['def', 'convert_hf_name_to_opus_name(hf_model_name):', 'hf_model_name', '=', 'remove_prefix(hf_model_name,', 'ORG_NAME)', 'if', 'hf_model_name', 'in', 'GROUP_TO_OPUS_NAME:', 'opus_w_prefix', '=', 'GROUP_TO_OPUS_NAME[hf_model_name]', 'else:', 'opus_w_prefix', '=', "hf_model_name.replace('_',", "'+')", 'return', 'remove... | 949,008 |
apeterswu/RL4NMT | optimize.py | learning_rate_decay | learning_rate_decay | Inverse-decay learning rate until warmup_steps, then decay. | [
"Inverse-decay",
"learning",
"rate",
"until",
"warmup_steps,",
"then",
"decay."
] | def learning_rate_decay(hparams, num_worker_replicas=1, num_train_steps=1):
warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps * num_worker_replicas)
step = tf.to_float(tf.train.get_or_create_global_step())
if hparams.learning_rate_decay_scheme == 'noam':
return 5000.0 * hparams.hidden_si... | ['def', 'learning_rate_decay(hparams,', 'num_worker_replicas=1,', 'num_train_steps=1):', 'warmup_steps', '=', 'tf.to_float(hparams.learning_rate_warmup_steps', '*', 'num_worker_replicas)', 'step', '=', 'tf.to_float(tf.train.get_or_create_global_step())', 'if', 'hparams.learning_rate_decay_scheme', '==', "'noam':", 'ret... | 331,791 |
lllingfa/computer_vision_with_python | harris.py | get_harris_points | get_harris_points | Return corners from a Harris response image min_dist is the minimum number of pixels separating corners and image boundary. | [
"Return",
"corners",
"from",
"a",
"Harris",
"response",
"image",
"min_dist",
"is",
"the",
"minimum",
"number",
"of",
"pixels",
"separating",
"corners",
"and",
"image",
"boundary."
] | def get_harris_points(harrisim, min_dist=10, threshold=0.9):
corner_threshold = harrisim.max() * threshold
harrisim_t = (harrisim > corner_threshold) * 1
coords = array(harrisim_t.nonzero()).T
candidate_values = [harrisim[c[0], c[1]] for c in coords]
index = argsort(candidate_values)
allowed_loc... | ['def', 'get_harris_points(harrisim,', 'min_dist=10,', 'threshold=0.9):', 'corner_threshold', '=', 'harrisim.max()', '*', 'threshold', 'harrisim_t', '=', '(harrisim', '>', 'corner_threshold)', '*', '1', 'coords', '=', 'array(harrisim_t.nonzero()).T', 'candidate_values', '=', '[harrisim[c[0],', 'c[1]]', 'for', 'c', 'in'... | 514,895 |
sek788432/Waymo-2D-Object-Detection | common.py | define_keras_flags | define_keras_flags | Define flags for Keras models. | [
"Define",
"flags",
"for",
"Keras",
"models."
] | def define_keras_flags(model=False, optimizer=False, pretrained_filepath=False):
flags_core.define_base(clean=True, num_gpu=True, run_eagerly=True, train_epochs=True, epochs_between_evals=True, distribution_strategy=True)
flags_core.define_performance(num_parallel_calls=False, synthetic_data=True, dtype=True, a... | ['def', 'define_keras_flags(model=False,', 'optimizer=False,', 'pretrained_filepath=False):', 'flags_core.define_base(clean=True,', 'num_gpu=True,', 'run_eagerly=True,', 'train_epochs=True,', 'epochs_between_evals=True,', 'distribution_strategy=True)', 'flags_core.define_performance(num_parallel_calls=False,', 'synthet... | 973,793 |
sek788432/Waymo-2D-Object-Detection | target_assigner.py | filter_mask_overlap_min_area | filter_mask_overlap_min_area | If a pixel belongs to 2 instances, remove it from the larger instance. | [
"If",
"a",
"pixel",
"belongs",
"to",
"2",
"instances,",
"remove",
"it",
"from",
"the",
"larger",
"instance."
] | def filter_mask_overlap_min_area(masks):
num_instances = tf.shape(masks)[0]
def _filter_min_area():
areas = tf.reduce_sum(masks, axis=[1, 2], keepdims=True)
per_pixel_area = masks * areas
per_pixel_area = masks * per_pixel_area + (1 - masks) * per_pixel_area.dtype.max
min_index ... | ['def', 'filter_mask_overlap_min_area(masks):', 'num_instances', '=', 'tf.shape(masks)[0]', 'def', '_filter_min_area():', 'areas', '=', 'tf.reduce_sum(masks,', 'axis=[1,', '2],', 'keepdims=True)', 'per_pixel_area', '=', 'masks', '*', 'areas', 'per_pixel_area', '=', 'masks', '*', 'per_pixel_area', '+', '(1', '-', 'masks... | 974,901 |
CentML/DeepView.Profile | utils.py | log_env_info | log_env_info | Prints information about execution environment. | [
"Prints",
"information",
"about",
"execution",
"environment."
] | def log_env_info():
logging.info('Collecting environment information...')
env_info = torch.utils.collect_env.get_pretty_env_info()
logging.info(f'{env_info}') | ['def', 'log_env_info():', "logging.info('Collecting", 'environment', "information...')", 'env_info', '=', 'torch.utils.collect_env.get_pretty_env_info()', "logging.info(f'{env_info}')"] | 540,829 |
ahthie7u/cockpit | problem.py | Problem.make_id | make_id | Return a human-readable id. | [
"Return",
"a",
"human-readable",
"id."
] | def make_id(self):
self.set_up()
prefix = self.id_prefix + '-' if self.id_prefix != '' else ''
id_str = (prefix + f'device={self.device}' + f'-data={self.data}' + f'-model={self.model}' + f'-individual-loss={self.individual_loss_function}' + f'-loss={self.loss_function}' + f'-optimizer={self.optimizer}').re... | ['def', 'make_id(self):', 'self.set_up()', 'prefix', '=', 'self.id_prefix', '+', "'-'", 'if', 'self.id_prefix', '!=', "''", 'else', "''", 'id_str', '=', '(prefix', '+', "f'device={self.device}'", '+', "f'-data={self.data}'", '+', "f'-model={self.model}'", '+', "f'-individual-loss={self.individual_loss_function}'", '+',... | 492,940 |
liang-hou/slimgan | slimmable_cgan_pd_32.py | SlimmableCGANPDDiscriminator32.forward | forward | Feedforwards a batch of real/fake images and produces a batch of GAN logits. | [
"Feedforwards",
"a",
"batch",
"of",
"real/fake",
"images",
"and",
"produces",
"a",
"batch",
"of",
"GAN",
"logits."
] | def forward(self, x, y=None):
idx = int(FLAGS.width_mult / 0.25) - 1
h = x
h = self.block1s[-1 if self.n_share > 0 else idx](h)
h = self.block2s[-1 if self.n_share > 1 else idx](h)
h = self.block3s[-1 if self.n_share > 2 else idx](h)
h = self.block4s[-1 if self.n_share > 3 else idx](h)
h = s... | ['def', 'forward(self,', 'x,', 'y=None):', 'idx', '=', 'int(FLAGS.width_mult', '/', '0.25)', '-', '1', 'h', '=', 'x', 'h', '=', 'self.block1s[-1', 'if', 'self.n_share', '>', '0', 'else', 'idx](h)', 'h', '=', 'self.block2s[-1', 'if', 'self.n_share', '>', '1', 'else', 'idx](h)', 'h', '=', 'self.block3s[-1', 'if', 'self.n... | 878,303 |
microsoft/nni | graph.py | NetworkDescriptor.add_skip_connection | add_skip_connection | Add a skip-connection to the descriptor. | [
"Add",
"a",
"skip-connection",
"to",
"the",
"descriptor."
] | def add_skip_connection(self, u, v, connection_type):
if connection_type not in [self.CONCAT_CONNECT, self.ADD_CONNECT]:
raise ValueError('connection_type should be NetworkDescriptor.CONCAT_CONNECT or NetworkDescriptor.ADD_CONNECT.')
self.skip_connections.append((u, v, connection_type)) | ['def', 'add_skip_connection(self,', 'u,', 'v,', 'connection_type):', 'if', 'connection_type', 'not', 'in', '[self.CONCAT_CONNECT,', 'self.ADD_CONNECT]:', 'raise', "ValueError('connection_type", 'should', 'be', 'NetworkDescriptor.CONCAT_CONNECT', 'or', "NetworkDescriptor.ADD_CONNECT.')", 'self.skip_connections.append((... | 728,362 |
pipermerriam/flex | test_match_request_path_to_api_path.py | test_regex_character_escaping | test_regex_character_escaping | Test that the expected characters get escaped. | [
"Test",
"that",
"the",
"expected",
"characters",
"get",
"escaped."
] | def test_regex_character_escaping(input_, expected):
actual = escape_regex_special_chars(input_)
assert actual == expected | ['def', 'test_regex_character_escaping(input_,', 'expected):', 'actual', '=', 'escape_regex_special_chars(input_)', 'assert', 'actual', '==', 'expected'] | 211,330 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | MakePmfFromDict | MakePmfFromDict | Makes a PMF from a map from values to probabilities. | [
"Makes",
"a",
"PMF",
"from",
"a",
"map",
"from",
"values",
"to",
"probabilities."
] | def MakePmfFromDict(d, label=None):
return Pmf(d, label=label) | ['def', 'MakePmfFromDict(d,', 'label=None):', 'return', 'Pmf(d,', 'label=label)'] | 19,306 |
kubeflow/pipelines | pipeline_spec_builder.py | merge_platform_specs | merge_platform_specs | Merges a sub_msg PlatformSpec into the main_msg PlatformSpec, leaving the sub_msg unchanged. | [
"Merges",
"a",
"sub_msg",
"PlatformSpec",
"into",
"the",
"main_msg",
"PlatformSpec,",
"leaving",
"the",
"sub_msg",
"unchanged."
] | def merge_platform_specs(main_msg: pipeline_spec_pb2.PlatformSpec, sub_msg: pipeline_spec_pb2.PlatformSpec) -> None:
for (platform_key, single_platform_spec) in sub_msg.platforms.items():
merge_platform_deployment_config(main_msg.platforms[platform_key].deployment_spec, single_platform_spec.deployment_spec) | ['def', 'merge_platform_specs(main_msg:', 'pipeline_spec_pb2.PlatformSpec,', 'sub_msg:', 'pipeline_spec_pb2.PlatformSpec)', '->', 'None:', 'for', '(platform_key,', 'single_platform_spec)', 'in', 'sub_msg.platforms.items():', 'merge_platform_deployment_config(main_msg.platforms[platform_key].deployment_spec,', 'single_p... | 779,940 |
deepmind/dm_control | views.py | MujocoDepthBuffer.render | render | Renders the overlay on screen. | [
"Renders",
"the",
"overlay",
"on",
"screen."
] | def render(self, context, viewport):
width_adjustment = viewport.width % 4
rect_shape = (viewport.width - width_adjustment, viewport.height)
if self._depth_buffer is None or self._depth_buffer.shape != rect_shape:
self._depth_buffer = np.zeros((viewport.width, viewport.height), np.float32)
mujoc... | ['def', 'render(self,', 'context,', 'viewport):', 'width_adjustment', '=', 'viewport.width', '%', '4', 'rect_shape', '=', '(viewport.width', '-', 'width_adjustment,', 'viewport.height)', 'if', 'self._depth_buffer', 'is', 'None', 'or', 'self._depth_buffer.shape', '!=', 'rect_shape:', 'self._depth_buffer', '=', 'np.zeros... | 166,644 |
s3prl/s3prl | wav2vec2_model.py | RelPositionMultiHeadedAttention.forward | forward | Compute scaled dot product attention. | [
"Compute",
"scaled",
"dot",
"product",
"attention."
] | def forward(self, query, key, value, pos_emb, key_padding_mask=None, **kwargs):
query = query.transpose(0, 1)
key = key.transpose(0, 1)
value = value.transpose(0, 1)
pos_emb = pos_emb.transpose(0, 1)
(q, k, v) = self.forward_qkv(query, key, value)
q = q.transpose(1, 2)
n_batch_pos = pos_emb.... | ['def', 'forward(self,', 'query,', 'key,', 'value,', 'pos_emb,', 'key_padding_mask=None,', '**kwargs):', 'query', '=', 'query.transpose(0,', '1)', 'key', '=', 'key.transpose(0,', '1)', 'value', '=', 'value.transpose(0,', '1)', 'pos_emb', '=', 'pos_emb.transpose(0,', '1)', '(q,', 'k,', 'v)', '=', 'self.forward_qkv(query... | 327,967 |
greydanus/mr_london | serving.py | WSGIRequestHandler.handle | handle | Handles a request ignoring dropped connections. | [
"Handles",
"a",
"request",
"ignoring",
"dropped",
"connections."
] | def handle(self):
rv = None
try:
rv = BaseHTTPRequestHandler.handle(self)
except (socket.error, socket.timeout) as e:
self.connection_dropped(e)
except Exception:
if self.server.ssl_context is None or not is_ssl_error():
raise
if self.server.shutdown_signal:
... | ['def', 'handle(self):', 'rv', '=', 'None', 'try:', 'rv', '=', 'BaseHTTPRequestHandler.handle(self)', 'except', '(socket.error,', 'socket.timeout)', 'as', 'e:', 'self.connection_dropped(e)', 'except', 'Exception:', 'if', 'self.server.ssl_context', 'is', 'None', 'or', 'not', 'is_ssl_error():', 'raise', 'if', 'self.serve... | 264,157 |
gunthercox/ChatterBot | test_mrecords.py | TestMRecordsImport.test_fromrecords_wmask | test_fromrecords_wmask | Tests construction from records w/ mask. | [
"Tests",
"construction",
"from",
"records",
"w/",
"mask."
] | def test_fromrecords_wmask(self):
(mrec, nrec, ddtype) = self.data
_mrec = fromrecords(nrec.tolist(), dtype=ddtype, mask=[0, 1, 0])
assert_equal_records(_mrec._data, mrec._data)
assert_equal(_mrec._mask.tolist(), [(0, 0, 0), (1, 1, 1), (0, 0, 0)])
_mrec = fromrecords(nrec.tolist(), dtype=ddtype, mas... | ['def', 'test_fromrecords_wmask(self):', '(mrec,', 'nrec,', 'ddtype)', '=', 'self.data', '_mrec', '=', 'fromrecords(nrec.tolist(),', 'dtype=ddtype,', 'mask=[0,', '1,', '0])', 'assert_equal_records(_mrec._data,', 'mrec._data)', 'assert_equal(_mrec._mask.tolist(),', '[(0,', '0,', '0),', '(1,', '1,', '1),', '(0,', '0,', '... | 532,141 |
pedrojrv/nucml | parsing.py | get_ame_originals | get_ame_originals | Request and store the three AME original files for further processing from the IAEA website. | [
"Request",
"and",
"store",
"the",
"three",
"AME",
"original",
"files",
"for",
"further",
"processing",
"from",
"the",
"IAEA",
"website."
] | def get_ame_originals(originals_directory):
mass16_txt = requests.get('https://www-nds.iaea.org/amdc/ame2016/mass16.txt').content
rct1_txt = requests.get('https://www-nds.iaea.org/amdc/ame2016/rct1-16.txt').content
rct2_txt = requests.get('https://www-nds.iaea.org/amdc/ame2016/rct2-16.txt').content
with... | ['def', 'get_ame_originals(originals_directory):', 'mass16_txt', '=', "requests.get('https://www-nds.iaea.org/amdc/ame2016/mass16.txt').content", 'rct1_txt', '=', "requests.get('https://www-nds.iaea.org/amdc/ame2016/rct1-16.txt').content", 'rct2_txt', '=', "requests.get('https://www-nds.iaea.org/amdc/ame2016/rct2-16.tx... | 249,677 |
huggingface/naacl_transfer_learning_tutorial | utils.py | add_logging_and_checkpoint_saving | add_logging_and_checkpoint_saving | Add to training engine tensorboard logging, progress bar with average loss, checkpoint saving and save training config. | [
"Add",
"to",
"training",
"engine",
"tensorboard",
"logging,",
"progress",
"bar",
"with",
"average",
"loss,",
"checkpoint",
"saving",
"and",
"save",
"training",
"config."
] | def add_logging_and_checkpoint_saving(trainer, evaluator, metrics, model, optimizer, args, prefix=''):
RunningAverage(output_transform=lambda x: x).attach(trainer, prefix + 'loss')
pbar = ProgressBar(persist=True)
pbar.attach(trainer, metric_names=[prefix + 'loss'])
evaluator.add_event_handler(Events.CO... | ['def', 'add_logging_and_checkpoint_saving(trainer,', 'evaluator,', 'metrics,', 'model,', 'optimizer,', 'args,', "prefix=''):", 'RunningAverage(output_transform=lambda', 'x:', 'x).attach(trainer,', 'prefix', '+', "'loss')", 'pbar', '=', 'ProgressBar(persist=True)', 'pbar.attach(trainer,', 'metric_names=[prefix', '+', "... | 651,696 |
Reinhardt-i/Artificial-Intelligence-SWE-323 | MiniMax Algorithm in tic_tac_toe.py | print_board | print_board | Print the current state of the Tic-Tac-Toe board. | [
"Print",
"the",
"current",
"state",
"of",
"the",
"Tic-Tac-Toe",
"board."
] | def print_board(board: List[List[str]]) -> None:
for row in board:
print(' '.join(row))
print() | ['def', 'print_board(board:', 'List[List[str]])', '->', 'None:', 'for', 'row', 'in', 'board:', "print('", "'.join(row))", 'print()'] | 91,521 |
open-mmlab/mmdetection3d | utils.py | yaw2local | yaw2local | Transform global yaw to local yaw (alpha in kitti) in camera coordinates, ranges from -pi to pi. | [
"Transform",
"global",
"yaw",
"to",
"local",
"yaw",
"(alpha",
"in",
"kitti)",
"in",
"camera",
"coordinates,",
"ranges",
"from",
"-pi",
"to",
"pi."
] | def yaw2local(yaw: Tensor, loc: Tensor) -> Tensor:
local_yaw = yaw - torch.atan2(loc[:, 0], loc[:, 2])
larger_idx = (local_yaw > np.pi).nonzero(as_tuple=False)
small_idx = (local_yaw < -np.pi).nonzero(as_tuple=False)
if len(larger_idx) != 0:
local_yaw[larger_idx] -= 2 * np.pi
if len(small_id... | ['def', 'yaw2local(yaw:', 'Tensor,', 'loc:', 'Tensor)', '->', 'Tensor:', 'local_yaw', '=', 'yaw', '-', 'torch.atan2(loc[:,', '0],', 'loc[:,', '2])', 'larger_idx', '=', '(local_yaw', '>', 'np.pi).nonzero(as_tuple=False)', 'small_idx', '=', '(local_yaw', '<', '-np.pi).nonzero(as_tuple=False)', 'if', 'len(larger_idx)', '!... | 632,293 |
LLNL/merlin | conditions.py | StudyOutputAware.glob | glob | Returns a regex string for the glob library to recursively find files with. | [
"Returns",
"a",
"regex",
"string",
"for",
"the",
"glob",
"library",
"to",
"recursively",
"find",
"files",
"with."
] | def glob(self, glob_string):
candidates = glob(glob_string)
if isinstance(candidates, list):
return sorted(candidates)[-1]
return candidates | ['def', 'glob(self,', 'glob_string):', 'candidates', '=', 'glob(glob_string)', 'if', 'isinstance(candidates,', 'list):', 'return', 'sorted(candidates)[-1]', 'return', 'candidates'] | 632,891 |
open-mmlab/mmselfsup | multi_prototypes.py | MultiPrototypes.forward | forward | Run forward for every prototype. | [
"Run",
"forward",
"for",
"every",
"prototype."
] | def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
out = []
for i in range(self.num_heads):
out.append(getattr(self, 'prototypes' + str(i))(x))
return out | ['def', 'forward(self,', 'x:', 'torch.Tensor)', '->', 'List[torch.Tensor]:', 'out', '=', '[]', 'for', 'i', 'in', 'range(self.num_heads):', 'out.append(getattr(self,', "'prototypes'", '+', 'str(i))(x))', 'return', 'out'] | 240,467 |
google-research/scenic | utils.py | compute_inner_product | compute_inner_product | Compute inner product between videos and text embeddings. | [
"Compute",
"inner",
"product",
"between",
"videos",
"and",
"text",
"embeddings."
] | def compute_inner_product(encoded_video, encoded_text):
assert len(encoded_video.shape) == 2
logging.info('Shape of encoded text is %s', encoded_text.shape)
assert len(encoded_text.shape) == 3 or len(encoded_text.shape) == 2
if len(encoded_text.shape) == 3:
inners = jnp.einsum('nd,mfd -> nmf', e... | ['def', 'compute_inner_product(encoded_video,', 'encoded_text):', 'assert', 'len(encoded_video.shape)', '==', '2', "logging.info('Shape", 'of', 'encoded', 'text', 'is', "%s',", 'encoded_text.shape)', 'assert', 'len(encoded_text.shape)', '==', '3', 'or', 'len(encoded_text.shape)', '==', '2', 'if', 'len(encoded_text.shap... | 847,496 |
keras-team/keras-cv | densenet_backbone.py | apply_conv_block | apply_conv_block | A building block for a dense block. | [
"A",
"building",
"block",
"for",
"a",
"dense",
"block."
] | def apply_conv_block(x, growth_rate, name=None):
if name is None:
name = f"conv_block_{keras.backend.get_uid('conv_block')}"
shortcut = x
x = keras.layers.BatchNormalization(axis=BN_AXIS, epsilon=BN_EPSILON, name=f'{name}_0_bn')(x)
x = keras.layers.Activation('relu', name=f'{name}_0_relu')(x)
... | ['def', 'apply_conv_block(x,', 'growth_rate,', 'name=None):', 'if', 'name', 'is', 'None:', 'name', '=', 'f"conv_block_{keras.backend.get_uid(\'conv_block\')}"', 'shortcut', '=', 'x', 'x', '=', 'keras.layers.BatchNormalization(axis=BN_AXIS,', 'epsilon=BN_EPSILON,', "name=f'{name}_0_bn')(x)", 'x', '=', "keras.layers.Acti... | 595,154 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | base.py | Tokens.module | module | Provides lazy import to the parser module. | [
"Provides",
"lazy",
"import",
"to",
"the",
"parser",
"module."
] | def module(self):
module = self.parserModule
if module:
return module
import java2python.lang.JavaParser as module
self.parserModule = module
return module | ['def', 'module(self):', 'module', '=', 'self.parserModule', 'if', 'module:', 'return', 'module', 'import', 'java2python.lang.JavaParser', 'as', 'module', 'self.parserModule', '=', 'module', 'return', 'module'] | 11,380 |
ajboyd2/vae_mpp | data.py | pad_and_combine_instances | pad_and_combine_instances | A collate function for padding and combining instance dictionaries. | [
"A",
"collate",
"function",
"for",
"padding",
"and",
"combining",
"instance",
"dictionaries."
] | def pad_and_combine_instances(batch, def_pad_value):
batch_size = len(batch)
max_seq_len = max(max((len(ex['ref_times']) for ex in batch)), max((len(ex['tgt_times']) for ex in batch)))
out_dict = _ld_to_dl(batch, max_seq_len, def_pad_value)
return {k: torch.stack(v, dim=0) for (k, v) in out_dict.items()... | ['def', 'pad_and_combine_instances(batch,', 'def_pad_value):', 'batch_size', '=', 'len(batch)', 'max_seq_len', '=', "max(max((len(ex['ref_times'])", 'for', 'ex', 'in', 'batch)),', "max((len(ex['tgt_times'])", 'for', 'ex', 'in', 'batch)))', 'out_dict', '=', '_ld_to_dl(batch,', 'max_seq_len,', 'def_pad_value)', 'return',... | 930,807 |
google-research/rigl | masked_test.py | MaskedTest.test_symmetric_mask_sparsity_half_full | test_symmetric_mask_sparsity_half_full | Tests shuffled mask generation, for a half-full mask. | [
"Tests",
"shuffled",
"mask",
"generation,",
"for",
"a",
"half-full",
"mask."
] | def test_symmetric_mask_sparsity_half_full(self):
mask = masked.symmetric_mask(self._masked_model, self._rng, 0.5)
param_len = len(self._masked_model.params['MaskedModule_0']['unmasked']['kernel'][:, 0])
mask_sum = jnp.sum(mask['MaskedModule_0']['kernel'][:, 0])
with self.subTest(name='symmetric_mask_va... | ['def', 'test_symmetric_mask_sparsity_half_full(self):', 'mask', '=', 'masked.symmetric_mask(self._masked_model,', 'self._rng,', '0.5)', 'param_len', '=', "len(self._masked_model.params['MaskedModule_0']['unmasked']['kernel'][:,", '0])', 'mask_sum', '=', "jnp.sum(mask['MaskedModule_0']['kernel'][:,", '0])', 'with', "se... | 841,488 |
jxhe/unify-parameter-efficient-tuning | run_hans.py | hans_data_collator | hans_data_collator | Data collator that removes the "pairID" key if present. | [
"Data",
"collator",
"that",
"removes",
"the",
"\"pairID\"",
"key",
"if",
"present."
] | def hans_data_collator(features: List[InputFeatures]) -> Dict[str, torch.Tensor]:
batch = default_data_collator(features)
_ = batch.pop('pairID', None)
return batch | ['def', 'hans_data_collator(features:', 'List[InputFeatures])', '->', 'Dict[str,', 'torch.Tensor]:', 'batch', '=', 'default_data_collator(features)', '_', '=', "batch.pop('pairID',", 'None)', 'return', 'batch'] | 948,086 |
AgileRL/AgileRL | evolvable_cnn.py | EvolvableCNN.short_dict | short_dict | Returns shortened version of model information in dictionary. | [
"Returns",
"shortened",
"version",
"of",
"model",
"information",
"in",
"dictionary."
] | def short_dict(self):
short_dict = {'channel_size': self.channel_size, 'kernal_size': self.kernal_size, 'stride_size': self.stride_size, 'hidden_size': self.hidden_size, 'num_atoms': self.num_atoms, 'mlp_activation': self.mlp_activation, 'cnn_activation': self.cnn_activation, 'layer_norm': self.layer_norm}
retu... | ['def', 'short_dict(self):', 'short_dict', '=', "{'channel_size':", 'self.channel_size,', "'kernal_size':", 'self.kernal_size,', "'stride_size':", 'self.stride_size,', "'hidden_size':", 'self.hidden_size,', "'num_atoms':", 'self.num_atoms,', "'mlp_activation':", 'self.mlp_activation,', "'cnn_activation':", 'self.cnn_ac... | 23,985 |
openvinotoolkit/training_extensions | visualizer.py | Visualizer.video_delay | video_delay | Check if video frames were inferenced faster than the original video FPS and delay visualizer if so. | [
"Check",
"if",
"video",
"frames",
"were",
"inferenced",
"faster",
"than",
"the",
"original",
"video",
"FPS",
"and",
"delay",
"visualizer",
"if",
"so."
] | def video_delay(self, elapsed_time: float, streamer: BaseStreamer):
if self.no_show:
return
if 'VIDEO' in str(streamer.get_type()):
orig_frame_time = 1 / streamer.fps()
if elapsed_time < orig_frame_time:
time.sleep(orig_frame_time - elapsed_time) | ['def', 'video_delay(self,', 'elapsed_time:', 'float,', 'streamer:', 'BaseStreamer):', 'if', 'self.no_show:', 'return', 'if', "'VIDEO'", 'in', 'str(streamer.get_type()):', 'orig_frame_time', '=', '1', '/', 'streamer.fps()', 'if', 'elapsed_time', '<', 'orig_frame_time:', 'time.sleep(orig_frame_time', '-', 'elapsed_time)... | 918,818 |
RE-OWOD/RE-OWOD | transform.py | RotationTransform.inverse | inverse | The inverse is to rotate it back with expand, and crop to get the original shape. | [
"The",
"inverse",
"is",
"to",
"rotate",
"it",
"back",
"with",
"expand,",
"and",
"crop",
"to",
"get",
"the",
"original",
"shape."
] | def inverse(self):
if not self.expand:
raise NotImplementedError()
rotation = RotationTransform(self.bound_h, self.bound_w, -self.angle, True, None, self.interp)
crop = CropTransform((rotation.bound_w - self.w) // 2, (rotation.bound_h - self.h) // 2, self.w, self.h)
return TransformList([rotatio... | ['def', 'inverse(self):', 'if', 'not', 'self.expand:', 'raise', 'NotImplementedError()', 'rotation', '=', 'RotationTransform(self.bound_h,', 'self.bound_w,', '-self.angle,', 'True,', 'None,', 'self.interp)', 'crop', '=', 'CropTransform((rotation.bound_w', '-', 'self.w)', '//', '2,', '(rotation.bound_h', '-', 'self.h)',... | 848,909 |
google/mentornet | cifar_eval.py | extract_resnet_features | extract_resnet_features | Not checked provide_resnet_noisy_data dataset might change. | [
"Not",
"checked",
"provide_resnet_noisy_data",
"dataset",
"might",
"change."
] | def extract_resnet_features(max_step_run=39000):
g = tf.Graph()
with g.as_default():
tf_global_step = tf.train.get_or_create_global_step()
(images, one_hot_labels, num_examples, num_of_classes, clean_labels, image_ids) = cifar_data_provider.provide_resnet_noisy_data(FLAGS.dataset_name, 'train', ... | ['def', 'extract_resnet_features(max_step_run=39000):', 'g', '=', 'tf.Graph()', 'with', 'g.as_default():', 'tf_global_step', '=', 'tf.train.get_or_create_global_step()', '(images,', 'one_hot_labels,', 'num_examples,', 'num_of_classes,', 'clean_labels,', 'image_ids)', '=', 'cifar_data_provider.provide_resnet_noisy_data(... | 632,522 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | base.py | LocalTree.parserTokens | parserTokens | Returns the sequence of tokens used to create this tree. | [
"Returns",
"the",
"sequence",
"of",
"tokens",
"used",
"to",
"create",
"this",
"tree."
] | def parserTokens(self):
return self.parser.input.tokens[self.tokenStartIndex:self.tokenStopIndex] | ['def', 'parserTokens(self):', 'return', 'self.parser.input.tokens[self.tokenStartIndex:self.tokenStopIndex]'] | 11,375 |
wutong8023/CoLL | modeling_tf_utils.py | shape_list | shape_list | Deal with dynamic shape in tensorflow cleanly. | [
"Deal",
"with",
"dynamic",
"shape",
"in",
"tensorflow",
"cleanly."
] | def shape_list(tensor: tf.Tensor) -> List[int]:
dynamic = tf.shape(tensor)
if tensor.shape == tf.TensorShape(None):
return dynamic
static = tensor.shape.as_list()
return [dynamic[i] if s is None else s for (i, s) in enumerate(static)] | ['def', 'shape_list(tensor:', 'tf.Tensor)', '->', 'List[int]:', 'dynamic', '=', 'tf.shape(tensor)', 'if', 'tensor.shape', '==', 'tf.TensorShape(None):', 'return', 'dynamic', 'static', '=', 'tensor.shape.as_list()', 'return', '[dynamic[i]', 'if', 's', 'is', 'None', 'else', 's', 'for', '(i,', 's)', 'in', 'enumerate(stati... | 496,326 |
rtlee9/recipe-summarization | prep_data.py | save_data_container | save_data_container | Save data container to disk in multiple pieces to keep under 2GB limit. | [
"Save",
"data",
"container",
"to",
"disk",
"in",
"multiple",
"pieces",
"to",
"keep",
"under",
"2GB",
"limit."
] | def save_data_container(data, filename_pickle):
with open(filename_pickle + '_train.pk', 'wb') as f:
pickle.dump(data.train, f)
with open(filename_pickle + '_validation.pk', 'wb') as f:
pickle.dump(data.validation, f)
with open(filename_pickle + '_test.pk', 'wb') as f:
pickle.dump(da... | ['def', 'save_data_container(data,', 'filename_pickle):', 'with', 'open(filename_pickle', '+', "'_train.pk',", "'wb')", 'as', 'f:', 'pickle.dump(data.train,', 'f)', 'with', 'open(filename_pickle', '+', "'_validation.pk',", "'wb')", 'as', 'f:', 'pickle.dump(data.validation,', 'f)', 'with', 'open(filename_pickle', '+', "... | 309,069 |
f-dangel/cockpit | cockpit.py | Cockpit.add | add | Add quantity to tracked quantities. | [
"Add",
"quantity",
"to",
"tracked",
"quantities."
] | def add(self, quantity):
if not isinstance(quantity, Quantity):
raise ValueError(f'Added quantities must be instances of Quantity. Got {quantity}')
else:
self.quantities.append(quantity) | ['def', 'add(self,', 'quantity):', 'if', 'not', 'isinstance(quantity,', 'Quantity):', 'raise', "ValueError(f'Added", 'quantities', 'must', 'be', 'instances', 'of', 'Quantity.', 'Got', "{quantity}')", 'else:', 'self.quantities.append(quantity)'] | 492,501 |
RasaHQ/rasa | trackers.py | DialogueStateTracker.freeze_current_state | freeze_current_state | Convert State dict into a hashable format FrozenState. | [
"Convert",
"State",
"dict",
"into",
"a",
"hashable",
"format",
"FrozenState."
] | def freeze_current_state(state: State) -> FrozenState:
return frozenset({key: frozenset(values.items()) if isinstance(values, Dict) else frozenset(values) for (key, values) in state.items()}.items()) | ['def', 'freeze_current_state(state:', 'State)', '->', 'FrozenState:', 'return', 'frozenset({key:', 'frozenset(values.items())', 'if', 'isinstance(values,', 'Dict)', 'else', 'frozenset(values)', 'for', '(key,', 'values)', 'in', 'state.items()}.items())'] | 837,525 |
LukasHedegaard/co3d | decoder.py | decode | decode | Decode the video and perform temporal sampling. | [
"Decode",
"the",
"video",
"and",
"perform",
"temporal",
"sampling."
] | def decode(container, sampling_rate, num_frames, clip_idx=-1, num_clips=10, video_meta=None, target_fps=30, backend='pyav', max_spatial_scale=0):
assert clip_idx >= -1, 'Not valid clip_idx {}'.format(clip_idx)
try:
if backend == 'pyav':
(frames, fps, decode_all_video) = pyav_decode(container... | ['def', 'decode(container,', 'sampling_rate,', 'num_frames,', 'clip_idx=-1,', 'num_clips=10,', 'video_meta=None,', 'target_fps=30,', "backend='pyav',", 'max_spatial_scale=0):', 'assert', 'clip_idx', '>=', '-1,', "'Not", 'valid', 'clip_idx', "{}'.format(clip_idx)", 'try:', 'if', 'backend', '==', "'pyav':", '(frames,', '... | 124,078 |
triaquae/triaquae | numbertheory.py | inverse_mod | inverse_mod | Inverse of a mod m. | [
"Inverse",
"of",
"a",
"mod",
"m."
] | def inverse_mod(a, m):
if a < 0 or m <= a:
a = a % m
(c, d) = (a, m)
(uc, vc, ud, vd) = (1, 0, 0, 1)
while c != 0:
(q, c, d) = divmod(d, c) + (c,)
(uc, vc, ud, vd) = (ud - q * uc, vd - q * vc, uc, vc)
assert d == 1
if ud > 0:
return ud
else:
return ud ... | ['def', 'inverse_mod(a,', 'm):', 'if', 'a', '<', '0', 'or', 'm', '<=', 'a:', 'a', '=', 'a', '%', 'm', '(c,', 'd)', '=', '(a,', 'm)', '(uc,', 'vc,', 'ud,', 'vd)', '=', '(1,', '0,', '0,', '1)', 'while', 'c', '!=', '0:', '(q,', 'c,', 'd)', '=', 'divmod(d,', 'c)', '+', '(c,)', '(uc,', 'vc,', 'ud,', 'vd)', '=', '(ud', '-', ... | 356,727 |
apeterswu/RL4NMT | modality.py | Modality.top_dimensionality | top_dimensionality | Integer, the last dimension of the predictions (vocab size). | [
"Integer,",
"the",
"last",
"dimension",
"of",
"the",
"predictions",
"(vocab",
"size)."
] | def top_dimensionality(self):
raise NotImplementedError('Abstract Method') | ['def', 'top_dimensionality(self):', 'raise', "NotImplementedError('Abstract", "Method')"] | 331,781 |
43Carrig/recurrent_neural_networks_practice | categorical.py | Categorical.probs | probs | Vector of coordinatewise probabilities. | [
"Vector",
"of",
"coordinatewise",
"probabilities."
] | def probs(self):
return self._probs | ['def', 'probs(self):', 'return', 'self._probs'] | 339,175 |
voidking/object-detection | model.py | yolo_head | yolo_head | Convert final layer features to bounding box parameters. | [
"Convert",
"final",
"layer",
"features",
"to",
"bounding",
"box",
"parameters."
] | def yolo_head(feats, anchors, num_classes, n):
num_anchors = len(anchors)
anchors_tensor = K.reshape(K.constant(anchors), [1, 1, 1, num_anchors, 2])
conv_dims = K.shape(feats)[1:3]
conv_height_index = K.arange(0, stop=conv_dims[0])
conv_width_index = K.arange(0, stop=conv_dims[1])
conv_height_in... | ['def', 'yolo_head(feats,', 'anchors,', 'num_classes,', 'n):', 'num_anchors', '=', 'len(anchors)', 'anchors_tensor', '=', 'K.reshape(K.constant(anchors),', '[1,', '1,', '1,', 'num_anchors,', '2])', 'conv_dims', '=', 'K.shape(feats)[1:3]', 'conv_height_index', '=', 'K.arange(0,', 'stop=conv_dims[0])', 'conv_width_index'... | 747,714 |
thuml/Transfer-Learning-Library | bbox_adaptation.py | clamp | clamp | clamp (limit) the values in boxes within the widths and heights of the image. | [
"clamp",
"(limit)",
"the",
"values",
"in",
"boxes",
"within",
"the",
"widths",
"and",
"heights",
"of",
"the",
"image."
] | def clamp(boxes, widths, heights):
clamped_boxes = []
for (box, w, h) in zip(boxes, widths, heights):
clamped_boxes.append(clamp_single(box, w, h))
return torch.stack(clamped_boxes, dim=0) | ['def', 'clamp(boxes,', 'widths,', 'heights):', 'clamped_boxes', '=', '[]', 'for', '(box,', 'w,', 'h)', 'in', 'zip(boxes,', 'widths,', 'heights):', 'clamped_boxes.append(clamp_single(box,', 'w,', 'h))', 'return', 'torch.stack(clamped_boxes,', 'dim=0)'] | 921,004 |
georghess/voxel-mae | coord_transform.py | extract_2d_info | extract_2d_info | Extract image augmentation information from img_meta. | [
"Extract",
"image",
"augmentation",
"information",
"from",
"img_meta."
] | def extract_2d_info(img_meta, tensor):
img_shape = img_meta['img_shape']
ori_shape = img_meta['ori_shape']
(img_h, img_w, _) = img_shape
(ori_h, ori_w, _) = ori_shape
img_scale_factor = tensor.new_tensor(img_meta['scale_factor'][:2]) if 'scale_factor' in img_meta else tensor.new_tensor([1.0, 1.0])
... | ['def', 'extract_2d_info(img_meta,', 'tensor):', 'img_shape', '=', "img_meta['img_shape']", 'ori_shape', '=', "img_meta['ori_shape']", '(img_h,', 'img_w,', '_)', '=', 'img_shape', '(ori_h,', 'ori_w,', '_)', '=', 'ori_shape', 'img_scale_factor', '=', "tensor.new_tensor(img_meta['scale_factor'][:2])", 'if', "'scale_facto... | 380,694 |
devashish-patel/webcam-motion-detector | lexer.py | Lexer.wrap | wrap | This is called with the stream as returned by `tokenize` and wraps every token in a :class:`Token` and converts the value. | [
"This",
"is",
"called",
"with",
"the",
"stream",
"as",
"returned",
"by",
"`tokenize`",
"and",
"wraps",
"every",
"token",
"in",
"a",
":class:`Token`",
"and",
"converts",
"the",
"value."
] | def wrap(self, stream, name=None, filename=None):
for (lineno, token, value) in stream:
if token in ignored_tokens:
continue
elif token == 'linestatement_begin':
token = 'block_begin'
elif token == 'linestatement_end':
token = 'block_end'
elif toke... | ['def', 'wrap(self,', 'stream,', 'name=None,', 'filename=None):', 'for', '(lineno,', 'token,', 'value)', 'in', 'stream:', 'if', 'token', 'in', 'ignored_tokens:', 'continue', 'elif', 'token', '==', "'linestatement_begin':", 'token', '=', "'block_begin'", 'elif', 'token', '==', "'linestatement_end':", 'token', '=', "'blo... | 979,791 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.