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 |
|---|---|---|---|---|---|---|---|---|
ajMIT95/MIT_Artificial_Intelligence_Labs | lab0.py | create_multiplier_function | create_multiplier_function | Given a multiplier m, returns a function that multiplies its input by m. | [
"Given",
"a",
"multiplier",
"m,",
"returns",
"a",
"function",
"that",
"multiplies",
"its",
"input",
"by",
"m."
] | def create_multiplier_function(m):
def multiply(input):
return input * m
return multiply | ['def', 'create_multiplier_function(m):', 'def', 'multiply(input):', 'return', 'input', '*', 'm', 'return', 'multiply'] | 239,184 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | network_units.py | linked_embeddings_name | linked_embeddings_name | Returns the name of the linked embedding matrix for some channel ID. | [
"Returns",
"the",
"name",
"of",
"the",
"linked",
"embedding",
"matrix",
"for",
"some",
"channel",
"ID."
] | def linked_embeddings_name(channel_id):
return 'linked_embedding_matrix_%d' % channel_id | ['def', 'linked_embeddings_name(channel_id):', 'return', "'linked_embedding_matrix_%d'", '%', 'channel_id'] | 111,219 |
Erotemic/vtool_ibeis | other.py | componentwise_dot | componentwise_dot | a dot product is a componentwise multiplication of two vector and then a sum. | [
"a",
"dot",
"product",
"is",
"a",
"componentwise",
"multiplication",
"of",
"two",
"vector",
"and",
"then",
"a",
"sum."
] | def componentwise_dot(arr1, arr2):
cosangle = np.multiply(arr1, arr2).sum(axis=-1).T
return cosangle | ['def', 'componentwise_dot(arr1,', 'arr2):', 'cosangle', '=', 'np.multiply(arr1,', 'arr2).sum(axis=-1).T', 'return', 'cosangle'] | 940,700 |
deep-learning-indaba/Baobab | tests.py | ResponseTagAPITest.test_tag_non_admin_non_reviewer | test_tag_non_admin_non_reviewer | Test that a non admin and non reviewer can't add a tag. | [
"Test",
"that",
"a",
"non",
"admin",
"and",
"non",
"reviewer",
"can't",
"add",
"a",
"tag."
] | def test_tag_non_admin_non_reviewer(self):
self._seed_static_data()
params = {'event_id': self.event1.id, 'tag_id': self.tag1.id, 'response_id': self.response1.id}
response = self.app.post('/api/v1/responsetag', headers=self.get_auth_header_for('user2@mail.com'), json=params)
self.assertEqual(response.s... | ['def', 'test_tag_non_admin_non_reviewer(self):', 'self._seed_static_data()', 'params', '=', "{'event_id':", 'self.event1.id,', "'tag_id':", 'self.tag1.id,', "'response_id':", 'self.response1.id}', 'response', '=', "self.app.post('/api/v1/responsetag',", "headers=self.get_auth_header_for('user2@mail.com'),", 'json=para... | 94,215 |
microsoft/maro | project_generator.py | generate_environment | generate_environment | Generate a common template environment. | [
"Generate",
"a",
"common",
"template",
"environment."
] | def generate_environment():
env = Environment(loader=PackageLoader('maro', 'cli/project_generator/templates'), trim_blocks=True)
return env | ['def', 'generate_environment():', 'env', '=', "Environment(loader=PackageLoader('maro',", "'cli/project_generator/templates'),", 'trim_blocks=True)', 'return', 'env'] | 628,326 |
reihaneh-torkzadehmahani/DP-CGAN | gaussian_query.py | GaussianAverageQuery.initial_global_state | initial_global_state | Returns the initial global state for the GaussianAverageQuery. | [
"Returns",
"the",
"initial",
"global",
"state",
"for",
"the",
"GaussianAverageQuery."
] | def initial_global_state(self):
sum_global_state = self._numerator.initial_global_state()
return self._GlobalState(sum_global_state, float(self._denominator)) | ['def', 'initial_global_state(self):', 'sum_global_state', '=', 'self._numerator.initial_global_state()', 'return', 'self._GlobalState(sum_global_state,', 'float(self._denominator))'] | 552,330 |
ifwe/digsby | buddyliststore.py | BuddyListStore.save_data | save_data | Returns the data to saved to the Digsby server. | [
"Returns",
"the",
"data",
"to",
"saved",
"to",
"the",
"Digsby",
"server."
] | def save_data(self):
self._update_order_from_sorter()
return dict(metacontacts=self.metacontacts.save_data(), order=dict(contacts=self._filtered_contacts(), groups=self.order['groups']), info=dict(((k, v) for (k, v) in self.info.iteritems() if v and any(v.values()) and (k is not None)))) | ['def', 'save_data(self):', 'self._update_order_from_sorter()', 'return', 'dict(metacontacts=self.metacontacts.save_data(),', 'order=dict(contacts=self._filtered_contacts(),', "groups=self.order['groups']),", 'info=dict(((k,', 'v)', 'for', '(k,', 'v)', 'in', 'self.info.iteritems()', 'if', 'v', 'and', 'any(v.values())',... | 185,217 |
deepmind/meltingpot | fruit_market.py | get_water | get_water | Get an animated water game object. | [
"Get",
"an",
"animated",
"water",
"game",
"object."
] | def get_water():
layer = 'background'
water = {'name': 'water_{}'.format(layer), 'components': [{'component': 'StateManager', 'kwargs': {'initialState': 'water_1', 'stateConfigs': [{'state': 'water_1', 'layer': layer, 'sprite': 'water_1', 'groups': ['water']}, {'state': 'water_2', 'layer': layer, 'sprite': 'wat... | ['def', 'get_water():', 'layer', '=', "'background'", 'water', '=', "{'name':", "'water_{}'.format(layer),", "'components':", "[{'component':", "'StateManager',", "'kwargs':", "{'initialState':", "'water_1',", "'stateConfigs':", "[{'state':", "'water_1',", "'layer':", 'layer,', "'sprite':", "'water_1',", "'groups':", "... | 285,366 |
microsoft/InnerEye-DeepLearning | metrics_dict.py | Hue.get_predictions | get_predictions | Return a concatenated copy of the roc predictions stored internally. | [
"Return",
"a",
"concatenated",
"copy",
"of",
"the",
"roc",
"predictions",
"stored",
"internally."
] | def get_predictions(self) -> np.ndarray:
return Hue._concat_if_needed(self.predictions) | ['def', 'get_predictions(self)', '->', 'np.ndarray:', 'return', 'Hue._concat_if_needed(self.predictions)'] | 612,961 |
deepmind/meltingpot | allelopathic_harvest.py | create_avatar_object | create_avatar_object | Return the avatar for the player numbered `player_idx`. | [
"Return",
"the",
"avatar",
"for",
"the",
"player",
"numbered",
"`player_idx`."
] | def create_avatar_object(player_idx: int, most_tasty_berry_idx: int) -> Dict[str, Any]:
lua_index = player_idx + 1
lua_most_tasty_berry_idx = most_tasty_berry_idx + 1
live_state_name = 'player{}'.format(lua_index)
avatar_sprite_name = 'avatarSprite{}'.format(lua_index)
avatar_object = {'name': 'avat... | ['def', 'create_avatar_object(player_idx:', 'int,', 'most_tasty_berry_idx:', 'int)', '->', 'Dict[str,', 'Any]:', 'lua_index', '=', 'player_idx', '+', '1', 'lua_most_tasty_berry_idx', '=', 'most_tasty_berry_idx', '+', '1', 'live_state_name', '=', "'player{}'.format(lua_index)", 'avatar_sprite_name', '=', "'avatarSprite{... | 285,619 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | pixelda_model.py | resnet_generator | resnet_generator | Creates a ResNet-based generator. | [
"Creates",
"a",
"ResNet-based",
"generator."
] | def resnet_generator(images, output_shape, hparams, latent_vars=None):
with tf.variable_scope('generator'):
if latent_vars:
noise_channel = project_latent_vars(hparams, proj_shape=images.shape.as_list()[1:3] + [1], latent_vars=latent_vars, combine_method='concat')
images = tf.concat(... | ['def', 'resnet_generator(images,', 'output_shape,', 'hparams,', 'latent_vars=None):', 'with', "tf.variable_scope('generator'):", 'if', 'latent_vars:', 'noise_channel', '=', 'project_latent_vars(hparams,', 'proj_shape=images.shape.as_list()[1:3]', '+', '[1],', 'latent_vars=latent_vars,', "combine_method='concat')", 'im... | 48,198 |
IntelLabs/nlp-architect | utils.py | read_tsv | read_tsv | Reads a tab separated value file. | [
"Reads",
"a",
"tab",
"separated",
"value",
"file."
] | def read_tsv(input_file, quotechar=None):
with open(input_file, 'r', encoding='utf-8-sig') as f:
reader = csv.reader(f, delimiter='\t', quotechar=quotechar)
lines = []
for line in reader:
if sys.version_info[0] == 2:
line = list((str(cell, 'utf-8') for cell in lin... | ['def', 'read_tsv(input_file,', 'quotechar=None):', 'with', 'open(input_file,', "'r',", "encoding='utf-8-sig')", 'as', 'f:', 'reader', '=', 'csv.reader(f,', "delimiter='\\t',", 'quotechar=quotechar)', 'lines', '=', '[]', 'for', 'line', 'in', 'reader:', 'if', 'sys.version_info[0]', '==', '2:', 'line', '=', 'list((str(ce... | 783,231 |
SimingYan/IAE | training.py | Trainer.eval_step | eval_step | Performs an evaluation step. | [
"Performs",
"an",
"evaluation",
"step."
] | def eval_step(self, data):
self.model.eval()
device = self.device
eval_dict = {}
points = data.get('points').to(device)
df = data.get('points.df').to(device)
inputs = data.get('inputs', torch.empty(points.size(0), 0)).to(device)
points_iou = data.get('points_iou').to(device)
df_iou = dat... | ['def', 'eval_step(self,', 'data):', 'self.model.eval()', 'device', '=', 'self.device', 'eval_dict', '=', '{}', 'points', '=', "data.get('points').to(device)", 'df', '=', "data.get('points.df').to(device)", 'inputs', '=', "data.get('inputs',", 'torch.empty(points.size(0),', '0)).to(device)', 'points_iou', '=', "data.ge... | 228,294 |
Westlake-AI/openmixup | svm_classifier.py | SVMHelper.load_input_data | load_input_data | Load the features and the targets. | [
"Load",
"the",
"features",
"and",
"the",
"targets."
] | def load_input_data(data_file, targets_file):
targets = np.load(targets_file, encoding='latin1')
features = np.array(np.load(data_file, encoding='latin1')).astype(np.float64)
assert features.shape[0] == targets.shape[0], 'Mismatched #images'
return (features, targets) | ['def', 'load_input_data(data_file,', 'targets_file):', 'targets', '=', 'np.load(targets_file,', "encoding='latin1')", 'features', '=', 'np.array(np.load(data_file,', "encoding='latin1')).astype(np.float64)", 'assert', 'features.shape[0]', '==', 'targets.shape[0],', "'Mismatched", "#images'", 'return', '(features,', 't... | 252,560 |
salesforce/CodeRL | run_flax_glue.py | create_learning_rate_fn | create_learning_rate_fn | Returns a linear warmup, linear_decay learning rate function. | [
"Returns",
"a",
"linear",
"warmup,",
"linear_decay",
"learning",
"rate",
"function."
] | def create_learning_rate_fn(train_ds_size: int, train_batch_size: int, num_train_epochs: int, num_warmup_steps: int, learning_rate: float) -> Callable[[int], jnp.array]:
steps_per_epoch = train_ds_size // train_batch_size
num_train_steps = steps_per_epoch * num_train_epochs
warmup_fn = optax.linear_schedule... | ['def', 'create_learning_rate_fn(train_ds_size:', 'int,', 'train_batch_size:', 'int,', 'num_train_epochs:', 'int,', 'num_warmup_steps:', 'int,', 'learning_rate:', 'float)', '->', 'Callable[[int],', 'jnp.array]:', 'steps_per_epoch', '=', 'train_ds_size', '//', 'train_batch_size', 'num_train_steps', '=', 'steps_per_epoch... | 493,667 |
FedML-AI/FedML | jax_haiku_model_trainer_classification.py | JaxHaikuModelTrainerCLS.loss | loss | Cross-entropy classification loss with regularization by L2 weight decay. | [
"Cross-entropy",
"classification",
"loss",
"with",
"regularization",
"by",
"L2",
"weight",
"decay."
] | def loss(params: hk.Params, x, labels) -> jnp.ndarray:
(batch_size, *_) = x.shape
logits = JaxHaikuModelTrainerCLS.static_model.model_network.apply(params, x)
labels = jax.nn.one_hot(labels, JaxHaikuModelTrainerCLS.static_model.output_dim)
l2_regularization = 0.5 * sum((jnp.sum(jnp.square(p)) for p in j... | ['def', 'loss(params:', 'hk.Params,', 'x,', 'labels)', '->', 'jnp.ndarray:', '(batch_size,', '*_)', '=', 'x.shape', 'logits', '=', 'JaxHaikuModelTrainerCLS.static_model.model_network.apply(params,', 'x)', 'labels', '=', 'jax.nn.one_hot(labels,', 'JaxHaikuModelTrainerCLS.static_model.output_dim)', 'l2_regularization', '... | 545,173 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | cmd.py | Command.spawn | spawn | Spawn an external command respecting dry-run flag. | [
"Spawn",
"an",
"external",
"command",
"respecting",
"dry-run",
"flag."
] | def spawn(self, cmd, search_path=1, level=1):
from distutils.spawn import spawn
spawn(cmd, search_path, dry_run=self.dry_run) | ['def', 'spawn(self,', 'cmd,', 'search_path=1,', 'level=1):', 'from', 'distutils.spawn', 'import', 'spawn', 'spawn(cmd,', 'search_path,', 'dry_run=self.dry_run)'] | 430,290 |
instadeepai/jumanji | env_test.py | test_bin_pack__pack_all_items_dummy_instance | test_bin_pack__pack_all_items_dummy_instance | Functional test to check that the dummy instance can be completed with a random agent. | [
"Functional",
"test",
"to",
"check",
"that",
"the",
"dummy",
"instance",
"can",
"be",
"completed",
"with",
"a",
"random",
"agent."
] | def test_bin_pack__pack_all_items_dummy_instance(bin_pack: BinPack, bin_pack_random_select_action: SelectActionFn) -> None:
step_fn = jax.jit(bin_pack.step)
key = jax.random.PRNGKey(0)
(state, timestep) = bin_pack.reset(key)
while not timestep.last():
(action_key, key) = jax.random.split(key)
... | ['def', 'test_bin_pack__pack_all_items_dummy_instance(bin_pack:', 'BinPack,', 'bin_pack_random_select_action:', 'SelectActionFn)', '->', 'None:', 'step_fn', '=', 'jax.jit(bin_pack.step)', 'key', '=', 'jax.random.PRNGKey(0)', '(state,', 'timestep)', '=', 'bin_pack.reset(key)', 'while', 'not', 'timestep.last():', '(actio... | 594,163 |
aws/sagemaker-python-sdk | session.py | Session.delete_model | delete_model | Delete an Amazon SageMaker Model. | [
"Delete",
"an",
"Amazon",
"SageMaker",
"Model."
] | def delete_model(self, model_name):
LOGGER.info('Deleting model with name: %s', model_name)
self.sagemaker_client.delete_model(ModelName=model_name) | ['def', 'delete_model(self,', 'model_name):', "LOGGER.info('Deleting", 'model', 'with', 'name:', "%s',", 'model_name)', 'self.sagemaker_client.delete_model(ModelName=model_name)'] | 829,635 |
Kvatsx/Artificial-Intelligence-Assignments | feature_base.py | Features.update_mapping | update_mapping | Called every time we care about the mapping of names to features. | [
"Called",
"every",
"time",
"we",
"care",
"about",
"the",
"mapping",
"of",
"names",
"to",
"features."
] | def update_mapping(self):
self.mapping = dict([(f.name, f) for f in iter(self)]) | ['def', 'update_mapping(self):', 'self.mapping', '=', 'dict([(f.name,', 'f)', 'for', 'f', 'in', 'iter(self)])'] | 39,652 |
avisekiit/wacv_2019 | factory.py | get_network | get_network | Get a network by name. | [
"Get",
"a",
"network",
"by",
"name."
] | def get_network(name):
if name.split('_')[1] == 'test':
return networks.VGGnet_test()
elif name.split('_')[1] == 'train':
return networks.VGGnet_train()
else:
raise KeyError('Unknown dataset: {}'.format(name)) | ['def', 'get_network(name):', 'if', "name.split('_')[1]", '==', "'test':", 'return', 'networks.VGGnet_test()', 'elif', "name.split('_')[1]", '==', "'train':", 'return', 'networks.VGGnet_train()', 'else:', 'raise', "KeyError('Unknown", 'dataset:', "{}'.format(name))"] | 381,055 |
rifqind/Agent-Programs-3KS1 | win32_pipe.py | Win32PipeInput.typeahead_hash | typeahead_hash | This needs to be unique for every `PipeInput`. | [
"This",
"needs",
"to",
"be",
"unique",
"for",
"every",
"`PipeInput`."
] | def typeahead_hash(self):
return 'pipe-input-%s' % (self._id,) | ['def', 'typeahead_hash(self):', 'return', "'pipe-input-%s'", '%', '(self._id,)'] | 45,219 |
SonyCSLParis/cae-invar | utils.py | median_filter | median_filter | Applies a median filter of size L to the matrix of row observations X. | [
"Applies",
"a",
"median",
"filter",
"of",
"size",
"L",
"to",
"the",
"matrix",
"of",
"row",
"observations",
"X."
] | def median_filter(X, L=9):
Y = np.ones(X.shape) * X.min()
Lh = (L - 1) / 2
for i in np.arange(Lh, X.shape[0] - Lh):
Y[i, :] = np.median(X[i - Lh:i + Lh, :], axis=0)
return Y | ['def', 'median_filter(X,', 'L=9):', 'Y', '=', 'np.ones(X.shape)', '*', 'X.min()', 'Lh', '=', '(L', '-', '1)', '/', '2', 'for', 'i', 'in', 'np.arange(Lh,', 'X.shape[0]', '-', 'Lh):', 'Y[i,', ':]', '=', 'np.median(X[i', '-', 'Lh:i', '+', 'Lh,', ':],', 'axis=0)', 'return', 'Y'] | 410,860 |
caiiiac/Machine-Learning-with-Python | gpc.py | GaussianProcessClassifier.fit | fit | Fit Gaussian process classification model Parameters ---------- X : array-like, shape = (n_samples, n_features) Training data y : array-like, shape = (n_samples,) Target values, must be binary Returns ------- self : returns an instance of self. | [
"Fit",
"Gaussian",
"process",
"classification",
"model",
"Parameters",
"----------",
"X",
":",
"array-like,",
"shape",
"=",
"(n_samples,",
"n_features)",
"Training",
"data",
"y",
":",
"array-like,",
"shape",
"=",
"(n_samples,)",
"Target",
"values,",
"must",
"be",
... | def fit(self, X, y):
(X, y) = check_X_y(X, y, multi_output=False)
self.base_estimator_ = _BinaryGaussianProcessClassifierLaplace(self.kernel, self.optimizer, self.n_restarts_optimizer, self.max_iter_predict, self.warm_start, self.copy_X_train, self.random_state)
self.classes_ = np.unique(y)
self.n_class... | ['def', 'fit(self,', 'X,', 'y):', '(X,', 'y)', '=', 'check_X_y(X,', 'y,', 'multi_output=False)', 'self.base_estimator_', '=', '_BinaryGaussianProcessClassifierLaplace(self.kernel,', 'self.optimizer,', 'self.n_restarts_optimizer,', 'self.max_iter_predict,', 'self.warm_start,', 'self.copy_X_train,', 'self.random_state)',... | 720,814 |
calico/basenji | borzoi_test_genes.py | genes_aggregate | genes_aggregate | Aggregate values across genes. | [
"Aggregate",
"values",
"across",
"genes."
] | def genes_aggregate(genes_bed_file, values_bedgraph):
values_bt = pybedtools.BedTool(values_bedgraph)
genes_bt = pybedtools.BedTool(genes_bed_file)
gene_values = {}
for overlap in genes_bt.intersect(values_bt, wo=True):
gene_id = overlap[3]
value = overlap[7]
gene_values[gene_id]... | ['def', 'genes_aggregate(genes_bed_file,', 'values_bedgraph):', 'values_bt', '=', 'pybedtools.BedTool(values_bedgraph)', 'genes_bt', '=', 'pybedtools.BedTool(genes_bed_file)', 'gene_values', '=', '{}', 'for', 'overlap', 'in', 'genes_bt.intersect(values_bt,', 'wo=True):', 'gene_id', '=', 'overlap[3]', 'value', '=', 'ove... | 94,839 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | inspect.py | Parameter.replace | replace | Creates a customized copy of the Parameter. | [
"Creates",
"a",
"customized",
"copy",
"of",
"the",
"Parameter."
] | def replace(self, *, name=_void, kind=_void, annotation=_void, default=_void):
if name is _void:
name = self._name
if kind is _void:
kind = self._kind
if annotation is _void:
annotation = self._annotation
if default is _void:
default = self._default
return type(self)(... | ['def', 'replace(self,', '*,', 'name=_void,', 'kind=_void,', 'annotation=_void,', 'default=_void):', 'if', 'name', 'is', '_void:', 'name', '=', 'self._name', 'if', 'kind', 'is', '_void:', 'kind', '=', 'self._kind', 'if', 'annotation', 'is', '_void:', 'annotation', '=', 'self._annotation', 'if', 'default', 'is', '_void:... | 428,697 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | variables.py | variable_device | variable_device | Fix the variable device to colocate its ops. | [
"Fix",
"the",
"variable",
"device",
"to",
"colocate",
"its",
"ops."
] | def variable_device(device, name):
if callable(device):
var_name = tf.get_variable_scope().name + '/' + name
var_def = tf.NodeDef(name=var_name, op='Variable')
device = device(var_def)
if device is None:
device = ''
return device | ['def', 'variable_device(device,', 'name):', 'if', 'callable(device):', 'var_name', '=', 'tf.get_variable_scope().name', '+', "'/'", '+', 'name', 'var_def', '=', 'tf.NodeDef(name=var_name,', "op='Variable')", 'device', '=', 'device(var_def)', 'if', 'device', 'is', 'None:', 'device', '=', "''", 'return', 'device'] | 49,162 |
myothida/Supervised-Machine-Learning | __init__.py | get_all_styles | get_all_styles | Return a generator for all styles by name, both builtin and plugin. | [
"Return",
"a",
"generator",
"for",
"all",
"styles",
"by",
"name,",
"both",
"builtin",
"and",
"plugin."
] | def get_all_styles():
yield from STYLE_MAP
for (name, _) in find_plugin_styles():
yield name | ['def', 'get_all_styles():', 'yield', 'from', 'STYLE_MAP', 'for', '(name,', '_)', 'in', 'find_plugin_styles():', 'yield', 'name'] | 444,785 |
v0lta/Complex-gated-recurrent-- | custom_cells.py | single_sigmoid_imag | single_sigmoid_imag | What happens if we throw the real part away? Problem: Half of the weights don't contribute. | [
"What",
"happens",
"if",
"we",
"throw",
"the",
"real",
"part",
"away?",
"Problem:",
"Half",
"of",
"the",
"weights",
"don't",
"contribute."
] | def single_sigmoid_imag(z, scope='', reuse=None):
with tf.variable_scope('sigmoid_imag_' + scope, reuse=reuse):
iz = tf.nn.sigmoid(tf.imag(z))
return tf.complex(iz, tf.zeros_like(iz)) | ['def', 'single_sigmoid_imag(z,', "scope='',", 'reuse=None):', 'with', "tf.variable_scope('sigmoid_imag_'", '+', 'scope,', 'reuse=reuse):', 'iz', '=', 'tf.nn.sigmoid(tf.imag(z))', 'return', 'tf.complex(iz,', 'tf.zeros_like(iz))'] | 135,959 |
astooke/rlpyt | utils.py | conv2d_output_shape | conv2d_output_shape | Returns output H, W after convolution/pooling on input H, W. | [
"Returns",
"output",
"H,",
"W",
"after",
"convolution/pooling",
"on",
"input",
"H,",
"W."
] | def conv2d_output_shape(h, w, kernel_size=1, stride=1, padding=0, dilation=1):
(kh, kw) = kernel_size if isinstance(kernel_size, tuple) else (kernel_size,) * 2
(sh, sw) = stride if isinstance(stride, tuple) else (stride,) * 2
(ph, pw) = padding if isinstance(padding, tuple) else (padding,) * 2
d = dilat... | ['def', 'conv2d_output_shape(h,', 'w,', 'kernel_size=1,', 'stride=1,', 'padding=0,', 'dilation=1):', '(kh,', 'kw)', '=', 'kernel_size', 'if', 'isinstance(kernel_size,', 'tuple)', 'else', '(kernel_size,)', '*', '2', '(sh,', 'sw)', '=', 'stride', 'if', 'isinstance(stride,', 'tuple)', 'else', '(stride,)', '*', '2', '(ph,'... | 334,578 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | experiment.py | load_eval | load_eval | Loads the latest saved model to the given session. | [
"Loads",
"the",
"latest",
"saved",
"model",
"to",
"the",
"given",
"session."
] | def load_eval(saver, session, load_dir):
saver.restore(session, load_dir)
print('model loaded successfully')
return extract_step(load_dir) | ['def', 'load_eval(saver,', 'session,', 'load_dir):', 'saver.restore(session,', 'load_dir)', "print('model", 'loaded', "successfully')", 'return', 'extract_step(load_dir)'] | 53,039 |
Alina-chan/realtime-object-detection | load_graph_trt_v1.py | LoadFrozenGraph.split_trt_graph | split_trt_graph | Load frozen_graph and split it into half of GPU and CPU. | [
"Load",
"frozen_graph",
"and",
"split",
"it",
"into",
"half",
"of",
"GPU",
"and",
"CPU."
] | def split_trt_graph(self, graph_def):
split_shape = self.cfg['split_shape']
num_classes = self.cfg['num_classes']
SPLIT_TARGET_NAME = ['Postprocessor/Slice', 'Postprocessor/ExpandDims_1']
tf.reset_default_graph()
target_in = [tf.placeholder(tf.float32, shape=(None, split_shape, num_classes), name=SP... | ['def', 'split_trt_graph(self,', 'graph_def):', 'split_shape', '=', "self.cfg['split_shape']", 'num_classes', '=', "self.cfg['num_classes']", 'SPLIT_TARGET_NAME', '=', "['Postprocessor/Slice',", "'Postprocessor/ExpandDims_1']", 'tf.reset_default_graph()', 'target_in', '=', '[tf.placeholder(tf.float32,', 'shape=(None,',... | 850,130 |
hzykent/LiDAL | pypcd.py | parse_header | parse_header | Parse header of PCD files. | [
"Parse",
"header",
"of",
"PCD",
"files."
] | def parse_header(lines):
metadata = {}
for ln in lines:
if ln.startswith('#') or len(ln) < 2:
continue
match = re.match('(\\w+)\\s+([\\w\\s\\.]+)', str(ln))
if not match:
warnings.warn("warning: can't understand line: %s" % ln)
continue
(key, v... | ['def', 'parse_header(lines):', 'metadata', '=', '{}', 'for', 'ln', 'in', 'lines:', 'if', "ln.startswith('#')", 'or', 'len(ln)', '<', '2:', 'continue', 'match', '=', "re.match('(\\\\w+)\\\\s+([\\\\w\\\\s\\\\.]+)',", 'str(ln))', 'if', 'not', 'match:', 'warnings.warn("warning:', "can't", 'understand', 'line:', '%s"', '%'... | 601,341 |
arshpreetsingh/quantopian-machinelearning | util.py | terminal_encoding | terminal_encoding | Return our best guess of encoding for the given *term*. | [
"Return",
"our",
"best",
"guess",
"of",
"encoding",
"for",
"the",
"given",
"*term*."
] | def terminal_encoding(term):
if getattr(term, 'encoding', None):
return term.encoding
import locale
return locale.getpreferredencoding() | ['def', 'terminal_encoding(term):', 'if', 'getattr(term,', "'encoding',", 'None):', 'return', 'term.encoding', 'import', 'locale', 'return', 'locale.getpreferredencoding()'] | 892,640 |
weimin17/Object-Detection_HelmetDetection | path_model.py | PathBasedModel.load_labels | load_labels | Loads the labels of the current instances. | [
"Loads",
"the",
"labels",
"of",
"the",
"current",
"instances."
] | def load_labels(self, session, batch_instances):
return session.run(self.labels_to_load, feed_dict={self.instances_to_load: batch_instances}) | ['def', 'load_labels(self,', 'session,', 'batch_instances):', 'return', 'session.run(self.labels_to_load,', 'feed_dict={self.instances_to_load:', 'batch_instances})'] | 757,750 |
kubeflow/pipelines | artifact_types.py | SlicedClassificationMetrics.load_roc_readings | load_roc_readings | Bulk loads ROC curve readings for a slice. | [
"Bulk",
"loads",
"ROC",
"curve",
"readings",
"for",
"a",
"slice."
] | def load_roc_readings(self, slice: str, readings: List[List[float]]) -> None:
self._upsert_classification_metrics_for_slice(slice)
self._sliced_metrics[slice].load_roc_readings(readings)
self._update_metadata(slice) | ['def', 'load_roc_readings(self,', 'slice:', 'str,', 'readings:', 'List[List[float]])', '->', 'None:', 'self._upsert_classification_metrics_for_slice(slice)', 'self._sliced_metrics[slice].load_roc_readings(readings)', 'self._update_metadata(slice)'] | 780,272 |
nicknochnack/RealTimeSignLanguageTFJS | _performance.py | define_performance | define_performance | Register flags for specifying performance tuning arguments. | [
"Register",
"flags",
"for",
"specifying",
"performance",
"tuning",
"arguments."
] | def define_performance(num_parallel_calls=False, inter_op=False, intra_op=False, synthetic_data=False, max_train_steps=False, dtype=False, all_reduce_alg=False, num_packs=False, tf_gpu_thread_mode=False, datasets_num_private_threads=False, datasets_num_parallel_batches=False, dynamic_loss_scale=False, fp16_implementati... | ['def', 'define_performance(num_parallel_calls=False,', 'inter_op=False,', 'intra_op=False,', 'synthetic_data=False,', 'max_train_steps=False,', 'dtype=False,', 'all_reduce_alg=False,', 'num_packs=False,', 'tf_gpu_thread_mode=False,', 'datasets_num_private_threads=False,', 'datasets_num_parallel_batches=False,', 'dynam... | 850,722 |
sunishsheth2009/ChatterBot | datastructures.py | Authorization.qop | qop | Indicates what "quality of protection" the client has applied to the message for HTTP digest auth. | [
"Indicates",
"what",
"\"quality",
"of",
"protection\"",
"the",
"client",
"has",
"applied",
"to",
"the",
"message",
"for",
"HTTP",
"digest",
"auth."
] | def qop(self):
def on_update(header_set):
if not header_set and 'qop' in self:
del self['qop']
elif header_set:
self['qop'] = header_set.to_header()
return parse_set_header(self.get('qop'), on_update) | ['def', 'qop(self):', 'def', 'on_update(header_set):', 'if', 'not', 'header_set', 'and', "'qop'", 'in', 'self:', 'del', "self['qop']", 'elif', 'header_set:', "self['qop']", '=', 'header_set.to_header()', 'return', "parse_set_header(self.get('qop'),", 'on_update)'] | 483,078 |
secretflow/secretflow | model.py | SSGLM.spu_w_to_federated | spu_w_to_federated | spu_w is our trained model of shape (num_feature + 1, 1) we are going to split it into federated form. | [
"spu_w",
"is",
"our",
"trained",
"model",
"of",
"shape",
"(num_feature",
"+",
"1,",
"1)",
"we",
"are",
"going",
"to",
"split",
"it",
"into",
"federated",
"form."
] | def spu_w_to_federated(self, federated_template: Union[FedNdarray, VDataFrame], bias_receiver: PYU) -> Tuple[FedNdarray, PYUObject]:
(federated_template, (_, num_feat)) = self._prepare_dataset(federated_template)
assert self.num_feat == num_feat, f'federated template must have number of features equal {self.num... | ['def', 'spu_w_to_federated(self,', 'federated_template:', 'Union[FedNdarray,', 'VDataFrame],', 'bias_receiver:', 'PYU)', '->', 'Tuple[FedNdarray,', 'PYUObject]:', '(federated_template,', '(_,', 'num_feat))', '=', 'self._prepare_dataset(federated_template)', 'assert', 'self.num_feat', '==', 'num_feat,', "f'federated", ... | 856,530 |
bhateharsh/computer_vision | cpp_lint.py | _FunctionState.Begin | Begin | Start analyzing function body. | [
"Start",
"analyzing",
"function",
"body."
] | def Begin(self, function_name):
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name | ['def', 'Begin(self,', 'function_name):', 'self.in_a_function', '=', 'True', 'self.lines_in_function', '=', '0', 'self.current_function', '=', 'function_name'] | 473,366 |
cannlytics/cannlytics-ai | get_data_ok.py | download_website_pdfs | download_website_pdfs | Download all PDFs from a given website to a given folder. | [
"Download",
"all",
"PDFs",
"from",
"a",
"given",
"website",
"to",
"a",
"given",
"folder."
] | def download_website_pdfs(url, destination):
files = []
if not os.path.exists(destination):
os.mkdir(destination)
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.select('a[href$=".pdf"]'):
file_name = os.path.join(destination, link['hr... | ['def', 'download_website_pdfs(url,', 'destination):', 'files', '=', '[]', 'if', 'not', 'os.path.exists(destination):', 'os.mkdir(destination)', 'response', '=', 'requests.get(url)', 'soup', '=', 'BeautifulSoup(response.text,', "'html.parser')", 'for', 'link', 'in', 'soup.select(\'a[href$=".pdf"]\'):', 'file_name', '='... | 108,892 |
google/deepvariant | show_examples.py | parse_vcf | parse_vcf | Parse VCF to extract a dict keyed by locus IDs. | [
"Parse",
"VCF",
"to",
"extract",
"a",
"dict",
"keyed",
"by",
"locus",
"IDs."
] | def parse_vcf(vcf_path: str) -> Set[str]:
if vcf_path.endswith('.gz'):
vcf_reader = gzip.open(vcf_path)
else:
vcf_reader = open(vcf_path, 'r')
ids_from_vcf = set()
for l in vcf_reader:
if isinstance(l, bytes):
l = l.decode('utf-8')
if not l.startswith('#'):
... | ['def', 'parse_vcf(vcf_path:', 'str)', '->', 'Set[str]:', 'if', "vcf_path.endswith('.gz'):", 'vcf_reader', '=', 'gzip.open(vcf_path)', 'else:', 'vcf_reader', '=', 'open(vcf_path,', "'r')", 'ids_from_vcf', '=', 'set()', 'for', 'l', 'in', 'vcf_reader:', 'if', 'isinstance(l,', 'bytes):', 'l', '=', "l.decode('utf-8')", 'if... | 540,436 |
suarez12138/AI-Reversi_IMP_TextDichotomy | backend_tools.py | ZoomPanBase.enable | enable | Connect press/release events and lock the canvas. | [
"Connect",
"press/release",
"events",
"and",
"lock",
"the",
"canvas."
] | def enable(self, event):
self.figure.canvas.widgetlock(self)
self._idPress = self.figure.canvas.mpl_connect('button_press_event', self._press)
self._idRelease = self.figure.canvas.mpl_connect('button_release_event', self._release)
self._idScroll = self.figure.canvas.mpl_connect('scroll_event', self.scro... | ['def', 'enable(self,', 'event):', 'self.figure.canvas.widgetlock(self)', 'self._idPress', '=', "self.figure.canvas.mpl_connect('button_press_event',", 'self._press)', 'self._idRelease', '=', "self.figure.canvas.mpl_connect('button_release_event',", 'self._release)', 'self._idScroll', '=', "self.figure.canvas.mpl_conne... | 96,291 |
enuguru/artificial_intelligence_and_machine_learning | test_easy_install.py | TestUserInstallTest.test_setup_requires | test_setup_requires | Regression test for Distribute issue #318 Ensure that a package with setup_requires can be installed when setuptools is installed in the user site-packages without causing a SandboxViolation. | [
"Regression",
"test",
"for",
"Distribute",
"issue",
"#318",
"Ensure",
"that",
"a",
"package",
"with",
"setup_requires",
"can",
"be",
"installed",
"when",
"setuptools",
"is",
"installed",
"in",
"the",
"user",
"site-packages",
"without",
"causing",
"a",
"SandboxViol... | def test_setup_requires(self):
test_setup_attrs = {'name': 'test_pkg', 'version': '0.0', 'setup_requires': ['foobar'], 'dependency_links': [os.path.abspath(self.dir)]}
test_pkg = os.path.join(self.dir, 'test_pkg')
test_setup_py = os.path.join(test_pkg, 'setup.py')
test_setup_cfg = os.path.join(test_pkg,... | ['def', 'test_setup_requires(self):', 'test_setup_attrs', '=', "{'name':", "'test_pkg',", "'version':", "'0.0',", "'setup_requires':", "['foobar'],", "'dependency_links':", '[os.path.abspath(self.dir)]}', 'test_pkg', '=', 'os.path.join(self.dir,', "'test_pkg')", 'test_setup_py', '=', 'os.path.join(test_pkg,', "'setup.p... | 164,293 |
Eric3911/OpenAGI | checkpoint.py | Checkpoint.load_best_parameters | load_best_parameters | Load a last model checkpoint from disk. | [
"Load",
"a",
"last",
"model",
"checkpoint",
"from",
"disk."
] | def load_best_parameters(self, model, optimizer=None, checkpoint_dir=None, checkpoint_path=None):
return self.load_parameters(model, optimizer, checkpoint_dir, checkpoint_path, 'checkpoint_best') | ['def', 'load_best_parameters(self,', 'model,', 'optimizer=None,', 'checkpoint_dir=None,', 'checkpoint_path=None):', 'return', 'self.load_parameters(model,', 'optimizer,', 'checkpoint_dir,', 'checkpoint_path,', "'checkpoint_best')"] | 251,552 |
drprojects/superpoint_transformer | data.py | Batch.get_example | get_example | Overwrite torch_geometric get_example to be able to handle Cluster objects batching. | [
"Overwrite",
"torch_geometric",
"get_example",
"to",
"be",
"able",
"to",
"handle",
"Cluster",
"objects",
"batching."
] | def get_example(self, idx):
if self.is_super:
sub_bckp = self.sub.clone()
self.sub = self.sub.to_csr_list()
data = super().get_example(idx)
if self.is_super:
self.sub = sub_bckp
return data | ['def', 'get_example(self,', 'idx):', 'if', 'self.is_super:', 'sub_bckp', '=', 'self.sub.clone()', 'self.sub', '=', 'self.sub.to_csr_list()', 'data', '=', 'super().get_example(idx)', 'if', 'self.is_super:', 'self.sub', '=', 'sub_bckp', 'return', 'data'] | 880,783 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | SearchDialogBase.py | SearchDialogBase.create_entries | create_entries | Create one or more entry lines with make_entry. | [
"Create",
"one",
"or",
"more",
"entry",
"lines",
"with",
"make_entry."
] | def create_entries(self):
self.ent = self.make_entry('Find:', self.engine.patvar)[0] | ['def', 'create_entries(self):', 'self.ent', '=', "self.make_entry('Find:',", 'self.engine.patvar)[0]'] | 430,946 |
ChenhongyiYang/PPAL | cityscapes.py | CityscapesDataset.evaluate | evaluate | Evaluation in Cityscapes/COCO protocol. | [
"Evaluation",
"in",
"Cityscapes/COCO",
"protocol."
] | def evaluate(self, results, metric='bbox', logger=None, outfile_prefix=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=np.arange(0.5, 0.96, 0.05)):
eval_results = dict()
metrics = metric.copy() if isinstance(metric, list) else [metric]
if 'cityscapes' in metrics:
eval_results.update(... | ['def', 'evaluate(self,', 'results,', "metric='bbox',", 'logger=None,', 'outfile_prefix=None,', 'classwise=False,', 'proposal_nums=(100,', '300,', '1000),', 'iou_thrs=np.arange(0.5,', '0.96,', '0.05)):', 'eval_results', '=', 'dict()', 'metrics', '=', 'metric.copy()', 'if', 'isinstance(metric,', 'list)', 'else', '[metri... | 821,360 |
rifqind/Agent-Programs-3KS1 | decorator.py | append | append | Append ``a`` to the list of the virtual ancestors, unless it is already included. | [
"Append",
"``a``",
"to",
"the",
"list",
"of",
"the",
"virtual",
"ancestors,",
"unless",
"it",
"is",
"already",
"included."
] | def append(a, vancestors):
add = True
for (j, va) in enumerate(vancestors):
if issubclass(va, a):
add = False
break
if issubclass(a, va):
vancestors[j] = a
add = False
if add:
vancestors.append(a) | ['def', 'append(a,', 'vancestors):', 'add', '=', 'True', 'for', '(j,', 'va)', 'in', 'enumerate(vancestors):', 'if', 'issubclass(va,', 'a):', 'add', '=', 'False', 'break', 'if', 'issubclass(a,', 'va):', 'vancestors[j]', '=', 'a', 'add', '=', 'False', 'if', 'add:', 'vancestors.append(a)'] | 40,461 |
fundamentalvision/BEVFormer | nuscenes_mono_dataset.py | CustomNuScenesMonoDataset.evaluate | evaluate | Evaluation in nuScenes protocol. | [
"Evaluation",
"in",
"nuScenes",
"protocol."
] | def evaluate(self, results, metric='bbox', logger=None, jsonfile_prefix=None, result_names=['img_bbox'], show=False, out_dir=None, pipeline=None):
(result_files, tmp_dir) = self.format_results(results, jsonfile_prefix)
if isinstance(result_files, dict):
results_dict = dict()
for name in result_n... | ['def', 'evaluate(self,', 'results,', "metric='bbox',", 'logger=None,', 'jsonfile_prefix=None,', "result_names=['img_bbox'],", 'show=False,', 'out_dir=None,', 'pipeline=None):', '(result_files,', 'tmp_dir)', '=', 'self.format_results(results,', 'jsonfile_prefix)', 'if', 'isinstance(result_files,', 'dict):', 'results_di... | 434,310 |
Ruturaj123/Flowchart-Detection | linear_test.py | LinearRegressorTest.testSdcaOptimizerBiasAndOtherColumns | testSdcaOptimizerBiasAndOtherColumns | Tests LinearClassifier with SDCAOptimizer and validates bias weight. | [
"Tests",
"LinearClassifier",
"with",
"SDCAOptimizer",
"and",
"validates",
"bias",
"weight."
] | def testSdcaOptimizerBiasAndOtherColumns(self):
def input_fn():
num_examples = 200
half = int(num_examples / 2)
return ({'example_id': constant_op.constant([str(x + 1) for x in range(num_examples)]), 'a': constant_op.constant([[1]] * int(half) + [[0]] * int(half)), 'b': constant_op.constant... | ['def', 'testSdcaOptimizerBiasAndOtherColumns(self):', 'def', 'input_fn():', 'num_examples', '=', '200', 'half', '=', 'int(num_examples', '/', '2)', 'return', "({'example_id':", 'constant_op.constant([str(x', '+', '1)', 'for', 'x', 'in', 'range(num_examples)]),', "'a':", 'constant_op.constant([[1]]', '*', 'int(half)', ... | 604,058 |
rudranil723/mini-main | band.py | GDALBand.nodata_value | nodata_value | Return the nodata value for this band, or None if it isn't set. | [
"Return",
"the",
"nodata",
"value",
"for",
"this",
"band,",
"or",
"None",
"if",
"it",
"isn't",
"set."
] | def nodata_value(self):
nodata_exists = c_int()
value = capi.get_band_nodata_value(self._ptr, nodata_exists)
if not nodata_exists:
value = None
elif self.datatype() in GDAL_INTEGER_TYPES:
value = int(value)
return value | ['def', 'nodata_value(self):', 'nodata_exists', '=', 'c_int()', 'value', '=', 'capi.get_band_nodata_value(self._ptr,', 'nodata_exists)', 'if', 'not', 'nodata_exists:', 'value', '=', 'None', 'elif', 'self.datatype()', 'in', 'GDAL_INTEGER_TYPES:', 'value', '=', 'int(value)', 'return', 'value'] | 315,226 |
Farama-Foundation/Gymnasium-Robotics | robot_env.py | BaseRobotEnv.compute_truncated | compute_truncated | The environments will be truncated only if setting a time limit with max_steps which will automatically wrap the environment in a gymnasium TimeLimit wrapper. | [
"The",
"environments",
"will",
"be",
"truncated",
"only",
"if",
"setting",
"a",
"time",
"limit",
"with",
"max_steps",
"which",
"will",
"automatically",
"wrap",
"the",
"environment",
"in",
"a",
"gymnasium",
"TimeLimit",
"wrapper."
] | def compute_truncated(self, achievec_goal, desired_goal, info):
return False | ['def', 'compute_truncated(self,', 'achievec_goal,', 'desired_goal,', 'info):', 'return', 'False'] | 573,688 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | MjrContextWrapper.offDepthStencil_r | offDepthStencil_r | offscreen depth and stencil buffer for resolving multisamples. | [
"offscreen",
"depth",
"and",
"stencil",
"buffer",
"for",
"resolving",
"multisamples."
] | def offDepthStencil_r(self):
return self._ptr.contents.offDepthStencil_r | ['def', 'offDepthStencil_r(self):', 'return', 'self._ptr.contents.offDepthStencil_r'] | 440,638 |
weimin17/Object-Detection_HelmetDetection | neural_gpu_trainer.py | zero_split | zero_split | Split tok_list (list of ints) on 0s, append int to all parts if given. | [
"Split",
"tok_list",
"(list",
"of",
"ints)",
"on",
"0s,",
"append",
"int",
"to",
"all",
"parts",
"if",
"given."
] | def zero_split(tok_list, append=None):
(res, cur, l) = ([], [], 0)
for tok in tok_list:
if tok == 0:
if append is not None:
cur.append(append)
res.append(cur)
l = max(l, len(cur))
cur = []
else:
cur.append(tok)
if ap... | ['def', 'zero_split(tok_list,', 'append=None):', '(res,', 'cur,', 'l)', '=', '([],', '[],', '0)', 'for', 'tok', 'in', 'tok_list:', 'if', 'tok', '==', '0:', 'if', 'append', 'is', 'not', 'None:', 'cur.append(append)', 'res.append(cur)', 'l', '=', 'max(l,', 'len(cur))', 'cur', '=', '[]', 'else:', 'cur.append(tok)', 'if', ... | 751,380 |
matsu0228/nlp-jp | widget_selection.py | findvalue | findvalue | A function that uses the compare function to return a value from the list. | [
"A",
"function",
"that",
"uses",
"the",
"compare",
"function",
"to",
"return",
"a",
"value",
"from",
"the",
"list."
] | def findvalue(array, value, compare=lambda x, y: x == y):
try:
return next((x for x in array if compare(x, value)))
except StopIteration:
raise ValueError('%r not in array' % value) | ['def', 'findvalue(array,', 'value,', 'compare=lambda', 'x,', 'y:', 'x', '==', 'y):', 'try:', 'return', 'next((x', 'for', 'x', 'in', 'array', 'if', 'compare(x,', 'value)))', 'except', 'StopIteration:', 'raise', "ValueError('%r", 'not', 'in', "array'", '%', 'value)'] | 787,627 |
TonyLianLong/VAI-ReinforcementLearning | wrappers.py | GlobalWrapper.offwidth | offwidth | width of offscreen buffer. | [
"width",
"of",
"offscreen",
"buffer."
] | def offwidth(self):
return self._ptr.contents.offwidth | ['def', 'offwidth(self):', 'return', 'self._ptr.contents.offwidth'] | 440,166 |
pytorch/rl | _utils.py | get_trace | get_trace | A simple debugging util to spot where a function is being called. | [
"A",
"simple",
"debugging",
"util",
"to",
"spot",
"where",
"a",
"function",
"is",
"being",
"called."
] | def get_trace():
traceback.print_stack() | ['def', 'get_trace():', 'traceback.print_stack()'] | 858,508 |
kzxuan/pytorch-dnnnlp | utils.py | len_to_mask | len_to_mask | Convert seq_len to mask matrix. | [
"Convert",
"seq_len",
"to",
"mask",
"matrix."
] | def len_to_mask(seq_len, max_seq_len=None):
if isinstance(seq_len, np.ndarray):
if max_seq_len is None:
max_seq_len = seq_len.max()
query = np.arange(0, max_seq_len)
mask = (query < seq_len.reshape(-1, 1)).astype(int)
else:
import torch
if max_seq_len is None:... | ['def', 'len_to_mask(seq_len,', 'max_seq_len=None):', 'if', 'isinstance(seq_len,', 'np.ndarray):', 'if', 'max_seq_len', 'is', 'None:', 'max_seq_len', '=', 'seq_len.max()', 'query', '=', 'np.arange(0,', 'max_seq_len)', 'mask', '=', '(query', '<', 'seq_len.reshape(-1,', '1)).astype(int)', 'else:', 'import', 'torch', 'if'... | 814,496 |
sek788432/Waymo-2D-Object-Detection | retinanet_model_test.py | RetinaNetTest.test_forward | test_forward | Test for creation of a R50-FPN RetinaNet. | [
"Test",
"for",
"creation",
"of",
"a",
"R50-FPN",
"RetinaNet."
] | def test_forward(self, strategy, image_size, training, has_att_heads):
tf.keras.backend.set_image_data_format('channels_last')
num_classes = 3
min_level = 3
max_level = 7
num_scales = 3
aspect_ratios = [1.0]
num_anchors_per_location = num_scales * len(aspect_ratios)
images = np.random.ra... | ['def', 'test_forward(self,', 'strategy,', 'image_size,', 'training,', 'has_att_heads):', "tf.keras.backend.set_image_data_format('channels_last')", 'num_classes', '=', '3', 'min_level', '=', '3', 'max_level', '=', '7', 'num_scales', '=', '3', 'aspect_ratios', '=', '[1.0]', 'num_anchors_per_location', '=', 'num_scales'... | 973,097 |
voxel51/fiftyone | database.py | get_collection_stats | get_collection_stats | Sets stats about the collection. | [
"Sets",
"stats",
"about",
"the",
"collection."
] | def get_collection_stats(collection_name):
conn = get_db_conn()
stats = dict(conn.command('collstats', collection_name))
stats['wiredTiger'] = None
stats['indexDetails'] = None
return stats | ['def', 'get_collection_stats(collection_name):', 'conn', '=', 'get_db_conn()', 'stats', '=', "dict(conn.command('collstats',", 'collection_name))', "stats['wiredTiger']", '=', 'None', "stats['indexDetails']", '=', 'None', 'return', 'stats'] | 583,533 |
intel/neural-compressor | optimize_qdq.py | OptimizeQDQGraph.get_quantized_nodes | get_quantized_nodes | Get the quantized Ops. | [
"Get",
"the",
"quantized",
"Ops."
] | def get_quantized_nodes(self):
count = 0
remove_redundant_quant_flag = False
op_wise_config_name_list = list(self.op_wise_config.keys())
all_node_length = len(self.op_wise_config)
for (_, node) in enumerate(self.input_graph.node):
if node in self.input_graph.node and node.op in self.transfor... | ['def', 'get_quantized_nodes(self):', 'count', '=', '0', 'remove_redundant_quant_flag', '=', 'False', 'op_wise_config_name_list', '=', 'list(self.op_wise_config.keys())', 'all_node_length', '=', 'len(self.op_wise_config)', 'for', '(_,', 'node)', 'in', 'enumerate(self.input_graph.node):', 'if', 'node', 'in', 'self.input... | 737,843 |
sek788432/Waymo-2D-Object-Detection | box_io.py | WriteToFile | WriteToFile | Helper function to write data to a file in Boxes proto format. | [
"Helper",
"function",
"to",
"write",
"data",
"to",
"a",
"file",
"in",
"Boxes",
"proto",
"format."
] | def WriteToFile(file_path, boxes, scores, class_indices):
serialized_data = SerializeToString(boxes, scores, class_indices)
with tf.io.gfile.GFile(file_path, 'w') as f:
f.write(serialized_data) | ['def', 'WriteToFile(file_path,', 'boxes,', 'scores,', 'class_indices):', 'serialized_data', '=', 'SerializeToString(boxes,', 'scores,', 'class_indices)', 'with', 'tf.io.gfile.GFile(file_path,', "'w')", 'as', 'f:', 'f.write(serialized_data)'] | 974,220 |
myothida/Supervised-Machine-Learning | text.py | Text.truncate | truncate | Truncate text if it is longer that a given width. | [
"Truncate",
"text",
"if",
"it",
"is",
"longer",
"that",
"a",
"given",
"width."
] | def truncate(self, max_width: int, *, overflow: Optional['OverflowMethod']=None, pad: bool=False) -> None:
_overflow = overflow or self.overflow or DEFAULT_OVERFLOW
if _overflow != 'ignore':
length = cell_len(self.plain)
if length > max_width:
if _overflow == 'ellipsis':
... | ['def', 'truncate(self,', 'max_width:', 'int,', '*,', 'overflow:', "Optional['OverflowMethod']=None,", 'pad:', 'bool=False)', '->', 'None:', '_overflow', '=', 'overflow', 'or', 'self.overflow', 'or', 'DEFAULT_OVERFLOW', 'if', '_overflow', '!=', "'ignore':", 'length', '=', 'cell_len(self.plain)', 'if', 'length', '>', 'm... | 445,125 |
nicknochnack/RealTimeSignLanguageTFJS | span_labeling_test.py | SpanLabelingTest.test_network_invocation_with_internal_logit_output | test_network_invocation_with_internal_logit_output | Validate that the logit outputs are correct. | [
"Validate",
"that",
"the",
"logit",
"outputs",
"are",
"correct."
] | def test_network_invocation_with_internal_logit_output(self):
sequence_length = 15
input_width = 512
test_network = span_labeling.SpanLabeling(input_width=input_width, output='predictions')
sequence_data = tf.keras.Input(shape=(sequence_length, input_width), dtype=tf.float32)
output = test_network(s... | ['def', 'test_network_invocation_with_internal_logit_output(self):', 'sequence_length', '=', '15', 'input_width', '=', '512', 'test_network', '=', 'span_labeling.SpanLabeling(input_width=input_width,', "output='predictions')", 'sequence_data', '=', 'tf.keras.Input(shape=(sequence_length,', 'input_width),', 'dtype=tf.fl... | 850,458 |
dgseten/bad-cv-tfm | calibration_builder_test.py | CalibrationBuilderTest.test_class_agnostic_function_approximation | test_class_agnostic_function_approximation | Ensures that calibration appropriate values, regardless of class. | [
"Ensures",
"that",
"calibration",
"appropriate",
"values,",
"regardless",
"of",
"class."
] | def test_class_agnostic_function_approximation(self):
class_agnostic_x = np.asarray([0.0, 0.5, 1.0])
class_agnostic_y = np.asarray([0.0, 0.25, 0.75])
calibration_config = calibration_pb2.CalibrationConfig()
self._add_function_approximation_to_calibration_proto(calibration_config, class_agnostic_x, class... | ['def', 'test_class_agnostic_function_approximation(self):', 'class_agnostic_x', '=', 'np.asarray([0.0,', '0.5,', '1.0])', 'class_agnostic_y', '=', 'np.asarray([0.0,', '0.25,', '0.75])', 'calibration_config', '=', 'calibration_pb2.CalibrationConfig()', 'self._add_function_approximation_to_calibration_proto(calibration_... | 421,395 |
jfzhuang/IFR | fp16_utils.py | cast_tensor_type | cast_tensor_type | Recursively convert Tensor in inputs from src_type to dst_type. | [
"Recursively",
"convert",
"Tensor",
"in",
"inputs",
"from",
"src_type",
"to",
"dst_type."
] | def cast_tensor_type(inputs, src_type, dst_type):
if isinstance(inputs, nn.Module):
return inputs
elif isinstance(inputs, torch.Tensor):
return inputs.to(dst_type)
elif isinstance(inputs, str):
return inputs
elif isinstance(inputs, np.ndarray):
return inputs
elif isin... | ['def', 'cast_tensor_type(inputs,', 'src_type,', 'dst_type):', 'if', 'isinstance(inputs,', 'nn.Module):', 'return', 'inputs', 'elif', 'isinstance(inputs,', 'torch.Tensor):', 'return', 'inputs.to(dst_type)', 'elif', 'isinstance(inputs,', 'str):', 'return', 'inputs', 'elif', 'isinstance(inputs,', 'np.ndarray):', 'return'... | 597,374 |
neokarn/computer_vision | utility.py | print_dict | print_dict | Recursively visualize a dict and indenting acrrording by the relationship of keys. | [
"Recursively",
"visualize",
"a",
"dict",
"and",
"indenting",
"acrrording",
"by",
"the",
"relationship",
"of",
"keys."
] | def print_dict(d, logger, delimiter=0):
for (k, v) in sorted(d.items()):
if isinstance(v, dict):
logger.info('{}{} : '.format(delimiter * ' ', str(k)))
print_dict(v, logger, delimiter + 4)
elif isinstance(v, list) and len(v) >= 1 and isinstance(v[0], dict):
logger... | ['def', 'print_dict(d,', 'logger,', 'delimiter=0):', 'for', '(k,', 'v)', 'in', 'sorted(d.items()):', 'if', 'isinstance(v,', 'dict):', "logger.info('{}{}", ':', "'.format(delimiter", '*', "'", "',", 'str(k)))', 'print_dict(v,', 'logger,', 'delimiter', '+', '4)', 'elif', 'isinstance(v,', 'list)', 'and', 'len(v)', '>=', '... | 474,523 |
jonathanventura/cylindricalsfmlearner | prepare_train_data.py | dump_example | dump_example | Dumps nth example (+intrinsics) to formatted files. | [
"Dumps",
"nth",
"example",
"(+intrinsics)",
"to",
"formatted",
"files."
] | def dump_example(n, dump_root):
if n % 200 == 0:
print('Progress %d/%d....' % (n, data_loader.num_train))
try:
example = data_loader.get_train_example_with_idx(n)
if example == False:
return
except:
print('bad image')
return
image_seq = concat_image_se... | ['def', 'dump_example(n,', 'dump_root):', 'if', 'n', '%', '200', '==', '0:', "print('Progress", "%d/%d....'", '%', '(n,', 'data_loader.num_train))', 'try:', 'example', '=', 'data_loader.get_train_example_with_idx(n)', 'if', 'example', '==', 'False:', 'return', 'except:', "print('bad", "image')", 'return', 'image_seq', ... | 197,740 |
nicknochnack/RealTimeSignLanguageTFJS | feature_io.py | ParseFromString | ParseFromString | Converts serialized DelfFeatures string to numpy arrays. | [
"Converts",
"serialized",
"DelfFeatures",
"string",
"to",
"numpy",
"arrays."
] | def ParseFromString(string):
delf_features = feature_pb2.DelfFeatures()
delf_features.ParseFromString(string)
return DelfFeaturesToArrays(delf_features) | ['def', 'ParseFromString(string):', 'delf_features', '=', 'feature_pb2.DelfFeatures()', 'delf_features.ParseFromString(string)', 'return', 'DelfFeaturesToArrays(delf_features)'] | 851,654 |
blakeblackshear/frigate | log.py | LogPipe.close | close | Close the write end of the pipe. | [
"Close",
"the",
"write",
"end",
"of",
"the",
"pipe."
] | def close(self) -> None:
os.close(self.fdWrite) | ['def', 'close(self)', '->', 'None:', 'os.close(self.fdWrite)'] | 564,454 |
sshleifer/object_detection_kitti | controller.py | Controller.add_to_replay_buffer | add_to_replay_buffer | Add batch of episodes to replay buffer. | [
"Add",
"batch",
"of",
"episodes",
"to",
"replay",
"buffer."
] | def add_to_replay_buffer(self, initial_state, observations, actions, rewards, terminated, pads):
if self.replay_buffer is None:
return
rewards = np.array(rewards)
pads = np.array(pads)
total_rewards = np.sum(rewards * (1 - pads), axis=0)
episodes = self.convert_from_batched_episodes(initial_... | ['def', 'add_to_replay_buffer(self,', 'initial_state,', 'observations,', 'actions,', 'rewards,', 'terminated,', 'pads):', 'if', 'self.replay_buffer', 'is', 'None:', 'return', 'rewards', '=', 'np.array(rewards)', 'pads', '=', 'np.array(pads)', 'total_rewards', '=', 'np.sum(rewards', '*', '(1', '-', 'pads),', 'axis=0)', ... | 795,340 |
PeizeSun/OneNet | c2_model_loading.py | convert_c2_detectron_names | convert_c2_detectron_names | Map Caffe2 Detectron weight names to Detectron2 names. | [
"Map",
"Caffe2",
"Detectron",
"weight",
"names",
"to",
"Detectron2",
"names."
] | def convert_c2_detectron_names(weights):
logger = logging.getLogger(__name__)
logger.info('Remapping C2 weights ......')
original_keys = sorted(weights.keys())
layer_keys = copy.deepcopy(original_keys)
layer_keys = convert_basic_c2_names(layer_keys)
layer_keys = [k.replace('conv.rpn.fpn2', 'prop... | ['def', 'convert_c2_detectron_names(weights):', 'logger', '=', 'logging.getLogger(__name__)', "logger.info('Remapping", 'C2', 'weights', "......')", 'original_keys', '=', 'sorted(weights.keys())', 'layer_keys', '=', 'copy.deepcopy(original_keys)', 'layer_keys', '=', 'convert_basic_c2_names(layer_keys)', 'layer_keys', '... | 755,809 |
grigorisg9gr/polynomial_nets | inception_score.py | inception_forward | inception_forward | Run the inception model (forward pass). | [
"Run",
"the",
"inception",
"model",
"(forward",
"pass)."
] | def inception_forward(model, ims, batch_size):
(n, c, w, h) = ims.shape
n_batches = int(math.ceil(float(n) / float(batch_size)))
xp = model.xp
ys = xp.empty((n, 1008), dtype=xp.float32)
for i in range(n_batches):
batch_start = i * batch_size
batch_end = min((i + 1) * batch_size, n)
... | ['def', 'inception_forward(model,', 'ims,', 'batch_size):', '(n,', 'c,', 'w,', 'h)', '=', 'ims.shape', 'n_batches', '=', 'int(math.ceil(float(n)', '/', 'float(batch_size)))', 'xp', '=', 'model.xp', 'ys', '=', 'xp.empty((n,', '1008),', 'dtype=xp.float32)', 'for', 'i', 'in', 'range(n_batches):', 'batch_start', '=', 'i', ... | 782,326 |
QData/deepWordBug | generator.py | Generator.clone | clone | Clone this generator with the exact same options. | [
"Clone",
"this",
"generator",
"with",
"the",
"exact",
"same",
"options."
] | def clone(self, fp):
return self.__class__(fp, self._mangle_from_, None, policy=self.policy) | ['def', 'clone(self,', 'fp):', 'return', 'self.__class__(fp,', 'self._mangle_from_,', 'None,', 'policy=self.policy)'] | 543,138 |
SALT-NLP/Adaptive-Compositional-Modules | tokenization_tapas.py | get_numeric_relation | get_numeric_relation | Compares two values and returns their relation or None. | [
"Compares",
"two",
"values",
"and",
"returns",
"their",
"relation",
"or",
"None."
] | def get_numeric_relation(value, other_value, sort_key_fn):
value = sort_key_fn(value)
other_value = sort_key_fn(other_value)
if value == other_value:
return Relation.EQ
if value < other_value:
return Relation.LT
if value > other_value:
return Relation.GT
return None | ['def', 'get_numeric_relation(value,', 'other_value,', 'sort_key_fn):', 'value', '=', 'sort_key_fn(value)', 'other_value', '=', 'sort_key_fn(other_value)', 'if', 'value', '==', 'other_value:', 'return', 'Relation.EQ', 'if', 'value', '<', 'other_value:', 'return', 'Relation.LT', 'if', 'value', '>', 'other_value:', 'retu... | 409,133 |
juaml/julearn | test_prepare.py | test_pick_columns_using_regex_match | test_pick_columns_using_regex_match | Test pick columns using regexes. | [
"Test",
"pick",
"columns",
"using",
"regexes."
] | def test_pick_columns_using_regex_match() -> None:
columns = ['conf_1', 'conf_2', 'feat_1', 'feat_2', 'Feat_3']
regexes = ['.*conf.*', '.*feat.*']
picked = _pick_columns(regexes, columns)
assert columns[:-1] == picked
columns = ['conf_1', 'conf_2', '_feat_1', 'feat_2', 'Feat_3']
regexes = ['.*co... | ['def', 'test_pick_columns_using_regex_match()', '->', 'None:', 'columns', '=', "['conf_1',", "'conf_2',", "'feat_1',", "'feat_2',", "'Feat_3']", 'regexes', '=', "['.*conf.*',", "'.*feat.*']", 'picked', '=', '_pick_columns(regexes,', 'columns)', 'assert', 'columns[:-1]', '==', 'picked', 'columns', '=', "['conf_1',", "'... | 593,731 |
rudranil723/mini-main | query.py | QuerySet.delete | delete | Delete the records in the current QuerySet. | [
"Delete",
"the",
"records",
"in",
"the",
"current",
"QuerySet."
] | def delete(self):
assert self.query.can_filter(), "Cannot use 'limit' or 'offset' with delete."
if self._fields is not None:
raise TypeError('Cannot call delete() after .values() or .values_list()')
del_query = self._chain()
del_query._for_write = True
del_query.query.select_for_update = Fal... | ['def', 'delete(self):', 'assert', 'self.query.can_filter(),', '"Cannot', 'use', "'limit'", 'or', "'offset'", 'with', 'delete."', 'if', 'self._fields', 'is', 'not', 'None:', 'raise', "TypeError('Cannot", 'call', 'delete()', 'after', '.values()', 'or', ".values_list()')", 'del_query', '=', 'self._chain()', 'del_query._f... | 316,038 |
joongbo/tta | run_unsupervisedstsb.py | create_instances_from_tokens | create_instances_from_tokens | Creates `TestInstance`s for a single sentence. | [
"Creates",
"`TestInstance`s",
"for",
"a",
"single",
"sentence."
] | def create_instances_from_tokens(tokens):
instance = TestingInstance(tokens)
return instance | ['def', 'create_instances_from_tokens(tokens):', 'instance', '=', 'TestingInstance(tokens)', 'return', 'instance'] | 426,328 |
arshpreetsingh/quantopian-machinelearning | strings.py | posix_path | posix_path | Turn a path into posix-style path/to/etc Mainly for use in latex on Windows, where native Windows paths are not allowed. | [
"Turn",
"a",
"path",
"into",
"posix-style",
"path/to/etc",
"Mainly",
"for",
"use",
"in",
"latex",
"on",
"Windows,",
"where",
"native",
"Windows",
"paths",
"are",
"not",
"allowed."
] | def posix_path(path):
if os.path.sep != '/':
return path.replace(os.path.sep, '/')
return path | ['def', 'posix_path(path):', 'if', 'os.path.sep', '!=', "'/':", 'return', 'path.replace(os.path.sep,', "'/')", 'return', 'path'] | 888,078 |
ChenhongyiYang/PPAL | general_data.py | GeneralData.new | new | Return a new results with same image meta information. | [
"Return",
"a",
"new",
"results",
"with",
"same",
"image",
"meta",
"information."
] | def new(self, meta_info=None, data=None):
new_data = self.__class__()
new_data.set_meta_info(dict(self.meta_info_items()))
if meta_info is not None:
new_data.set_meta_info(meta_info)
if data is not None:
new_data.set_data(data)
return new_data | ['def', 'new(self,', 'meta_info=None,', 'data=None):', 'new_data', '=', 'self.__class__()', 'new_data.set_meta_info(dict(self.meta_info_items()))', 'if', 'meta_info', 'is', 'not', 'None:', 'new_data.set_meta_info(meta_info)', 'if', 'data', 'is', 'not', 'None:', 'new_data.set_data(data)', 'return', 'new_data'] | 821,279 |
rudranil723/mini-main | debug.py | ExceptionReporter.get_traceback_data | get_traceback_data | Return a dictionary containing traceback information. | [
"Return",
"a",
"dictionary",
"containing",
"traceback",
"information."
] | def get_traceback_data(self):
if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
self.template_does_not_exist = True
self.postmortem = self.exc_value.chain or [self.exc_value]
frames = self.get_traceback_frames()
for (i, frame) in enumerate(frames):
if 'vars' in fr... | ['def', 'get_traceback_data(self):', 'if', 'self.exc_type', 'and', 'issubclass(self.exc_type,', 'TemplateDoesNotExist):', 'self.template_does_not_exist', '=', 'True', 'self.postmortem', '=', 'self.exc_value.chain', 'or', '[self.exc_value]', 'frames', '=', 'self.get_traceback_frames()', 'for', '(i,', 'frame)', 'in', 'en... | 316,844 |
flavioschneider/rl-transfer- | test_erwr.py | TestERWR.test_erwr_cartpole | test_erwr_cartpole | Test ERWR with Cartpole-v1 environment. | [
"Test",
"ERWR",
"with",
"Cartpole-v1",
"environment."
] | def test_erwr_cartpole(self):
with TFTrainer(snapshot_config, sess=self.sess) as trainer:
deterministic.set_seed(1)
env = GymEnv('CartPole-v1')
policy = CategoricalMLPPolicy(name='policy', env_spec=env.spec, hidden_sizes=(32, 32))
baseline = LinearFeatureBaseline(env_spec=env.spec)
... | ['def', 'test_erwr_cartpole(self):', 'with', 'TFTrainer(snapshot_config,', 'sess=self.sess)', 'as', 'trainer:', 'deterministic.set_seed(1)', 'env', '=', "GymEnv('CartPole-v1')", 'policy', '=', "CategoricalMLPPolicy(name='policy',", 'env_spec=env.spec,', 'hidden_sizes=(32,', '32))', 'baseline', '=', 'LinearFeatureBaseli... | 861,743 |
huawei-noah/xingtian | atari_impala_opt.py | AtariImpalaOpt.reset | reset | Clear the sample_vector buffer. | [
"Clear",
"the",
"sample_vector",
"buffer."
] | def reset(self):
self.sample_vector = dict()
for env_id in range(self.vector_env_size):
self.sample_vector[env_id] = defaultdict(list) | ['def', 'reset(self):', 'self.sample_vector', '=', 'dict()', 'for', 'env_id', 'in', 'range(self.vector_env_size):', 'self.sample_vector[env_id]', '=', 'defaultdict(list)'] | 962,049 |
explosion/spaCy | test_span_group.py | test_span_group_init_doc | test_span_group_init_doc | Test that all spans must come from the specified doc. | [
"Test",
"that",
"all",
"spans",
"must",
"come",
"from",
"the",
"specified",
"doc."
] | def test_span_group_init_doc(en_tokenizer):
doc1 = en_tokenizer('a b c')
doc2 = en_tokenizer('a b c')
span_group = SpanGroup(doc1, spans=[doc1[0:1], doc1[1:2]])
with pytest.raises(ValueError):
span_group = SpanGroup(doc1, spans=[doc1[0:1], doc2[1:2]]) | ['def', 'test_span_group_init_doc(en_tokenizer):', 'doc1', '=', "en_tokenizer('a", 'b', "c')", 'doc2', '=', "en_tokenizer('a", 'b', "c')", 'span_group', '=', 'SpanGroup(doc1,', 'spans=[doc1[0:1],', 'doc1[1:2]])', 'with', 'pytest.raises(ValueError):', 'span_group', '=', 'SpanGroup(doc1,', 'spans=[doc1[0:1],', 'doc2[1:2]... | 894,142 |
sarnsdev/social-alignment-data-mining | configparser.py | parse_config_string | parse_config_string | Parses a config string (comma-separated key=value components) into a dict. | [
"Parses",
"a",
"config",
"string",
"(comma-separated",
"key=value",
"components)",
"into",
"a",
"dict."
] | def parse_config_string(config_string, issue_warnings=True):
config_dict = {}
my_splitter = shlex.shlex(config_string, posix=True)
my_splitter.whitespace = ','
my_splitter.whitespace_split = True
for kv_pair in my_splitter:
kv_pair = kv_pair.strip()
if not kv_pair:
contin... | ['def', 'parse_config_string(config_string,', 'issue_warnings=True):', 'config_dict', '=', '{}', 'my_splitter', '=', 'shlex.shlex(config_string,', 'posix=True)', 'my_splitter.whitespace', '=', "','", 'my_splitter.whitespace_split', '=', 'True', 'for', 'kv_pair', 'in', 'my_splitter:', 'kv_pair', '=', 'kv_pair.strip()', ... | 392,452 |
ldkong1205/LaserMix | detr3d_transformer.py | Detr3DTransformerDecoder.forward | forward | Forward function for `Detr3DTransformerDecoder`. | [
"Forward",
"function",
"for",
"`Detr3DTransformerDecoder`."
] | def forward(self, query, *args, reference_points=None, reg_branches=None, **kwargs):
output = query
intermediate = []
intermediate_reference_points = []
for (lid, layer) in enumerate(self.layers):
reference_points_input = reference_points
output = layer(output, *args, reference_points=re... | ['def', 'forward(self,', 'query,', '*args,', 'reference_points=None,', 'reg_branches=None,', '**kwargs):', 'output', '=', 'query', 'intermediate', '=', '[]', 'intermediate_reference_points', '=', '[]', 'for', '(lid,', 'layer)', 'in', 'enumerate(self.layers):', 'reference_points_input', '=', 'reference_points', 'output'... | 624,526 |
segmind/cral | core.py | ClassificationPipe.set_algo | set_algo | Set model for training and prediction. | [
"Set",
"model",
"for",
"training",
"and",
"prediction."
] | def set_algo(self, feature_extractor, config, weights='imagenet', base_trainable=False, preprocessing_fn=None, optimizer=tf.keras.optimizers.Adam(lr=0.0001, clipnorm=0.001), distribute_strategy=None):
classification_algo_meta = dict(feature_extractor_from_cral=False, classification_meta=None)
assert isinstance(... | ['def', 'set_algo(self,', 'feature_extractor,', 'config,', "weights='imagenet',", 'base_trainable=False,', 'preprocessing_fn=None,', 'optimizer=tf.keras.optimizers.Adam(lr=0.0001,', 'clipnorm=0.001),', 'distribute_strategy=None):', 'classification_algo_meta', '=', 'dict(feature_extractor_from_cral=False,', 'classificat... | 490,648 |
jimtin/Stock_Comparison | misc_util.py | Configuration.get_build_temp_dir | get_build_temp_dir | Return a path to a temporary directory where temporary files should be placed. | [
"Return",
"a",
"path",
"to",
"a",
"temporary",
"directory",
"where",
"temporary",
"files",
"should",
"be",
"placed."
] | def get_build_temp_dir(self):
cmd = get_cmd('build')
cmd.ensure_finalized()
return cmd.build_temp | ['def', 'get_build_temp_dir(self):', 'cmd', '=', "get_cmd('build')", 'cmd.ensure_finalized()', 'return', 'cmd.build_temp'] | 386,872 |
deepmind/brave | video_sampling.py | decode_crop_images | decode_crop_images | Given a crop window, decode the input tensors. | [
"Given",
"a",
"crop",
"window,",
"decode",
"the",
"input",
"tensors."
] | def decode_crop_images(jpeg_encoded_images: tf.Tensor, crop_window: tf.Tensor) -> tf.Tensor:
return tf.map_fn(lambda x: _decode_and_crop(x, crop_window), jpeg_encoded_images, fn_output_signature=tf.uint8) | ['def', 'decode_crop_images(jpeg_encoded_images:', 'tf.Tensor,', 'crop_window:', 'tf.Tensor)', '->', 'tf.Tensor:', 'return', 'tf.map_fn(lambda', 'x:', '_decode_and_crop(x,', 'crop_window),', 'jpeg_encoded_images,', 'fn_output_signature=tf.uint8)'] | 108,350 |
salu133445/bmusegan | metrics.py | eval_dataset | eval_dataset | Run evaluation on a dataset stored in either shared array (if `location` is 'sa') or in hard disk (if `location` is 'hd') and save the results to the given directory. | [
"Run",
"evaluation",
"on",
"a",
"dataset",
"stored",
"in",
"either",
"shared",
"array",
"(if",
"`location`",
"is",
"'sa')",
"or",
"in",
"hard",
"disk",
"(if",
"`location`",
"is",
"'hd')",
"and",
"save",
"the",
"results",
"to",
"the",
"given",
"directory."
] | def eval_dataset(filepath, result_dir, location, config):
print('[*] Loading dataset...')
if location == 'sa':
data = sa.attach(filepath)
elif location == 'hd':
data = sa.attach(filepath)
else:
raise ValueError('Unrecognized value for `location`')
print('[*] Running evaluatio... | ['def', 'eval_dataset(filepath,', 'result_dir,', 'location,', 'config):', "print('[*]", 'Loading', "dataset...')", 'if', 'location', '==', "'sa':", 'data', '=', 'sa.attach(filepath)', 'elif', 'location', '==', "'hd':", 'data', '=', 'sa.attach(filepath)', 'else:', 'raise', "ValueError('Unrecognized", 'value', 'for', "`l... | 461,878 |
gunthercox/ChatterBot | ma.py | MaskedArray.unshare_mask | unshare_mask | If currently sharing mask, make a copy. | [
"If",
"currently",
"sharing",
"mask,",
"make",
"a",
"copy."
] | def unshare_mask(self):
if self._shared_mask:
self._mask = make_mask(self._mask, copy=1, flag=0)
self._shared_mask = 0 | ['def', 'unshare_mask(self):', 'if', 'self._shared_mask:', 'self._mask', '=', 'make_mask(self._mask,', 'copy=1,', 'flag=0)', 'self._shared_mask', '=', '0'] | 532,460 |
HDI-Project/ATM | database.py | Database.mark_datarun_running | mark_datarun_running | Set the status of the Datarun to RUNNING and set the 'start_time' field to the current datetime. | [
"Set",
"the",
"status",
"of",
"the",
"Datarun",
"to",
"RUNNING",
"and",
"set",
"the",
"'start_time'",
"field",
"to",
"the",
"current",
"datetime."
] | def mark_datarun_running(self, datarun_id):
datarun = self.get_datarun(datarun_id)
if datarun.status == RunStatus.PENDING:
datarun.status = RunStatus.RUNNING
datarun.start_time = datetime.now() | ['def', 'mark_datarun_running(self,', 'datarun_id):', 'datarun', '=', 'self.get_datarun(datarun_id)', 'if', 'datarun.status', '==', 'RunStatus.PENDING:', 'datarun.status', '=', 'RunStatus.RUNNING', 'datarun.start_time', '=', 'datetime.now()'] | 402,695 |
lvwerra/trl | dpo_trainer.py | DPOTrainer.log | log | Log `logs` on the various objects watching training, including stored metrics. | [
"Log",
"`logs`",
"on",
"the",
"various",
"objects",
"watching",
"training,",
"including",
"stored",
"metrics."
] | def log(self, logs: Dict[str, float]) -> None:
train_eval = 'train' if 'loss' in logs else 'eval'
for (key, metrics) in self._stored_metrics[train_eval].items():
logs[key] = torch.tensor(metrics).mean().item()
del self._stored_metrics[train_eval]
return super().log(logs) | ['def', 'log(self,', 'logs:', 'Dict[str,', 'float])', '->', 'None:', 'train_eval', '=', "'train'", 'if', "'loss'", 'in', 'logs', 'else', "'eval'", 'for', '(key,', 'metrics)', 'in', 'self._stored_metrics[train_eval].items():', 'logs[key]', '=', 'torch.tensor(metrics).mean().item()', 'del', 'self._stored_metrics[train_ev... | 425,897 |
nicknochnack/RealTimeSignLanguageTFJS | common_layer.py | CommonLayers.set_regularizer_scale | set_regularizer_scale | Override / set a new weights regularizer scale. | [
"Override",
"/",
"set",
"a",
"new",
"weights",
"regularizer",
"scale."
] | def set_regularizer_scale(self, regularizer_scale):
self._regularizer_scale = regularizer_scale | ['def', 'set_regularizer_scale(self,', 'regularizer_scale):', 'self._regularizer_scale', '=', 'regularizer_scale'] | 831,158 |
Eric3911/OpenAGI | reverse_pad_list.py | reverse_pad_list | reverse_pad_list | Reverse padding for the list of tensors. | [
"Reverse",
"padding",
"for",
"the",
"list",
"of",
"tensors."
] | def reverse_pad_list(ys_pad: paddle.Tensor, ys_lens: paddle.Tensor, pad_value: float=-1.0) -> paddle.Tensor:
r_ys_pad = pad_sequence([paddle.flip(y[:i], [0]) for (y, i) in zip(ys_pad, ys_lens)], True, pad_value)
return r_ys_pad | ['def', 'reverse_pad_list(ys_pad:', 'paddle.Tensor,', 'ys_lens:', 'paddle.Tensor,', 'pad_value:', 'float=-1.0)', '->', 'paddle.Tensor:', 'r_ys_pad', '=', 'pad_sequence([paddle.flip(y[:i],', '[0])', 'for', '(y,', 'i)', 'in', 'zip(ys_pad,', 'ys_lens)],', 'True,', 'pad_value)', 'return', 'r_ys_pad'] | 251,951 |
deepmind/acme | tree_utils_test.py | SequenceStackTest.test_stack_sequence_fields | test_stack_sequence_fields | Tests that `stack_sequence_fields` behaves correctly on nested data. | [
"Tests",
"that",
"`stack_sequence_fields`",
"behaves",
"correctly",
"on",
"nested",
"data."
] | def test_stack_sequence_fields(self):
stacked = tree_utils.stack_sequence_fields(TEST_SEQUENCE)
tree.assert_same_structure(stacked, TEST_SEQUENCE[0])
self.assertEqual(stacked['action'].shape, (3, 1))
self.assertEqual(stacked['observation'][0].shape, (3, 3))
self.assertEqual(stacked['reward'].shape, ... | ['def', 'test_stack_sequence_fields(self):', 'stacked', '=', 'tree_utils.stack_sequence_fields(TEST_SEQUENCE)', 'tree.assert_same_structure(stacked,', 'TEST_SEQUENCE[0])', "self.assertEqual(stacked['action'].shape,", '(3,', '1))', "self.assertEqual(stacked['observation'][0].shape,", '(3,', '3))', "self.assertEqual(stac... | 8,443 |
scottemmons/rvs | test_runs.py | test_gcsl_run | test_gcsl_run | Check that a GCSL lunar run completes with no errors. | [
"Check",
"that",
"a",
"GCSL",
"lunar",
"run",
"completes",
"with",
"no",
"errors."
] | def test_gcsl_run():
os.environ['WANDB_MODE'] = 'offline'
subprocess.run(lunar_command, check=True) | ['def', 'test_gcsl_run():', "os.environ['WANDB_MODE']", '=', "'offline'", 'subprocess.run(lunar_command,', 'check=True)'] | 327,056 |
Kvatsx/Artificial-Intelligence-Assignments | image_test.py | test_magic | test_magic | tests a given file to see if the magic hex matches. | [
"tests",
"a",
"given",
"file",
"to",
"see",
"if",
"the",
"magic",
"hex",
"matches."
] | def test_magic(f, magic_hex):
data = f.read(len(magic_hex))
if len(data) != len(magic_hex):
return 0
for i in range(len(magic_hex)):
if magic_hex[i] != ord_(data[i]):
return 0
return 1 | ['def', 'test_magic(f,', 'magic_hex):', 'data', '=', 'f.read(len(magic_hex))', 'if', 'len(data)', '!=', 'len(magic_hex):', 'return', '0', 'for', 'i', 'in', 'range(len(magic_hex)):', 'if', 'magic_hex[i]', '!=', 'ord_(data[i]):', 'return', '0', 'return', '1'] | 76,410 |
Ruturaj123/Flowchart-Detection | embedding_ops_test.py | SampledScatteredEmbeddingLookupSparseTest.test_output_values | test_output_values | Verifies the values in a trivial case. | [
"Verifies",
"the",
"values",
"in",
"a",
"trivial",
"case."
] | def test_output_values(self):
with self.test_session():
sp_values = sparse_tensor_lib.SparseTensor(values=['a'], indices=[[1, 0]], dense_shape=[3, 1])
params = constant_op.constant([0.1, 0.2, 0.3])
result = embedding_ops._sampled_scattered_embedding_lookup_sparse(params, sp_values, dimension... | ['def', 'test_output_values(self):', 'with', 'self.test_session():', 'sp_values', '=', "sparse_tensor_lib.SparseTensor(values=['a'],", 'indices=[[1,', '0]],', 'dense_shape=[3,', '1])', 'params', '=', 'constant_op.constant([0.1,', '0.2,', '0.3])', 'result', '=', 'embedding_ops._sampled_scattered_embedding_lookup_sparse(... | 603,620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.