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
rudranil723/mini-main
_regex_core.py
parse_repl_named_char
parse_repl_named_char
Parses a named character in a replacement string.
[ "Parses", "a", "named", "character", "in", "a", "replacement", "string." ]
def parse_repl_named_char(source): saved_pos = source.pos if source.match('{'): name = source.get_while(ALPHA | set(' ')) if source.match('}'): try: value = unicodedata.lookup(name) return ord(value) except KeyError: raise e...
['def', 'parse_repl_named_char(source):', 'saved_pos', '=', 'source.pos', 'if', "source.match('{'):", 'name', '=', 'source.get_while(ALPHA', '|', "set('", "'))", 'if', "source.match('}'):", 'try:', 'value', '=', 'unicodedata.lookup(name)', 'return', 'ord(value)', 'except', 'KeyError:', 'raise', "error('undefined", 'cha...
269,831
eddylau328/fyp-artificial-intelligence-ac-control-device
acl.py
ObjectACL.user_project
user_project
Compute the user project charged for API requests for this ACL.
[ "Compute", "the", "user", "project", "charged", "for", "API", "requests", "for", "this", "ACL." ]
def user_project(self): return self.blob.user_project
['def', 'user_project(self):', 'return', 'self.blob.user_project']
214,986
Eric3911/OpenAGI
online_clustering.py
merge_vectors
merge_vectors
Merge feature (embedding) vectors estimated to be the same cluster label.
[ "Merge", "feature", "(embedding)", "vectors", "estimated", "to", "be", "the", "same", "cluster", "label." ]
def merge_vectors(selected_inds: torch.Tensor, emb_ndx: torch.Tensor, pre_cluster_labels: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: if emb_ndx.shape[0] != pre_cluster_labels.shape[0]: raise ValueError('pre_cluster_labels and emb_ndx have mismatch in dimension') avg_emb = torch.mean(emb_ndx[sel...
['def', 'merge_vectors(selected_inds:', 'torch.Tensor,', 'emb_ndx:', 'torch.Tensor,', 'pre_cluster_labels:', 'torch.Tensor)', '->', 'Tuple[torch.Tensor,', 'torch.Tensor]:', 'if', 'emb_ndx.shape[0]', '!=', 'pre_cluster_labels.shape[0]:', 'raise', "ValueError('pre_cluster_labels", 'and', 'emb_ndx', 'have', 'mismatch', 'i...
272,955
voxel51/fiftyone
voc.py
VOCAnnotation.from_xml
from_xml
Creates a :class:`VOCAnnotation` instance from an XML annotations file.
[ "Creates", "a", ":class:`VOCAnnotation`", "instance", "from", "an", "XML", "annotations", "file." ]
def from_xml(cls, xml_path): d = fou.load_xml_as_json_dict(xml_path) return cls.from_dict(d)
['def', 'from_xml(cls,', 'xml_path):', 'd', '=', 'fou.load_xml_as_json_dict(xml_path)', 'return', 'cls.from_dict(d)']
584,229
myothida/Supervised-Machine-Learning
fancy_getopt.py
FancyGetopt.set_aliases
set_aliases
Set the aliases for this option parser.
[ "Set", "the", "aliases", "for", "this", "option", "parser." ]
def set_aliases(self, alias): self._check_alias_dict(alias, 'alias') self.alias = alias
['def', 'set_aliases(self,', 'alias):', 'self._check_alias_dict(alias,', "'alias')", 'self.alias', '=', 'alias']
447,095
jeanphix/Flask-Dashed
admin.py
ObjectAdminModule.default_rules
default_rules
Adds object list rule to current app.
[ "Adds", "object", "list", "rule", "to", "current", "app." ]
def default_rules(self): return [('/', 'list', self.list_view.as_view('short_title', self)), ('/page/<page>', 'listpaged', self.list_view.as_view('short_title', self)), ('/new', 'new', self.form_view.as_view('short_title', self)), ('/<pk>/edit', 'edit', self.form_view.as_view('short_title', self)), ('/<pk>/delete',...
['def', 'default_rules(self):', 'return', "[('/',", "'list',", "self.list_view.as_view('short_title',", 'self)),', "('/page/<page>',", "'listpaged',", "self.list_view.as_view('short_title',", 'self)),', "('/new',", "'new',", "self.form_view.as_view('short_title',", 'self)),', "('/<pk>/edit',", "'edit',", "self.form_vie...
211,177
facebookresearch/salina
__init__.py
L2ActionAgent
L2ActionAgent
L2 regularizer added in the framework.
[ "L2", "regularizer", "added", "in", "the", "framework." ]
def L2ActionAgent(input_dimension, output_dimension, hidden_size, l2_coeff, start_steps, layer_norm): return CRLAgents(L2Action(input_dimension, output_dimension, hidden_size, l2_coeff, start_steps, input_name='env/env_obs', layer_norm=layer_norm))
['def', 'L2ActionAgent(input_dimension,', 'output_dimension,', 'hidden_size,', 'l2_coeff,', 'start_steps,', 'layer_norm):', 'return', 'CRLAgents(L2Action(input_dimension,', 'output_dimension,', 'hidden_size,', 'l2_coeff,', 'start_steps,', "input_name='env/env_obs',", 'layer_norm=layer_norm))']
328,595
facebookresearch/deep_bisim4control
lqr_solver.py
solve
solve
Returns the optimal value and policy for LQR problem.
[ "Returns", "the", "optimal", "value", "and", "policy", "for", "LQR", "problem." ]
def solve(env): n = env.physics.model.nq m = env.physics.model.nu mass = np.zeros((n, n)) wrapper.mjbindings.mjlib.mj_fullM(env.physics.model.ptr, mass, env.physics.data.qM) stiffness = np.diag(env.physics.model.jnt_stiffness.ravel()) damping = np.diag(env.physics.model.dof_damping.ravel()) ...
['def', 'solve(env):', 'n', '=', 'env.physics.model.nq', 'm', '=', 'env.physics.model.nu', 'mass', '=', 'np.zeros((n,', 'n))', 'wrapper.mjbindings.mjlib.mj_fullM(env.physics.model.ptr,', 'mass,', 'env.physics.data.qM)', 'stiffness', '=', 'np.diag(env.physics.model.jnt_stiffness.ravel())', 'damping', '=', 'np.diag(env.p...
536,403
TerenceCYJ/S2HAND
hand_detect.py
dump
dump
Save predictions into a json file.
[ "Save", "predictions", "into", "a", "json", "file." ]
def dump(pred_out_path, all_hand_peaks, all_hand_peaks_values, all_hand_names): xy_pred_list = [x.tolist() for x in all_hand_peaks] value_pred_list = [x.tolist() for x in all_hand_peaks_values] name_list = [x.tolist() for x in all_hand_names] with open(pred_out_path, 'w') as fo: json.dump([xy_pr...
['def', 'dump(pred_out_path,', 'all_hand_peaks,', 'all_hand_peaks_values,', 'all_hand_names):', 'xy_pred_list', '=', '[x.tolist()', 'for', 'x', 'in', 'all_hand_peaks]', 'value_pred_list', '=', '[x.tolist()', 'for', 'x', 'in', 'all_hand_peaks_values]', 'name_list', '=', '[x.tolist()', 'for', 'x', 'in', 'all_hand_names]'...
327,296
QData/deepWordBug
test_sequences.py
test_capability
test_capability
Check that capability lookup works.
[ "Check", "that", "capability", "lookup", "works." ]
def test_capability(): @as_subprocess def child(): t = TestTerminal() sc = unicode_cap('sc') assert t.save == sc assert t.save == sc child()
['def', 'test_capability():', '@as_subprocess', 'def', 'child():', 't', '=', 'TestTerminal()', 'sc', '=', "unicode_cap('sc')", 'assert', 't.save', '==', 'sc', 'assert', 't.save', '==', 'sc', 'child()']
541,168
juaml/julearn
test_version.py
test_multiple_false
test_multiple_false
Test multiple checks false.
[ "Test", "multiple", "checks", "false." ]
def test_multiple_false() -> None: assert check_version('3.2.1', major_check=lambda x: int(x) == 3, minor_check=lambda x: int(x) == 3, patch_check=lambda x: int(x) >= 2) is False
['def', 'test_multiple_false()', '->', 'None:', 'assert', "check_version('3.2.1',", 'major_check=lambda', 'x:', 'int(x)', '==', '3,', 'minor_check=lambda', 'x:', 'int(x)', '==', '3,', 'patch_check=lambda', 'x:', 'int(x)', '>=', '2)', 'is', 'False']
593,823
suarez12138/AI-Reversi_IMP_TextDichotomy
test_mio.py
mlarr
mlarr
Convenience function to return matlab-compatible 2-D array.
[ "Convenience", "function", "to", "return", "matlab-compatible", "2-D", "array." ]
def mlarr(*args, **kwargs): arr = np.array(*args, **kwargs) arr.shape = matdims(arr) return arr
['def', 'mlarr(*args,', '**kwargs):', 'arr', '=', 'np.array(*args,', '**kwargs)', 'arr.shape', '=', 'matdims(arr)', 'return', 'arr']
99,546
aws/sagemaker-python-sdk
utils.py
build_dict
build_dict
Return a dict of key and value pair if value is not None, otherwise return an empty dict.
[ "Return", "a", "dict", "of", "key", "and", "value", "pair", "if", "value", "is", "not", "None,", "otherwise", "return", "an", "empty", "dict." ]
def build_dict(key, value): if value: return {key: value} return {}
['def', 'build_dict(key,', 'value):', 'if', 'value:', 'return', '{key:', 'value}', 'return', '{}']
829,719
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
dp_pca.py
ComputeDPPrincipalProjection
ComputeDPPrincipalProjection
Compute differentially private projection.
[ "Compute", "differentially", "private", "projection." ]
def ComputeDPPrincipalProjection(data, projection_dims, sanitizer, eps_delta, sigma): (eps, delta) = eps_delta normalized_data = tf.nn.l2_normalize(data, 1) covar = tf.matmul(tf.transpose(normalized_data), normalized_data) saved_shape = tf.shape(covar) num_examples = tf.slice(tf.shape(data), [0], [1...
['def', 'ComputeDPPrincipalProjection(data,', 'projection_dims,', 'sanitizer,', 'eps_delta,', 'sigma):', '(eps,', 'delta)', '=', 'eps_delta', 'normalized_data', '=', 'tf.nn.l2_normalize(data,', '1)', 'covar', '=', 'tf.matmul(tf.transpose(normalized_data),', 'normalized_data)', 'saved_shape', '=', 'tf.shape(covar)', 'nu...
53,817
aeon-toolkit/aeon
test_naive.py
test_strategy_mean_seasonal_simple
test_strategy_mean_seasonal_simple
Create 2d matrix (seasons on rows, time points of each season on columns).
[ "Create", "2d", "matrix", "(seasons", "on", "rows,", "time", "points", "of", "each", "season", "on", "columns)." ]
def test_strategy_mean_seasonal_simple(n_seasons, sp): values = np.random.normal(size=(n_seasons, sp)) y = pd.Series(values.ravel()) expected = values.mean(axis=0) assert expected.shape == (sp,) f = NaiveForecaster(strategy='mean', sp=sp) f.fit(y) fh = np.arange(1, sp + 1) y_pred = f.pre...
['def', 'test_strategy_mean_seasonal_simple(n_seasons,', 'sp):', 'values', '=', 'np.random.normal(size=(n_seasons,', 'sp))', 'y', '=', 'pd.Series(values.ravel())', 'expected', '=', 'values.mean(axis=0)', 'assert', 'expected.shape', '==', '(sp,)', 'f', '=', "NaiveForecaster(strategy='mean',", 'sp=sp)', 'f.fit(y)', 'fh',...
399,732
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
timed.py
TimestampSigner.timestamp_to_datetime
timestamp_to_datetime
Used to convert the timestamp from :meth:`get_timestamp` into a datetime object.
[ "Used", "to", "convert", "the", "timestamp", "from", ":meth:`get_timestamp`", "into", "a", "datetime", "object." ]
def timestamp_to_datetime(self, ts): return datetime.utcfromtimestamp(ts)
['def', 'timestamp_to_datetime(self,', 'ts):', 'return', 'datetime.utcfromtimestamp(ts)']
102,182
zackmcnulty/CSE_446-Machine_Learning
mlab.py
base_repr
base_repr
Return the representation of a *number* in any given *base*.
[ "Return", "the", "representation", "of", "a", "*number*", "in", "any", "given", "*base*." ]
def base_repr(number, base=2, padding=0): chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' if number < base: return (padding - 1) * chars[0] + chars[int(number)] max_exponent = int(math.log(number) / math.log(base)) max_power = int(base) ** max_exponent lead_digit = int(number / max_power) ...
['def', 'base_repr(number,', 'base=2,', 'padding=0):', 'chars', '=', "'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'", 'if', 'number', '<', 'base:', 'return', '(padding', '-', '1)', '*', 'chars[0]', '+', 'chars[int(number)]', 'max_exponent', '=', 'int(math.log(number)', '/', 'math.log(base))', 'max_power', '=', 'int(base)', '*...
194,514
stan-hua/CytoImageNet
visualize_classes.py
plot_labels
plot_labels
Create and save gridplots for each label in <labels>.
[ "Create", "and", "save", "gridplots", "for", "each", "label", "in", "<labels>." ]
def plot_labels(labels, df_metadata=None): for label in labels: imgs = load_images_from_label(label, num_imgs=81, df=df_metadata) if torch_gridplot_images(imgs, fig_title=label, save_name=label + '_grid', save=True) is None: print('Success! for ' + label) else: print(...
['def', 'plot_labels(labels,', 'df_metadata=None):', 'for', 'label', 'in', 'labels:', 'imgs', '=', 'load_images_from_label(label,', 'num_imgs=81,', 'df=df_metadata)', 'if', 'torch_gridplot_images(imgs,', 'fig_title=label,', 'save_name=label', '+', "'_grid',", 'save=True)', 'is', 'None:', "print('Success!", 'for', "'", ...
524,696
RasaHQ/rasa
test.py
set_test_arguments
set_test_arguments
Sets test arguments for a parser.
[ "Sets", "test", "arguments", "for", "a", "parser." ]
def set_test_arguments(parser: argparse.ArgumentParser) -> None: add_model_param(parser, add_positional_arg=False) core_arguments = parser.add_argument_group('Core Test Arguments') add_test_core_argument_group(core_arguments) nlu_arguments = parser.add_argument_group('NLU Test Arguments') add_test_n...
['def', 'set_test_arguments(parser:', 'argparse.ArgumentParser)', '->', 'None:', 'add_model_param(parser,', 'add_positional_arg=False)', 'core_arguments', '=', "parser.add_argument_group('Core", 'Test', "Arguments')", 'add_test_core_argument_group(core_arguments)', 'nlu_arguments', '=', "parser.add_argument_group('NLU"...
836,657
zehuichen123/AutoAlignV2
custom_3d.py
Custom3DDataset.prepare_test_data
prepare_test_data
Prepare data for testing.
[ "Prepare", "data", "for", "testing." ]
def prepare_test_data(self, index): input_dict = self.get_data_info(index) self.pre_pipeline(input_dict) example = self.pipeline(input_dict) return example
['def', 'prepare_test_data(self,', 'index):', 'input_dict', '=', 'self.get_data_info(index)', 'self.pre_pipeline(input_dict)', 'example', '=', 'self.pipeline(input_dict)', 'return', 'example']
416,684
sek788432/Waymo-2D-Object-Detection
movinet.py
build_movinet
build_movinet
Builds MoViNet backbone from a config.
[ "Builds", "MoViNet", "backbone", "from", "a", "config." ]
def build_movinet(input_specs: tf.keras.layers.InputSpec, backbone_config: hyperparams.Config, norm_activation_config: hyperparams.Config, l2_regularizer: tf.keras.regularizers.Regularizer=None) -> tf.keras.Model: backbone_type = backbone_config.type backbone_cfg = backbone_config.get() assert backbone_type...
['def', 'build_movinet(input_specs:', 'tf.keras.layers.InputSpec,', 'backbone_config:', 'hyperparams.Config,', 'norm_activation_config:', 'hyperparams.Config,', 'l2_regularizer:', 'tf.keras.regularizers.Regularizer=None)', '->', 'tf.keras.Model:', 'backbone_type', '=', 'backbone_config.type', 'backbone_cfg', '=', 'back...
973,321
adamshamsudeen/vision.ai
__init__.py
VersionControl.check_version
check_version
Return True if the version is identical to what exists and doesn't need to be updated.
[ "Return", "True", "if", "the", "version", "is", "identical", "to", "what", "exists", "and", "doesn't", "need", "to", "be", "updated." ]
def check_version(self, dest, rev_options): raise NotImplementedError
['def', 'check_version(self,', 'dest,', 'rev_options):', 'raise', 'NotImplementedError']
943,359
enuguru/artificial_intelligence_and_machine_learning
test.py
Client.get
get
Like open but method is enforced to GET.
[ "Like", "open", "but", "method", "is", "enforced", "to", "GET." ]
def get(self, *args, **kw): kw['method'] = 'GET' return self.open(*args, **kw)
['def', 'get(self,', '*args,', '**kw):', "kw['method']", '=', "'GET'", 'return', 'self.open(*args,', '**kw)']
161,470
rifqind/Agent-Programs-3KS1
entrypoints.py
EntryPoint.load
load
Load the object to which this entry point refers.
[ "Load", "the", "object", "to", "which", "this", "entry", "point", "refers." ]
def load(self): mod = import_module(self.module_name) obj = mod if self.object_name: for attr in self.object_name.split('.'): obj = getattr(obj, attr) return obj
['def', 'load(self):', 'mod', '=', 'import_module(self.module_name)', 'obj', '=', 'mod', 'if', 'self.object_name:', 'for', 'attr', 'in', "self.object_name.split('.'):", 'obj', '=', 'getattr(obj,', 'attr)', 'return', 'obj']
40,469
accel-brain/accel-brain-code
facade_yfinance.py
FacadeYFinance.load
load
Load and save histroical data into local csv file.
[ "Load", "and", "save", "histroical", "data", "into", "local", "csv", "file." ]
def load(self, target_ticker=None): if target_ticker is not None: self.__get_and_sleep([target_ticker]) else: df = pd.read_csv(self.__ticker_master_path) ticker_list = df.ticker.astype(str).values.tolist() self.__get_and_sleep(ticker_list)
['def', 'load(self,', 'target_ticker=None):', 'if', 'target_ticker', 'is', 'not', 'None:', 'self.__get_and_sleep([target_ticker])', 'else:', 'df', '=', 'pd.read_csv(self.__ticker_master_path)', 'ticker_list', '=', 'df.ticker.astype(str).values.tolist()', 'self.__get_and_sleep(ticker_list)']
7,084
scikit-learn/scikit-learn
test_stacking.py
test_stacking_classifier_base_regressor
test_stacking_classifier_base_regressor
Check that a regressor can be used as the first layer in `StackingClassifier`.
[ "Check", "that", "a", "regressor", "can", "be", "used", "as", "the", "first", "layer", "in", "`StackingClassifier`." ]
def test_stacking_classifier_base_regressor(): (X_train, X_test, y_train, y_test) = train_test_split(scale(X_iris), y_iris, stratify=y_iris, random_state=42) clf = StackingClassifier(estimators=[('ridge', Ridge())]) clf.fit(X_train, y_train) clf.predict(X_test) clf.predict_proba(X_test) assert c...
['def', 'test_stacking_classifier_base_regressor():', '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(scale(X_iris),', 'y_iris,', 'stratify=y_iris,', 'random_state=42)', 'clf', '=', "StackingClassifier(estimators=[('ridge',", 'Ridge())])', 'clf.fit(X_train,', 'y_train)', 'clf.predict(X_test)', 'cl...
853,199
Ruturaj123/Flowchart-Detection
ops.py
dropout
dropout
Returns a dropout layer applied to the input.
[ "Returns", "a", "dropout", "layer", "applied", "to", "the", "input." ]
def dropout(inputs, keep_prob=0.5, is_training=True, scope=None): if is_training and keep_prob > 0: with tf.name_scope(scope, 'Dropout', [inputs]): return tf.nn.dropout(inputs, keep_prob) else: return inputs
['def', 'dropout(inputs,', 'keep_prob=0.5,', 'is_training=True,', 'scope=None):', 'if', 'is_training', 'and', 'keep_prob', '>', '0:', 'with', 'tf.name_scope(scope,', "'Dropout',", '[inputs]):', 'return', 'tf.nn.dropout(inputs,', 'keep_prob)', 'else:', 'return', 'inputs']
585,732
deephyper/deephyper
_base_ensemble.py
BaseEnsemble.load
load
Load an ensemble from a save.
[ "Load", "an", "ensemble", "from", "a", "save." ]
def load(self, file: str) -> None: self.load_members_files(file)
['def', 'load(self,', 'file:', 'str)', '->', 'None:', 'self.load_members_files(file)']
520,784
rwth-i6/returnn
engine.py
Engine.init_train_epoch
init_train_epoch
Init for the current train epoch.
[ "Init", "for", "the", "current", "train", "epoch." ]
def init_train_epoch(self): if self.is_pretrain_epoch() or self.custom_get_net_dict: new_network_desc = self.get_net_dict_for_epoch(epoch=self.epoch) self._maybe_update_config(net_desc=new_network_desc, epoch=self.epoch) if self.need_init_new_network(new_network_desc): self.init_...
['def', 'init_train_epoch(self):', 'if', 'self.is_pretrain_epoch()', 'or', 'self.custom_get_net_dict:', 'new_network_desc', '=', 'self.get_net_dict_for_epoch(epoch=self.epoch)', 'self._maybe_update_config(net_desc=new_network_desc,', 'epoch=self.epoch)', 'if', 'self.need_init_new_network(new_network_desc):', 'self.init...
347,169
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
pixelda_losses.py
log_quaternion_loss_batch
log_quaternion_loss_batch
A helper function to compute the error between quaternions.
[ "A", "helper", "function", "to", "compute", "the", "error", "between", "quaternions." ]
def log_quaternion_loss_batch(predictions, labels, params): use_logging = params['use_logging'] assertions = [] if use_logging: assertions.append(tf.Assert(tf.reduce_all(tf.less(tf.abs(tf.reduce_sum(tf.square(predictions), [1]) - 1), 0.0001)), ['The l2 norm of each prediction quaternion vector shoul...
['def', 'log_quaternion_loss_batch(predictions,', 'labels,', 'params):', 'use_logging', '=', "params['use_logging']", 'assertions', '=', '[]', 'if', 'use_logging:', 'assertions.append(tf.Assert(tf.reduce_all(tf.less(tf.abs(tf.reduce_sum(tf.square(predictions),', '[1])', '-', '1),', '0.0001)),', "['The", 'l2', 'norm', '...
48,113
google-research/scenic
pileup_coverage_vit_config.py
get_config
get_config
Returns the ViT experiment configuration for SV classification.
[ "Returns", "the", "ViT", "experiment", "configuration", "for", "SV", "classification." ]
def get_config(runlocal=''): runlocal = bool(runlocal) config = ml_collections.ConfigDict() config.experiment_name = 'sv-vit' config.dataset_name = 'pileup_coverage' config.data_dtype_str = 'float32' config.dataset_configs = ml_collections.ConfigDict() (version, patch) = VARIANT.split('/') ...
['def', "get_config(runlocal=''):", 'runlocal', '=', 'bool(runlocal)', 'config', '=', 'ml_collections.ConfigDict()', 'config.experiment_name', '=', "'sv-vit'", 'config.dataset_name', '=', "'pileup_coverage'", 'config.data_dtype_str', '=', "'float32'", 'config.dataset_configs', '=', 'ml_collections.ConfigDict()', '(vers...
847,356
MycroftAI/mycroft-core
gui.py
SkillGUI.remote_url
remote_url
Returns configuration value for url of remote-server.
[ "Returns", "configuration", "value", "for", "url", "of", "remote-server." ]
def remote_url(self): return self.config.get('remote-server')
['def', 'remote_url(self):', 'return', "self.config.get('remote-server')"]
290,382
rudranil723/mini-main
__init__.py
UFOReader.getCharacterMapping
getCharacterMapping
Return a dictionary that maps unicode values (ints) to lists of glyph names.
[ "Return", "a", "dictionary", "that", "maps", "unicode", "values", "(ints)", "to", "lists", "of", "glyph", "names." ]
def getCharacterMapping(self, layerName=None, validate=None): if validate is None: validate = self._validate glyphSet = self.getGlyphSet(layerName, validateRead=validate, validateWrite=True) allUnicodes = glyphSet.getUnicodes() cmap = {} for (glyphName, unicodes) in allUnicodes.items(): ...
['def', 'getCharacterMapping(self,', 'layerName=None,', 'validate=None):', 'if', 'validate', 'is', 'None:', 'validate', '=', 'self._validate', 'glyphSet', '=', 'self.getGlyphSet(layerName,', 'validateRead=validate,', 'validateWrite=True)', 'allUnicodes', '=', 'glyphSet.getUnicodes()', 'cmap', '=', '{}', 'for', '(glyphN...
317,526
Ruturaj123/Flowchart-Detection
state_management.py
ChainingStateManager.initialize_graph
initialize_graph
Adds required operations to the graph.
[ "Adds", "required", "operations", "to", "the", "graph." ]
def initialize_graph(self, model, input_statistics=None): super(ChainingStateManager, self).initialize_graph(model=model, input_statistics=input_statistics) self._start_state = model.get_start_state() self._cached_states = math_utils.TupleOfTensorsLookup(key_dtype=dtypes.int64, default_values=self._start_st...
['def', 'initialize_graph(self,', 'model,', 'input_statistics=None):', 'super(ChainingStateManager,', 'self).initialize_graph(model=model,', 'input_statistics=input_statistics)', 'self._start_state', '=', 'model.get_start_state()', 'self._cached_states', '=', 'math_utils.TupleOfTensorsLookup(key_dtype=dtypes.int64,', '...
604,683
devashish-patel/webcam-motion-detector
decorators.py
onlyif_cmds_exist
onlyif_cmds_exist
Decorator to skip test when at least one of `commands` is not found.
[ "Decorator", "to", "skip", "test", "when", "at", "least", "one", "of", "`commands`", "is", "not", "found." ]
def onlyif_cmds_exist(*commands): for cmd in commands: if not which(cmd): return skip("This test runs only if command '{0}' is installed".format(cmd)) return null_deco
['def', 'onlyif_cmds_exist(*commands):', 'for', 'cmd', 'in', 'commands:', 'if', 'not', 'which(cmd):', 'return', 'skip("This', 'test', 'runs', 'only', 'if', 'command', "'{0}'", 'is', 'installed".format(cmd))', 'return', 'null_deco']
979,577
AIChallenger/AI_Challenger_2018
feature_extractor.py
extract_features
extract_features
Extracts features by the particular model_variant.
[ "Extracts", "features", "by", "the", "particular", "model_variant." ]
def extract_features(images, output_stride=8, multi_grid=None, depth_multiplier=1.0, final_endpoint=None, model_variant=None, weight_decay=0.0001, reuse=None, is_training=False, fine_tune_batch_norm=False, regularize_depthwise=False, preprocess_images=True, num_classes=None, global_pool=False): if 'resnet' in model...
['def', 'extract_features(images,', 'output_stride=8,', 'multi_grid=None,', 'depth_multiplier=1.0,', 'final_endpoint=None,', 'model_variant=None,', 'weight_decay=0.0001,', 'reuse=None,', 'is_training=False,', 'fine_tune_batch_norm=False,', 'regularize_depthwise=False,', 'preprocess_images=True,', 'num_classes=None,', '...
87,072
jshilong/SEPC
fsaf_head.py
iou_loss_tblr
iou_loss_tblr
Calculate the iou loss when both the prediction and targets are encoded in TBLR format.
[ "Calculate", "the", "iou", "loss", "when", "both", "the", "prediction", "and", "targets", "are", "encoded", "in", "TBLR", "format." ]
def iou_loss_tblr(pred, target, eps=1e-06): (xt, xb, xl, xr) = torch.split(pred, 1, dim=-1) (gt, gb, gl, gr) = torch.split(target, 1, dim=-1) X = (xt + xb) * (xl + xr) G = (gt + gb) * (gl + gr) Ih = torch.min(xt, gt) + torch.min(xb, gb) Iw = torch.min(xl, gl) + torch.min(xr, gr) In = Ih * Iw...
['def', 'iou_loss_tblr(pred,', 'target,', 'eps=1e-06):', '(xt,', 'xb,', 'xl,', 'xr)', '=', 'torch.split(pred,', '1,', 'dim=-1)', '(gt,', 'gb,', 'gl,', 'gr)', '=', 'torch.split(target,', '1,', 'dim=-1)', 'X', '=', '(xt', '+', 'xb)', '*', '(xl', '+', 'xr)', 'G', '=', '(gt', '+', 'gb)', '*', '(gl', '+', 'gr)', 'Ih', '=', ...
876,285
mattchorlian/Berkeley-CS188-Spring21
agents.py
TrivialVacuumEnvironment.percept
percept
Returns the agent's location, and the location status (Dirty/Clean).
[ "Returns", "the", "agent's", "location,", "and", "the", "location", "status", "(Dirty/Clean)." ]
def percept(self, agent): return (agent.location, self.status[agent.location])
['def', 'percept(self,', 'agent):', 'return', '(agent.location,', 'self.status[agent.location])']
106,509
rudranil723/mini-main
makemigrations.py
Command.write_migration_files
write_migration_files
Take a changes dict and write them out as migration files.
[ "Take", "a", "changes", "dict", "and", "write", "them", "out", "as", "migration", "files." ]
def write_migration_files(self, changes): directory_created = {} for (app_label, app_migrations) in changes.items(): if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label) + '\n') for migration in app_migrations: writer = ...
['def', 'write_migration_files(self,', 'changes):', 'directory_created', '=', '{}', 'for', '(app_label,', 'app_migrations)', 'in', 'changes.items():', 'if', 'self.verbosity', '>=', '1:', 'self.stdout.write(self.style.MIGRATE_HEADING("Migrations', 'for', '\'%s\':"', '%', 'app_label)', '+', "'\\n')", 'for', 'migration', ...
315,645
matsu0228/nlp-jp
base.py
Node.insertText
insertText
Insert data as text in the current node, positioned before the start of node insertBefore or to the end of the node's text.
[ "Insert", "data", "as", "text", "in", "the", "current", "node,", "positioned", "before", "the", "start", "of", "node", "insertBefore", "or", "to", "the", "end", "of", "the", "node's", "text." ]
def insertText(self, data, insertBefore=None): raise NotImplementedError
['def', 'insertText(self,', 'data,', 'insertBefore=None):', 'raise', 'NotImplementedError']
803,716
aasimkhan0207/computer_vision
test_solver.py
TestSolver.test_net_memory
test_net_memory
Check that nets survive after the solver is destroyed.
[ "Check", "that", "nets", "survive", "after", "the", "solver", "is", "destroyed." ]
def test_net_memory(self): nets = [self.solver.net] + list(self.solver.test_nets) self.assertEqual(len(nets), 2) del self.solver total = 0 for net in nets: for ps in net.params.itervalues(): for p in ps: total += p.data.sum() + p.diff.sum() for bl in net.b...
['def', 'test_net_memory(self):', 'nets', '=', '[self.solver.net]', '+', 'list(self.solver.test_nets)', 'self.assertEqual(len(nets),', '2)', 'del', 'self.solver', 'total', '=', '0', 'for', 'net', 'in', 'nets:', 'for', 'ps', 'in', 'net.params.itervalues():', 'for', 'p', 'in', 'ps:', 'total', '+=', 'p.data.sum()', '+', '...
472,839
matsu0228/nlp-jp
traitlets.py
HasTraits.trait_names
trait_names
Get a list of all the names of this class' traits.
[ "Get", "a", "list", "of", "all", "the", "names", "of", "this", "class'", "traits." ]
def trait_names(self, **metadata): return list(self.traits(**metadata))
['def', 'trait_names(self,', '**metadata):', 'return', 'list(self.traits(**metadata))']
807,562
openml-labs/gama
test_ea_crossover.py
test_crossover_max_length
test_crossover_max_length
Setting `max_length` affects only maximum produced length.
[ "Setting", "`max_length`", "affects", "only", "maximum", "produced", "length." ]
def test_crossover_max_length(SS_RBS_SS_BNB): primitives_in_parent = len(SS_RBS_SS_BNB.primitives) produced_lengths = [] for _ in range(60): (ind1, ind2) = random_crossover(SS_RBS_SS_BNB.copy_as_new(), SS_RBS_SS_BNB.copy_as_new(), max_length=primitives_in_parent) produced_lengths.append(len(...
['def', 'test_crossover_max_length(SS_RBS_SS_BNB):', 'primitives_in_parent', '=', 'len(SS_RBS_SS_BNB.primitives)', 'produced_lengths', '=', '[]', 'for', '_', 'in', 'range(60):', '(ind1,', 'ind2)', '=', 'random_crossover(SS_RBS_SS_BNB.copy_as_new(),', 'SS_RBS_SS_BNB.copy_as_new(),', 'max_length=primitives_in_parent)', '...
566,232
Ruturaj123/Flowchart-Detection
sdca_estimator.py
_SdcaUpdateWeightsHook.before_run
before_run
Return the update_weights op so that it is executed during this run.
[ "Return", "the", "update_weights", "op", "so", "that", "it", "is", "executed", "during", "this", "run." ]
def before_run(self, run_context): return session_run_hook.SessionRunArgs(self._update_op)
['def', 'before_run(self,', 'run_context):', 'return', 'session_run_hook.SessionRunArgs(self._update_op)']
604,249
gletarte/dichotomize-and-generalize
utils.py
get_logging_dir_name
get_logging_dir_name
Map experiment config dictionnary to a unique directory name.
[ "Map", "experiment", "config", "dictionnary", "to", "a", "unique", "directory", "name." ]
def get_logging_dir_name(experiment_setting): return f"{experiment_setting['network']}_H{experiment_setting['hidden_layers']}-{experiment_setting['hidden_size']}" + f"_B{experiment_setting['batch_size']}_{experiment_setting['optim_algo']}_WD{experiment_setting['weight_decay']}" + f"_LR{experiment_setting['learning_...
['def', 'get_logging_dir_name(experiment_setting):', 'return', 'f"{experiment_setting[\'network\']}_H{experiment_setting[\'hidden_layers\']}-{experiment_setting[\'hidden_size\']}"', '+', 'f"_B{experiment_setting[\'batch_size\']}_{experiment_setting[\'optim_algo\']}_WD{experiment_setting[\'weight_decay\']}"', '+', 'f"_L...
550,317
Ruturaj123/Flowchart-Detection
gmm.py
GMM.weights
weights
Returns the cluster weights.
[ "Returns", "the", "cluster", "weights." ]
def weights(self): return checkpoint_utils.load_variable(self.model_dir, gmm_ops.GmmAlgorithm.CLUSTERS_WEIGHT)
['def', 'weights(self):', 'return', 'checkpoint_utils.load_variable(self.model_dir,', 'gmm_ops.GmmAlgorithm.CLUSTERS_WEIGHT)']
603,004
frgfm/Holocron
yolov4.py
YoloLayer.forward
forward
Perform detection on an image tensor and returns either the loss dictionary in training mode or the list of detections in eval mode.
[ "Perform", "detection", "on", "an", "image", "tensor", "and", "returns", "either", "the", "loss", "dictionary", "in", "training", "mode", "or", "the", "list", "of", "detections", "in", "eval", "mode." ]
def forward(self, x: Tensor, target: Optional[List[Dict[str, Tensor]]]=None) -> Union[Dict[str, Tensor], List[Dict[str, Tensor]]]: if self.training and target is None: raise ValueError('`target` needs to be specified in training mode') (pred_boxes, b_o, b_scores) = self._format_outputs(x) if self.tr...
['def', 'forward(self,', 'x:', 'Tensor,', 'target:', 'Optional[List[Dict[str,', 'Tensor]]]=None)', '->', 'Union[Dict[str,', 'Tensor],', 'List[Dict[str,', 'Tensor]]]:', 'if', 'self.training', 'and', 'target', 'is', 'None:', 'raise', "ValueError('`target`", 'needs', 'to', 'be', 'specified', 'in', 'training', "mode')", '(...
570,043
open-mmlab/mmdetection3d
mvx_two_stage.py
MVXTwoStageDetector.with_fusion
with_fusion
bool: Whether the detector has a fusion layer.
[ "bool:", "Whether", "the", "detector", "has", "a", "fusion", "layer." ]
def with_fusion(self): return hasattr(self, 'pts_fusion_layer') and self.fusion_layer is not None
['def', 'with_fusion(self):', 'return', 'hasattr(self,', "'pts_fusion_layer')", 'and', 'self.fusion_layer', 'is', 'not', 'None']
632,004
AlperHuseyn/artificial-intelligence-and-machine-learning-with-python
batchVec_IMDB.py
train_evaluate_save_model
train_evaluate_save_model
Train, evaluate, and save the IMDB review-sentiment prediction model.
[ "Train,", "evaluate,", "and", "save", "the", "IMDB", "review-sentiment", "prediction", "model." ]
def train_evaluate_save_model(X_train, y_train, X_valid, y_valid, X_test, y_test, num_categories, vectorizer, X_to_predict, batch_size=32, name='model', epochs=5): model = create_IMDB_model(input_dim=len(vectorizer.vocabulary_), num_categories=num_categories, name='IMDB-review-sentiment') train_data_generator =...
['def', 'train_evaluate_save_model(X_train,', 'y_train,', 'X_valid,', 'y_valid,', 'X_test,', 'y_test,', 'num_categories,', 'vectorizer,', 'X_to_predict,', 'batch_size=32,', "name='model',", 'epochs=5):', 'model', '=', 'create_IMDB_model(input_dim=len(vectorizer.vocabulary_),', 'num_categories=num_categories,', "name='I...
36,147
thaines/helit
pruners.py
Pruner.clone
clone
Returns a copy of this object.
[ "Returns", "a", "copy", "of", "this", "object." ]
def clone(self): raise NotImplementedError
['def', 'clone(self):', 'raise', 'NotImplementedError']
591,336
PacktPublishing/Hands-On-Artificial--for-Banking
categorical.py
Categorical.describe
describe
Describes this Categorical Returns ------- description: `DataFrame` A dataframe with frequency and counts by category.
[ "Describes", "this", "Categorical", "Returns", "-------", "description:", "`DataFrame`", "A", "dataframe", "with", "frequency", "and", "counts", "by", "category." ]
def describe(self): counts = self.value_counts(dropna=False) freqs = counts / float(counts.sum()) from pandas.core.reshape.concat import concat result = concat([counts, freqs], axis=1) result.columns = ['counts', 'freqs'] result.index.name = 'categories' return result
['def', 'describe(self):', 'counts', '=', 'self.value_counts(dropna=False)', 'freqs', '=', 'counts', '/', 'float(counts.sum())', 'from', 'pandas.core.reshape.concat', 'import', 'concat', 'result', '=', 'concat([counts,', 'freqs],', 'axis=1)', 'result.columns', '=', "['counts',", "'freqs']", 'result.index.name', '=', "'...
236,293
tensorflow/quantum
benchmark_op_gradients.py
GradientBenchmarks.benchmark_parameter_shift
benchmark_parameter_shift
Benchmark the parameter shift gradient method.
[ "Benchmark", "the", "parameter", "shift", "gradient", "method." ]
def benchmark_parameter_shift(self): diff = parameter_shift.ParameterShift() self._benchmark_tfq_differentiator(diff, self.params)
['def', 'benchmark_parameter_shift(self):', 'diff', '=', 'parameter_shift.ParameterShift()', 'self._benchmark_tfq_differentiator(diff,', 'self.params)']
834,545
Kvatsx/Artificial-Intelligence-Assignments
utils.py
unite
unite
Turns a two dimensional array into a one dimensional.
[ "Turns", "a", "two", "dimensional", "array", "into", "a", "one", "dimensional." ]
def unite(iterable): return set((typ for types in iterable for typ in types))
['def', 'unite(iterable):', 'return', 'set((typ', 'for', 'types', 'in', 'iterable', 'for', 'typ', 'in', 'types))']
39,130
nilearn/nilearn
conftest.py
shape_4d_default
shape_4d_default
Return default shape for a 4D image.
[ "Return", "default", "shape", "for", "a", "4D", "image." ]
def shape_4d_default(): return _shape_4d_default()
['def', 'shape_4d_default():', 'return', '_shape_4d_default()']
723,622
Kvatsx/Artificial-Intelligence-Assignments
test_markdown.py
TestMarkdown.test_markdown2html_math_mixed
test_markdown2html_math_mixed
ensure markdown between inline and inline-block math works and test multiple LaTeX markup syntaxes.
[ "ensure", "markdown", "between", "inline", "and", "inline-block", "math", "works", "and", "test", "multiple", "LaTeX", "markup", "syntaxes." ]
def test_markdown2html_math_mixed(self): case = 'The entries of \\\\(C\\\\) are given by the exact formula:\n$$\nC_{ik} = \\sum_{j=1}^n A_{ij} B_{jk},\n$$\nbut you can _implement_ this computation in many ways.\n$\x07pprox 2mnp$ flops are needed for \\\\[ C_{ik} = \\sum_{j=1}^n A_{ij} B_{jk} \\\\].\nAlso check empt...
['def', 'test_markdown2html_math_mixed(self):', 'case', '=', "'The", 'entries', 'of', '\\\\\\\\(C\\\\\\\\)', 'are', 'given', 'by', 'the', 'exact', 'formula:\\n$$\\nC_{ik}', '=', '\\\\sum_{j=1}^n', 'A_{ij}', 'B_{jk},\\n$$\\nbut', 'you', 'can', '_implement_', 'this', 'computation', 'in', 'many', 'ways.\\n$\\x07pprox', '2...
1,782
myothida/Supervised-Machine-Learning
test_affinity_propagation.py
test_affinity_propagation
test_affinity_propagation
Test consistency of the affinity propagations.
[ "Test", "consistency", "of", "the", "affinity", "propagations." ]
def test_affinity_propagation(global_random_seed, global_dtype): S = -euclidean_distances(X.astype(global_dtype, copy=False), squared=True) preference = np.median(S) * 10 (cluster_centers_indices, labels) = affinity_propagation(S, preference=preference, random_state=global_random_seed) n_clusters_ = len...
['def', 'test_affinity_propagation(global_random_seed,', 'global_dtype):', 'S', '=', '-euclidean_distances(X.astype(global_dtype,', 'copy=False),', 'squared=True)', 'preference', '=', 'np.median(S)', '*', '10', '(cluster_centers_indices,', 'labels)', '=', 'affinity_propagation(S,', 'preference=preference,', 'random_sta...
363,486
open-mmlab/mmdetection3d
loading.py
LoadMultiViewImageFromFiles.transform
transform
Call function to load multi-view image from files.
[ "Call", "function", "to", "load", "multi-view", "image", "from", "files." ]
def transform(self, results: dict) -> Optional[dict]: if self.num_ref_frames > 0: init_choice = np.array([0], dtype=np.int64) num_frames = len(results['img_filename']) // self.num_views - 1 if num_frames == 0: choices = np.random.choice(1, self.num_ref_frames, replace=True) ...
['def', 'transform(self,', 'results:', 'dict)', '->', 'Optional[dict]:', 'if', 'self.num_ref_frames', '>', '0:', 'init_choice', '=', 'np.array([0],', 'dtype=np.int64)', 'num_frames', '=', "len(results['img_filename'])", '//', 'self.num_views', '-', '1', 'if', 'num_frames', '==', '0:', 'choices', '=', 'np.random.choice(...
631,710
xiaoaleiBLUE/computer_vision
config_util_test.py
ConfigUtilTest.test_create_pipeline_proto_from_configs
test_create_pipeline_proto_from_configs
Tests that proto can be reconstructed from configs dictionary.
[ "Tests", "that", "proto", "can", "be", "reconstructed", "from", "configs", "dictionary." ]
def test_create_pipeline_proto_from_configs(self): pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config') pipeline_config = pipeline_pb2.TrainEvalPipelineConfig() pipeline_config.model.faster_rcnn.num_classes = 10 pipeline_config.train_config.batch_size = 32 pipeline_config.trai...
['def', 'test_create_pipeline_proto_from_configs(self):', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.model.faster_rcnn.num_classes', '=', '10', 'pipeline_config.train_config.batch_size', '=', ...
512,388
rifqind/Agent-Programs-3KS1
pretty.py
PrettyPrinter.flush
flush
Flush data that is left in the buffer.
[ "Flush", "data", "that", "is", "left", "in", "the", "buffer." ]
def flush(self): for data in self.buffer: self.output_width += data.output(self.output, self.output_width) self.buffer.clear() self.buffer_width = 0
['def', 'flush(self):', 'for', 'data', 'in', 'self.buffer:', 'self.output_width', '+=', 'data.output(self.output,', 'self.output_width)', 'self.buffer.clear()', 'self.buffer_width', '=', '0']
41,657
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
predict_test.py
full_batch_norm
full_batch_norm
Batch normalization on convolutional maps.
[ "Batch", "normalization", "on", "convolutional", "maps." ]
def full_batch_norm(x, n_out, phase_train, scope='bn'): with tf.variable_scope(scope): beta = tf.Variable(tf.constant(0.0, shape=[n_out]), name='beta', trainable=True) gamma = tf.Variable(tf.constant(1.0, shape=[n_out]), name='gamma', trainable=True) (batch_mean, batch_var) = tf.nn.moments(x...
['def', 'full_batch_norm(x,', 'n_out,', 'phase_train,', "scope='bn'):", 'with', 'tf.variable_scope(scope):', 'beta', '=', 'tf.Variable(tf.constant(0.0,', 'shape=[n_out]),', "name='beta',", 'trainable=True)', 'gamma', '=', 'tf.Variable(tf.constant(1.0,', 'shape=[n_out]),', "name='gamma',", 'trainable=True)', '(batch_mea...
432,985
matsu0228/nlp-jp
filters.py
do_mark_safe
do_mark_safe
Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
[ "Mark", "the", "value", "as", "safe", "which", "means", "that", "in", "an", "environment", "with", "automatic", "escaping", "enabled", "this", "variable", "will", "not", "be", "escaped." ]
def do_mark_safe(value): return Markup(value)
['def', 'do_mark_safe(value):', 'return', 'Markup(value)']
787,877
cuiziteng/ICCV_MAET
ga_retina_head.py
GARetinaHead.init_weights
init_weights
Initialize weights of the layer.
[ "Initialize", "weights", "of", "the", "layer." ]
def init_weights(self): for m in self.cls_convs: normal_init(m.conv, std=0.01) for m in self.reg_convs: normal_init(m.conv, std=0.01) self.feature_adaption_cls.init_weights() self.feature_adaption_reg.init_weights() bias_cls = bias_init_with_prob(0.01) normal_init(self.conv_loc, ...
['def', 'init_weights(self):', 'for', 'm', 'in', 'self.cls_convs:', 'normal_init(m.conv,', 'std=0.01)', 'for', 'm', 'in', 'self.reg_convs:', 'normal_init(m.conv,', 'std=0.01)', 'self.feature_adaption_cls.init_weights()', 'self.feature_adaption_reg.init_weights()', 'bias_cls', '=', 'bias_init_with_prob(0.01)', 'normal_i...
228,604
43Carrig/recurrent_neural_networks_practice
session_ops.py
TensorHandle.handle
handle
The string representation of this handle.
[ "The", "string", "representation", "of", "this", "handle." ]
def handle(self): return self._handle
['def', 'handle(self):', 'return', 'self._handle']
338,957
octree-nn/ocnn-pytorch
octree.py
Octree.construct_neigh
construct_neigh
Constructs the :obj:`3x3x3` neighbors for each octree node.
[ "Constructs", "the", ":obj:`3x3x3`", "neighbors", "for", "each", "octree", "node." ]
def construct_neigh(self, depth: int): if depth <= self.full_depth: nnum = 1 << 3 * depth key = torch.arange(nnum, dtype=torch.long, device=self.device) (x, y, z, _) = key2xyz(key, depth) xyz = torch.stack([x, y, z], dim=-1) grid = self.rng_grid(min=-1, max=1) xyz = x...
['def', 'construct_neigh(self,', 'depth:', 'int):', 'if', 'depth', '<=', 'self.full_depth:', 'nnum', '=', '1', '<<', '3', '*', 'depth', 'key', '=', 'torch.arange(nnum,', 'dtype=torch.long,', 'device=self.device)', '(x,', 'y,', 'z,', '_)', '=', 'key2xyz(key,', 'depth)', 'xyz', '=', 'torch.stack([x,', 'y,', 'z],', 'dim=-...
249,935
Kvatsx/Artificial-Intelligence-Assignments
ptyprocess.py
PtyProcess.getwinsize
getwinsize
Return the window size of the pseudoterminal as a tuple (rows, cols).
[ "Return", "the", "window", "size", "of", "the", "pseudoterminal", "as", "a", "tuple", "(rows,", "cols)." ]
def getwinsize(self): TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912) s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(self.fd, TIOCGWINSZ, s) return struct.unpack('HHHH', x)[0:2]
['def', 'getwinsize(self):', 'TIOCGWINSZ', '=', 'getattr(termios,', "'TIOCGWINSZ',", '1074295912)', 's', '=', "struct.pack('HHHH',", '0,', '0,', '0,', '0)', 'x', '=', 'fcntl.ioctl(self.fd,', 'TIOCGWINSZ,', 's)', 'return', "struct.unpack('HHHH',", 'x)[0:2]']
76,173
google-research/tensor2robot
resnet.py
get_resnet50_spatial
get_resnet50_spatial
ResNet50, but cut off last block and return before global pooling.
[ "ResNet50,", "but", "cut", "off", "last", "block", "and", "return", "before", "global", "pooling." ]
def get_resnet50_spatial(images, is_training): num_classes = 1001 model = resnet_lib.Model(resnet_size=50, bottleneck=True, num_classes=num_classes, num_filters=64, kernel_size=7, conv_stride=2, first_pool_size=3, first_pool_stride=2, block_sizes=[3, 4, 6], block_strides=[1, 2, 2], resnet_version=resnet_lib.DEF...
['def', 'get_resnet50_spatial(images,', 'is_training):', 'num_classes', '=', '1001', 'model', '=', 'resnet_lib.Model(resnet_size=50,', 'bottleneck=True,', 'num_classes=num_classes,', 'num_filters=64,', 'kernel_size=7,', 'conv_stride=2,', 'first_pool_size=3,', 'first_pool_stride=2,', 'block_sizes=[3,', '4,', '6],', 'blo...
908,377
Farama-Foundation/Gymnasium
test_vector_env.py
test_vector_env_equal
test_vector_env_equal
Test that vector environment are equal for both async and sync variants.
[ "Test", "that", "vector", "environment", "are", "equal", "for", "both", "async", "and", "sync", "variants." ]
def test_vector_env_equal(shared_memory): env_fns = [make_env('CartPole-v1', i) for i in range(4)] num_steps = 100 async_env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) sync_env = SyncVectorEnv(env_fns) assert async_env.num_envs == sync_env.num_envs assert async_env.observation_space ...
['def', 'test_vector_env_equal(shared_memory):', 'env_fns', '=', "[make_env('CartPole-v1',", 'i)', 'for', 'i', 'in', 'range(4)]', 'num_steps', '=', '100', 'async_env', '=', 'AsyncVectorEnv(env_fns,', 'shared_memory=shared_memory)', 'sync_env', '=', 'SyncVectorEnv(env_fns)', 'assert', 'async_env.num_envs', '==', 'sync_e...
573,544
opendilab/DI-star
actions.py
raw_cmd_pt
raw_cmd_pt
Do a raw command to another unit towards a point.
[ "Do", "a", "raw", "command", "to", "another", "unit", "towards", "a", "point." ]
def raw_cmd_pt(action, ability_id, queued, unit_tags, world): action_cmd = action.action_raw.unit_command action_cmd.ability_id = ability_id action_cmd.queue_command = queued if not isinstance(unit_tags, (tuple, list)): unit_tags = [unit_tags] action_cmd.unit_tags.extend(unit_tags) world...
['def', 'raw_cmd_pt(action,', 'ability_id,', 'queued,', 'unit_tags,', 'world):', 'action_cmd', '=', 'action.action_raw.unit_command', 'action_cmd.ability_id', '=', 'ability_id', 'action_cmd.queue_command', '=', 'queued', 'if', 'not', 'isinstance(unit_tags,', '(tuple,', 'list)):', 'unit_tags', '=', '[unit_tags]', 'actio...
184,664
dguo98/DiffPruning
modeling_auto.py
AutoModelForQuestionAnswering.from_config
from_config
Instantiates one of the base model classes of the library from a configuration.
[ "Instantiates", "one", "of", "the", "base", "model", "classes", "of", "the", "library", "from", "a", "configuration." ]
def from_config(cls, config): for (config_class, model_class) in MODEL_FOR_QUESTION_ANSWERING_MAPPING.items(): if isinstance(config, config_class): return model_class(config) raise ValueError('Unrecognized configuration class {} for this kind of AutoModel: {}.\nModel type should be one of {}...
['def', 'from_config(cls,', 'config):', 'for', '(config_class,', 'model_class)', 'in', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING.items():', 'if', 'isinstance(config,', 'config_class):', 'return', 'model_class(config)', 'raise', "ValueError('Unrecognized", 'configuration', 'class', '{}', 'for', 'this', 'kind', 'of', 'AutoMo...
550,541
gatapia/py_ml_utils
ast_parser.py
StrNodeVisitor.args
args
convenience function called from visit_Call.
[ "convenience", "function", "called", "from", "visit_Call." ]
def args(self, args): visit = self.visit return [visit(n) for n in args]
['def', 'args(self,', 'args):', 'visit', '=', 'self.visit', 'return', '[visit(n)', 'for', 'n', 'in', 'args]']
302,655
Trusted-AI/AIF360
reweighing.py
ReweighingMeta.score
score
Returns the output of the estimator's score function on the given test data and labels.
[ "Returns", "the", "output", "of", "the", "estimator's", "score", "function", "on", "the", "given", "test", "data", "and", "labels." ]
def score(self, X, y, sample_weight=None): return self.estimator_.score(X, y, sample_weight=sample_weight)
['def', 'score(self,', 'X,', 'y,', 'sample_weight=None):', 'return', 'self.estimator_.score(X,', 'y,', 'sample_weight=sample_weight)']
412,473
facebookresearch/mtenv
noxfile.py
get_supported_envsetups
get_supported_envsetups
Get the list of EnvSetups that can run in a given session.
[ "Get", "the", "list", "of", "EnvSetups", "that", "can", "run", "in", "a", "given", "session." ]
def get_supported_envsetups(session: Session) -> List[EnvSetup]: return [env_setup for env_setup in get_all_envsetups(session=session) if session.python in env_setup.supported_python_versions]
['def', 'get_supported_envsetups(session:', 'Session)', '->', 'List[EnvSetup]:', 'return', '[env_setup', 'for', 'env_setup', 'in', 'get_all_envsetups(session=session)', 'if', 'session.python', 'in', 'env_setup.supported_python_versions]']
642,656
rudranil723/mini-main
DateTime.py
DateTime.pDay
pDay
Return the abbreviated (with period) name of the day of the week.
[ "Return", "the", "abbreviated", "(with", "period)", "name", "of", "the", "day", "of", "the", "week." ]
def pDay(self): return self._pday
['def', 'pDay(self):', 'return', 'self._pday']
314,563
arshpreetsingh/quantopian-machinelearning
interactiveshell.py
InteractiveShell.show_usage_error
show_usage_error
Show a short message for UsageErrors These are special exceptions that shouldn't show a traceback.
[ "Show", "a", "short", "message", "for", "UsageErrors", "These", "are", "special", "exceptions", "that", "shouldn't", "show", "a", "traceback." ]
def show_usage_error(self, exc): print('UsageError: %s' % exc, file=sys.stderr)
['def', 'show_usage_error(self,', 'exc):', "print('UsageError:", "%s'", '%', 'exc,', 'file=sys.stderr)']
886,321
Eric3911/OpenAGI
token_classifier.py
TokenClassifier.forward
forward
Performs the forward step of the module.
[ "Performs", "the", "forward", "step", "of", "the", "module." ]
def forward(self, hidden_states): hidden_states = self.dropout(hidden_states) logits = self.mlp(hidden_states) return logits
['def', 'forward(self,', 'hidden_states):', 'hidden_states', '=', 'self.dropout(hidden_states)', 'logits', '=', 'self.mlp(hidden_states)', 'return', 'logits']
273,745
TrellixVulnTeam/Unsupervised_Learning_HFI7
checkpoints.py
Checkpoints.rename_all_checkpoints
rename_all_checkpoints
Rename all checkpoints for old_path to new_path.
[ "Rename", "all", "checkpoints", "for", "old_path", "to", "new_path." ]
def rename_all_checkpoints(self, old_path, new_path): for cp in self.list_checkpoints(old_path): self.rename_checkpoint(cp['id'], old_path, new_path)
['def', 'rename_all_checkpoints(self,', 'old_path,', 'new_path):', 'for', 'cp', 'in', 'self.list_checkpoints(old_path):', "self.rename_checkpoint(cp['id'],", 'old_path,', 'new_path)']
452,218
ludwig-ai/ludwig
sequence_decoders.py
SequenceGeneratorDecoder.forward
forward
Decodes combiner_outputs into a sequence.
[ "Decodes", "combiner_outputs", "into", "a", "sequence." ]
def forward(self, combiner_outputs: Dict[str, torch.Tensor], target: torch.Tensor=None) -> Dict[str, torch.Tensor]: logits = self.rnn_decoder(combiner_outputs, target) return {LOGITS: logits}
['def', 'forward(self,', 'combiner_outputs:', 'Dict[str,', 'torch.Tensor],', 'target:', 'torch.Tensor=None)', '->', 'Dict[str,', 'torch.Tensor]:', 'logits', '=', 'self.rnn_decoder(combiner_outputs,', 'target)', 'return', '{LOGITS:', 'logits}']
616,720
TrellixVulnTeam/Unsupervised_Learning_HFI7
named_commands.py
beginning_of_line
beginning_of_line
Move to the start of the current line.
[ "Move", "to", "the", "start", "of", "the", "current", "line." ]
def beginning_of_line(event: E) -> None: buff = event.current_buffer buff.cursor_position += buff.document.get_start_of_line_position(after_whitespace=False)
['def', 'beginning_of_line(event:', 'E)', '->', 'None:', 'buff', '=', 'event.current_buffer', 'buff.cursor_position', '+=', 'buff.document.get_start_of_line_position(after_whitespace=False)']
435,230
thu-ml/tianshou
atari_network.py
Rainbow.forward
forward
Mapping: x -> Z(x, \*).
[ "Mapping:", "x", "->", "Z(x,", "\\*)." ]
def forward(self, obs: Union[np.ndarray, torch.Tensor], state: Optional[Any]=None, info: Optional[dict[str, Any]]=None) -> tuple[torch.Tensor, Any]: if info is None: info = {} (obs, state) = super().forward(obs) q = self.Q(obs) q = q.view(-1, self.action_num, self.num_atoms) if self._is_duel...
['def', 'forward(self,', 'obs:', 'Union[np.ndarray,', 'torch.Tensor],', 'state:', 'Optional[Any]=None,', 'info:', 'Optional[dict[str,', 'Any]]=None)', '->', 'tuple[torch.Tensor,', 'Any]:', 'if', 'info', 'is', 'None:', 'info', '=', '{}', '(obs,', 'state)', '=', 'super().forward(obs)', 'q', '=', 'self.Q(obs)', 'q', '=', ...
355,167
vertical-knowledge/ripozo
siren.py
TestSirenAdapter.test_generate_field_for_endpoint_func_url_params
test_generate_field_for_endpoint_func_url_params
Tests that url params are not a part of the fields returned.
[ "Tests", "that", "url", "params", "are", "not", "a", "part", "of", "the", "fields", "returned." ]
def test_generate_field_for_endpoint_func_url_params(self): fields_method = mock.Mock(return_value=[mock.Mock(arg_type=input_categories.URL_PARAMS)]) endpoint_func = mock.Mock(fields=fields_method) adapter = SirenAdapter(mock.MagicMock()) fields_found = adapter.generate_fields_for_endpoint_funct(endpoin...
['def', 'test_generate_field_for_endpoint_func_url_params(self):', 'fields_method', '=', 'mock.Mock(return_value=[mock.Mock(arg_type=input_categories.URL_PARAMS)])', 'endpoint_func', '=', 'mock.Mock(fields=fields_method)', 'adapter', '=', 'SirenAdapter(mock.MagicMock())', 'fields_found', '=', 'adapter.generate_fields_f...
349,218
weimin17/Object-Detection_HelmetDetection
minigo.py
bootstrap
bootstrap
Initialize the model with random weights.
[ "Initialize", "the", "model", "with", "random", "weights." ]
def bootstrap(estimator_model_dir, trained_models_dir, params): bootstrap_name = utils.generate_model_name(0) _ensure_dir_exists(trained_models_dir) bootstrap_model_path = os.path.join(trained_models_dir, bootstrap_name) _ensure_dir_exists(estimator_model_dir) print('Bootstrapping with working dir {...
['def', 'bootstrap(estimator_model_dir,', 'trained_models_dir,', 'params):', 'bootstrap_name', '=', 'utils.generate_model_name(0)', '_ensure_dir_exists(trained_models_dir)', 'bootstrap_model_path', '=', 'os.path.join(trained_models_dir,', 'bootstrap_name)', '_ensure_dir_exists(estimator_model_dir)', "print('Bootstrappi...
758,167
SALT-NLP/Adaptive-Compositional-Modules
training_args.py
TrainingArguments.to_dict
to_dict
Serializes this instance while replace `Enum` by their values (for JSON serialization support).
[ "Serializes", "this", "instance", "while", "replace", "`Enum`", "by", "their", "values", "(for", "JSON", "serialization", "support)." ]
def to_dict(self): d = asdict(self) for (k, v) in d.items(): if isinstance(v, Enum): d[k] = v.value if isinstance(v, list) and len(v) > 0 and isinstance(v[0], Enum): d[k] = [x.value for x in v] return d
['def', 'to_dict(self):', 'd', '=', 'asdict(self)', 'for', '(k,', 'v)', 'in', 'd.items():', 'if', 'isinstance(v,', 'Enum):', 'd[k]', '=', 'v.value', 'if', 'isinstance(v,', 'list)', 'and', 'len(v)', '>', '0', 'and', 'isinstance(v[0],', 'Enum):', 'd[k]', '=', '[x.value', 'for', 'x', 'in', 'v]', 'return', 'd']
408,458
zihuitang/medical_AI_platform
test_zipfile.py
AbstractBadCrcTests.test_read_with_bad_crc
test_read_with_bad_crc
Tests that files with bad CRCs raise a BadZipFile exception when read.
[ "Tests", "that", "files", "with", "bad", "CRCs", "raise", "a", "BadZipFile", "exception", "when", "read." ]
def test_read_with_bad_crc(self): zipdata = self.zip_with_bad_crc with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf: self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile') with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf: with zipf.open('afile', 'r') as corrupt_file: ...
['def', 'test_read_with_bad_crc(self):', 'zipdata', '=', 'self.zip_with_bad_crc', 'with', 'zipfile.ZipFile(io.BytesIO(zipdata),', "mode='r')", 'as', 'zipf:', 'self.assertRaises(zipfile.BadZipFile,', 'zipf.read,', "'afile')", 'with', 'zipfile.ZipFile(io.BytesIO(zipdata),', "mode='r')", 'as', 'zipf:', 'with', "zipf.open(...
283,764
devashish-patel/webcam-motion-detector
console_widget.py
ConsoleWidget.cut
cut
Copy the currently selected text to the clipboard and delete it if it's inside the input buffer.
[ "Copy", "the", "currently", "selected", "text", "to", "the", "clipboard", "and", "delete", "it", "if", "it's", "inside", "the", "input", "buffer." ]
def cut(self): self.copy() if self.can_cut(): self._control.textCursor().removeSelectedText()
['def', 'cut(self):', 'self.copy()', 'if', 'self.can_cut():', 'self._control.textCursor().removeSelectedText()']
984,406
ylsung/Ladder-Side-Tuning
pruning_methods_test.py
round_pruning_amount
round_pruning_amount
round the parameter amount after pruning to an integer multiple of `round_to`.
[ "round", "the", "parameter", "amount", "after", "pruning", "to", "an", "integer", "multiple", "of", "`round_to`." ]
def round_pruning_amount(total_parameters, n_to_prune, round_to): n_remain = round_to * max(int(total_parameters - n_to_prune) // round_to, 1) return max(total_parameters - n_remain, 0)
['def', 'round_pruning_amount(total_parameters,', 'n_to_prune,', 'round_to):', 'n_remain', '=', 'round_to', '*', 'max(int(total_parameters', '-', 'n_to_prune)', '//', 'round_to,', '1)', 'return', 'max(total_parameters', '-', 'n_remain,', '0)']
623,168
ivanmontero/autobot
pipelines.py
Pipeline.save_pretrained
save_pretrained
Save the pipeline's model and tokenizer.
[ "Save", "the", "pipeline's", "model", "and", "tokenizer." ]
def save_pretrained(self, save_directory: str): if os.path.isfile(save_directory): logger.error('Provided path ({}) should be a directory, not a file'.format(save_directory)) return os.makedirs(save_directory, exist_ok=True) self.model.save_pretrained(save_directory) self.tokenizer.save_...
['def', 'save_pretrained(self,', 'save_directory:', 'str):', 'if', 'os.path.isfile(save_directory):', "logger.error('Provided", 'path', '({})', 'should', 'be', 'a', 'directory,', 'not', 'a', "file'.format(save_directory))", 'return', 'os.makedirs(save_directory,', 'exist_ok=True)', 'self.model.save_pretrained(save_dire...
418,220
nilearn/nilearn
test_helpers.py
test_transfer_deprecated_param_vals
test_transfer_deprecated_param_vals
Unit test to check that values assigned to deprecated parameters are correctly reassigned to the replacement parameters.
[ "Unit", "test", "to", "check", "that", "values", "assigned", "to", "deprecated", "parameters", "are", "correctly", "reassigned", "to", "the", "replacement", "parameters." ]
def test_transfer_deprecated_param_vals(): (mock_input, replacement_params) = _mock_args_for_testing_replace_parameter() expected_output = {'unchanged_param_0': 'unchanged_param_0_val', 'replacement_param_0': 'deprecated_param_0_val', 'replacement_param_1': 'deprecated_param_1_val', 'unchanged_param_1': 'unchan...
['def', 'test_transfer_deprecated_param_vals():', '(mock_input,', 'replacement_params)', '=', '_mock_args_for_testing_replace_parameter()', 'expected_output', '=', "{'unchanged_param_0':", "'unchanged_param_0_val',", "'replacement_param_0':", "'deprecated_param_0_val',", "'replacement_param_1':", "'deprecated_param_1_v...
724,339
hans/pyccg
test_logic.py
test_iter_application_splits_complete
test_iter_application_splits_complete
Evaluate completeness of `iter_application_splits` (not an exhaustive test).
[ "Evaluate", "completeness", "of", "`iter_application_splits`", "(not", "an", "exhaustive", "test)." ]
def test_iter_application_splits_complete(): ontology = _make_mock_ontology() cases = [('\\x.and_(foo(x),bar(x))', {('\\z1 x.z1(x,foo)', '\\z1 z2.and_(z2(z1),bar(z1))', '/'), ('\\z1 x.and_(z1(x),bar(x))', 'foo', '/')})] def do_test(expr, assert_in): expr = Expression.fromstring(expr) splits...
['def', 'test_iter_application_splits_complete():', 'ontology', '=', '_make_mock_ontology()', 'cases', '=', "[('\\\\x.and_(foo(x),bar(x))',", "{('\\\\z1", "x.z1(x,foo)',", "'\\\\z1", "z2.and_(z2(z1),bar(z1))',", "'/'),", "('\\\\z1", "x.and_(z1(x),bar(x))',", "'foo',", "'/')})]", 'def', 'do_test(expr,', 'assert_in):', '...
296,049
scikit-learn/scikit-learn
test_neighbors.py
test_nearest_neighbors_validate_params
test_nearest_neighbors_validate_params
Validate parameter of NearestNeighbors.
[ "Validate", "parameter", "of", "NearestNeighbors." ]
def test_nearest_neighbors_validate_params(): X = rng.random_sample((10, 2)) nbrs = neighbors.NearestNeighbors().fit(X) msg = 'Unsupported mode, must be one of "connectivity", or "distance" but got "blah" instead' with pytest.raises(ValueError, match=msg): nbrs.kneighbors_graph(X, mode='blah') ...
['def', 'test_nearest_neighbors_validate_params():', 'X', '=', 'rng.random_sample((10,', '2))', 'nbrs', '=', 'neighbors.NearestNeighbors().fit(X)', 'msg', '=', "'Unsupported", 'mode,', 'must', 'be', 'one', 'of', '"connectivity",', 'or', '"distance"', 'but', 'got', '"blah"', "instead'", 'with', 'pytest.raises(ValueError...
853,876
weimin17/Object-Detection_HelmetDetection
dsn.py
create_model
create_model
Creates a DSN model.
[ "Creates", "a", "DSN", "model." ]
def create_model(source_images, source_labels, domain_selection_mask, target_images, target_labels, similarity_loss, params, basic_tower_name): network = getattr(models, basic_tower_name) num_classes = source_labels['classes'].get_shape().as_list()[1] network = partial(network, num_classes=num_classes) ...
['def', 'create_model(source_images,', 'source_labels,', 'domain_selection_mask,', 'target_images,', 'target_labels,', 'similarity_loss,', 'params,', 'basic_tower_name):', 'network', '=', 'getattr(models,', 'basic_tower_name)', 'num_classes', '=', "source_labels['classes'].get_shape().as_list()[1]", 'network', '=', 'pa...
749,841
sarnsdev/social-alignment-data-mining
pyparsing.py
ParseResults.getName
getName
Returns the results name for this token expression.
[ "Returns", "the", "results", "name", "for", "this", "token", "expression." ]
def getName(self): if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif len(self) == 1 and len(self.__tokdict) == 1 and (self.__tokdict.values()[0][0][1] in (0, -1)): ...
['def', 'getName(self):', 'if', 'self.__name:', 'return', 'self.__name', 'elif', 'self.__parent:', 'par', '=', 'self.__parent()', 'if', 'par:', 'return', 'par.__lookup(self)', 'else:', 'return', 'None', 'elif', 'len(self)', '==', '1', 'and', 'len(self.__tokdict)', '==', '1', 'and', '(self.__tokdict.values()[0][0][1]', ...
390,578
tobegit3hub/deep_image_model
debugger_cli_common.py
CommandHandlerRegistry.dispatch_command
dispatch_command
Handles a command by dispatching it to a registered command handler.
[ "Handles", "a", "command", "by", "dispatching", "it", "to", "a", "registered", "command", "handler." ]
def dispatch_command(self, prefix, argv, screen_info=None): if not prefix: raise ValueError('Prefix is empty') resolved_prefix = self._resolve_prefix(prefix) if not resolved_prefix: raise ValueError('No handler is registered for command prefix "%s"' % prefix) handler = self._handlers[res...
['def', 'dispatch_command(self,', 'prefix,', 'argv,', 'screen_info=None):', 'if', 'not', 'prefix:', 'raise', "ValueError('Prefix", 'is', "empty')", 'resolved_prefix', '=', 'self._resolve_prefix(prefix)', 'if', 'not', 'resolved_prefix:', 'raise', "ValueError('No", 'handler', 'is', 'registered', 'for', 'command', 'prefix...
182,406
google-research/rigl
utils_test.py
UtilsTest.test_compute_metrics_equal_logits
test_compute_metrics_equal_logits
Tests output when the logit outputs are equal for all classes.
[ "Tests", "output", "when", "the", "logit", "outputs", "are", "equal", "for", "all", "classes." ]
def test_compute_metrics_equal_logits(self): (logits, labels_correct) = self._create_logits_labels(True) logits = training._shard_batch(logits) labels_correct = training._shard_batch(labels_correct) p_compute_metrics = jax.pmap(utils.compute_metrics, axis_name='batch') metrics = p_compute_metrics(lo...
['def', 'test_compute_metrics_equal_logits(self):', '(logits,', 'labels_correct)', '=', 'self._create_logits_labels(True)', 'logits', '=', 'training._shard_batch(logits)', 'labels_correct', '=', 'training._shard_batch(labels_correct)', 'p_compute_metrics', '=', 'jax.pmap(utils.compute_metrics,', "axis_name='batch')", '...
841,563
guxm2021/ALT_SpeechBrain
train_rnnlm.py
LM.compute_forward
compute_forward
Forward computations from the sentence batches to the output probabilities.
[ "Forward", "computations", "from", "the", "sentence", "batches", "to", "the", "output", "probabilities." ]
def compute_forward(self, batch, stage): batch = batch.to(self.device) (tokens_bos, _) = batch.tokens_bos logits = self.hparams.model(tokens_bos) pred = self.hparams.log_softmax(logits) return pred
['def', 'compute_forward(self,', 'batch,', 'stage):', 'batch', '=', 'batch.to(self.device)', '(tokens_bos,', '_)', '=', 'batch.tokens_bos', 'logits', '=', 'self.hparams.model(tokens_bos)', 'pred', '=', 'self.hparams.log_softmax(logits)', 'return', 'pred']
415,377
voxel51/fiftyone
cvat.py
CVATAnnotationAPI.put
put
Sends a PUT request to the given CVAT API URL.
[ "Sends", "a", "PUT", "request", "to", "the", "given", "CVAT", "API", "URL." ]
def put(self, url, **kwargs): return self._make_request(self._session.put, url, **kwargs)
['def', 'put(self,', 'url,', '**kwargs):', 'return', 'self._make_request(self._session.put,', 'url,', '**kwargs)']
583,994
tensortrade-org/tensortrade
environment.py
TradingEnv.save
save
Saves the rendered view of the environment.
[ "Saves", "the", "rendered", "view", "of", "the", "environment." ]
def save(self) -> None: self.renderer.save()
['def', 'save(self)', '->', 'None:', 'self.renderer.save()']
366,705
ryu-ed/SpaceInvaders_Ros
request.py
URLopener.http_error_default
http_error_default
Default error handler: close the connection and raise IOError.
[ "Default", "error", "handler:", "close", "the", "connection", "and", "raise", "IOError." ]
def http_error_default(self, url, fp, errcode, errmsg, headers): fp.close() raise HTTPError(url, errcode, errmsg, headers, None)
['def', 'http_error_default(self,', 'url,', 'fp,', 'errcode,', 'errmsg,', 'headers):', 'fp.close()', 'raise', 'HTTPError(url,', 'errcode,', 'errmsg,', 'headers,', 'None)']
395,934
skku-tnt/22-2-Computer-Vision
dist.py
wait_for_the_master
wait_for_the_master
Make all processes waiting for the master to do some task.
[ "Make", "all", "processes", "waiting", "for", "the", "master", "to", "do", "some", "task." ]
def wait_for_the_master(local_rank: int=None): if local_rank is None: local_rank = get_local_rank() if local_rank > 0: dist.barrier() yield if local_rank == 0: if not dist.is_available(): return if not dist.is_initialized(): return else: ...
['def', 'wait_for_the_master(local_rank:', 'int=None):', 'if', 'local_rank', 'is', 'None:', 'local_rank', '=', 'get_local_rank()', 'if', 'local_rank', '>', '0:', 'dist.barrier()', 'yield', 'if', 'local_rank', '==', '0:', 'if', 'not', 'dist.is_available():', 'return', 'if', 'not', 'dist.is_initialized():', 'return', 'el...
375,676
meghdadFar/snlp
am.py
calculate_am
calculate_am
Read the counts from path_to_counts and for each compound calculates the measure specified by am.
[ "Read", "the", "counts", "from", "path_to_counts", "and", "for", "each", "compound", "calculates", "the", "measure", "specified", "by", "am." ]
def calculate_am(count_data: dict, am: str, mwe_types: List[str]) -> Dict[str, Dict]: res = {} num_words = sum(count_data['WORDS'].values()) if am == 'pmi': for mt in mwe_types: compound_dict_tmp = calculate_pmi(compound_dict=count_data[mt], word_dic=count_data['WORDS'], num_compound=sum...
['def', 'calculate_am(count_data:', 'dict,', 'am:', 'str,', 'mwe_types:', 'List[str])', '->', 'Dict[str,', 'Dict]:', 'res', '=', '{}', 'num_words', '=', "sum(count_data['WORDS'].values())", 'if', 'am', '==', "'pmi':", 'for', 'mt', 'in', 'mwe_types:', 'compound_dict_tmp', '=', 'calculate_pmi(compound_dict=count_data[mt]...
878,881
Alexander-Parker/youtube_nlp
options.py
Options.add_argument
add_argument
Add argument to be used for the browser process.
[ "Add", "argument", "to", "be", "used", "for", "the", "browser", "process." ]
def add_argument(self, argument): if argument is None: raise ValueError() self._arguments.append(argument)
['def', 'add_argument(self,', 'argument):', 'if', 'argument', 'is', 'None:', 'raise', 'ValueError()', 'self._arguments.append(argument)']
970,867