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
axis_artist.py
Ticks.set_ticksize
set_ticksize
Set length of the ticks in points.
[ "Set", "length", "of", "the", "ticks", "in", "points." ]
def set_ticksize(self, ticksize): self._ticksize = ticksize
['def', 'set_ticksize(self,', 'ticksize):', 'self._ticksize', '=', 'ticksize']
320,444
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
neural_gpu.py
autoenc_quantize
autoenc_quantize
Autoencoder into nbits vectors of bits, using noise and sigmoids.
[ "Autoencoder", "into", "nbits", "vectors", "of", "bits,", "using", "noise", "and", "sigmoids." ]
def autoenc_quantize(x, nbits, nmaps, do_training, layers=1): enc_x = tf.reshape(x, [-1, nmaps]) for i in xrange(layers - 1): enc_x = tf.layers.dense(enc_x, nmaps, name='autoenc_%d' % i) enc_x = tf.layers.dense(enc_x, nbits, name='autoenc_%d' % (layers - 1)) noise = tf.truncated_normal(tf.shape(...
['def', 'autoenc_quantize(x,', 'nbits,', 'nmaps,', 'do_training,', 'layers=1):', 'enc_x', '=', 'tf.reshape(x,', '[-1,', 'nmaps])', 'for', 'i', 'in', 'xrange(layers', '-', '1):', 'enc_x', '=', 'tf.layers.dense(enc_x,', 'nmaps,', "name='autoenc_%d'", '%', 'i)', 'enc_x', '=', 'tf.layers.dense(enc_x,', 'nbits,', "name='aut...
50,098
deepmind/dm_control
viewer.py
CameraSelector.escape
escape
Unconditionally switches to the free camera.
[ "Unconditionally", "switches", "to", "the", "free", "camera." ]
def escape(self) -> None: self._camera_idx = -1 self._commit_selection()
['def', 'escape(self)', '->', 'None:', 'self._camera_idx', '=', '-1', 'self._commit_selection()']
166,625
AxeldeRomblay/MLBox
test_classifier.py
test_predict_classifier
test_predict_classifier
Test predict method of Classifier class.
[ "Test", "predict", "method", "of", "Classifier", "class." ]
def test_predict_classifier(): df_train = pd.read_csv('data_for_tests/clean_train.csv') y_train = pd.read_csv('data_for_tests/clean_target.csv', squeeze=True) classifier = Classifier() with pytest.raises(ValueError): classifier.predict(df_train) classifier.fit(df_train, y_train) with pyt...
['def', 'test_predict_classifier():', 'df_train', '=', "pd.read_csv('data_for_tests/clean_train.csv')", 'y_train', '=', "pd.read_csv('data_for_tests/clean_target.csv',", 'squeeze=True)', 'classifier', '=', 'Classifier()', 'with', 'pytest.raises(ValueError):', 'classifier.predict(df_train)', 'classifier.fit(df_train,', ...
630,013
chribsen/simple-machine-learning-examples
test_peak_finding.py
TestFindPeaks.test_find_peaks_exact
test_find_peaks_exact
Generate a series of gaussians and attempt to find the peak locations.
[ "Generate", "a", "series", "of", "gaussians", "and", "attempt", "to", "find", "the", "peak", "locations." ]
def test_find_peaks_exact(self): sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0] num_points = 500 (test_data, act_locs) = _gen_gaussians_even(sigmas, num_points) widths = np.arange(0.1, max(sigmas)) found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=0, min_length=None) np.testing.a...
['def', 'test_find_peaks_exact(self):', 'sigmas', '=', '[5.0,', '3.0,', '10.0,', '20.0,', '10.0,', '50.0]', 'num_points', '=', '500', '(test_data,', 'act_locs)', '=', '_gen_gaussians_even(sigmas,', 'num_points)', 'widths', '=', 'np.arange(0.1,', 'max(sigmas))', 'found_locs', '=', 'find_peaks_cwt(test_data,', 'widths,',...
938,394
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
imagenet.py
get_split
get_split
Gets a dataset tuple with instructions for reading ImageNet.
[ "Gets", "a", "dataset", "tuple", "with", "instructions", "for", "reading", "ImageNet." ]
def get_split(split_name, dataset_dir, file_pattern=None, reader=None): if split_name not in _SPLITS_TO_SIZES: raise ValueError('split name %s was not recognized.' % split_name) if not file_pattern: file_pattern = _FILE_PATTERN file_pattern = os.path.join(dataset_dir, file_pattern % split_na...
['def', 'get_split(split_name,', 'dataset_dir,', 'file_pattern=None,', 'reader=None):', 'if', 'split_name', 'not', 'in', '_SPLITS_TO_SIZES:', 'raise', "ValueError('split", 'name', '%s', 'was', 'not', "recognized.'", '%', 'split_name)', 'if', 'not', 'file_pattern:', 'file_pattern', '=', '_FILE_PATTERN', 'file_pattern', ...
109,782
Ruturaj123/Flowchart-Detection
resource_variable_ops.py
ResourceVariable.create
create
The op responsible for initializing this variable.
[ "The", "op", "responsible", "for", "initializing", "this", "variable." ]
def create(self): if not context.in_graph_mode(): raise RuntimeError('Calling create in EAGER mode not supported.') return self._initializer_op
['def', 'create(self):', 'if', 'not', 'context.in_graph_mode():', 'raise', "RuntimeError('Calling", 'create', 'in', 'EAGER', 'mode', 'not', "supported.')", 'return', 'self._initializer_op']
606,075
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
real_nvp_multiscale_dataset.py
HParams.update_config
update_config
Update the dictionary with a comma separated list.
[ "Update", "the", "dictionary", "with", "a", "comma", "separated", "list." ]
def update_config(self, in_string): pairs = in_string.split(',') pairs = [pair.split('=') for pair in pairs] for (key, val) in pairs: self.dict_[key] = type(self.dict_[key])(val) self.__dict__.update(self.dict_) return self
['def', 'update_config(self,', 'in_string):', 'pairs', '=', "in_string.split(',')", 'pairs', '=', "[pair.split('=')", 'for', 'pair', 'in', 'pairs]', 'for', '(key,', 'val)', 'in', 'pairs:', 'self.dict_[key]', '=', 'type(self.dict_[key])(val)', 'self.__dict__.update(self.dict_)', 'return', 'self']
26,546
chenbinghui1/DSL
gaussian_target.py
gather_feat
gather_feat
Gather feature according to index.
[ "Gather", "feature", "according", "to", "index." ]
def gather_feat(feat, ind, mask=None): dim = feat.size(2) ind = ind.unsqueeze(2).repeat(1, 1, dim) feat = feat.gather(1, ind) if mask is not None: mask = mask.unsqueeze(2).expand_as(feat) feat = feat[mask] feat = feat.view(-1, dim) return feat
['def', 'gather_feat(feat,', 'ind,', 'mask=None):', 'dim', '=', 'feat.size(2)', 'ind', '=', 'ind.unsqueeze(2).repeat(1,', '1,', 'dim)', 'feat', '=', 'feat.gather(1,', 'ind)', 'if', 'mask', 'is', 'not', 'None:', 'mask', '=', 'mask.unsqueeze(2).expand_as(feat)', 'feat', '=', 'feat[mask]', 'feat', '=', 'feat.view(-1,', 'd...
167,958
deepmind/pycolab
maze_walker_test.py
MazeWalkerTest.testNotConfinedToBoard
testNotConfinedToBoard
An ordinary MazeWalker disappears if it walks off the board.
[ "An", "ordinary", "MazeWalker", "disappears", "if", "it", "walks", "off", "the", "board." ]
def testNotConfinedToBoard(self): art = [' ', ' P ', ' '] engine = ascii_art.ascii_art_to_game(art=art, what_lies_beneath=' ', sprites=dict(P=ascii_art.Partial(tt.TestMazeWalker, impassable=''))) engine.its_showtime() def check_positions(actions, board, layers, backdrop, things, the_plot): ...
['def', 'testNotConfinedToBoard(self):', 'art', '=', "['", "',", "'", 'P', "',", "'", "']", 'engine', '=', 'ascii_art.ascii_art_to_game(art=art,', "what_lies_beneath='", "',", 'sprites=dict(P=ascii_art.Partial(tt.TestMazeWalker,', "impassable='')))", 'engine.its_showtime()', 'def', 'check_positions(actions,', 'board,',...
819,306
chengfx/neural-networks-and-deep-learning-for-python3
Network.py
Network.cost_derivative
cost_derivative
Return the vector of partial derivatives \partial C_x / \partial a for the output activations.
[ "Return", "the", "vector", "of", "partial", "derivatives", "\\partial", "C_x", "/", "\\partial", "a", "for", "the", "output", "activations." ]
def cost_derivative(self, output_activations, y): return output_activations - y
['def', 'cost_derivative(self,', 'output_activations,', 'y):', 'return', 'output_activations', '-', 'y']
722,006
kubeflow/pipelines
remote_runner.py
resolve_init_args
resolve_init_args
Resolves Metadata/InputPath parameters to resource names.
[ "Resolves", "Metadata/InputPath", "parameters", "to", "resource", "names." ]
def resolve_init_args(key, value): if key.endswith('_name'): if value.startswith(RESOURCE_PREFIX['google_cloud_storage_gcs_fuse']): value = value[len(RESOURCE_PREFIX['google_cloud_storage_gcs_fuse']):] if value.startswith(RESOURCE_PREFIX.get('aiplatform')): prefix_str = f"{RE...
['def', 'resolve_init_args(key,', 'value):', 'if', "key.endswith('_name'):", 'if', "value.startswith(RESOURCE_PREFIX['google_cloud_storage_gcs_fuse']):", 'value', '=', "value[len(RESOURCE_PREFIX['google_cloud_storage_gcs_fuse']):]", 'if', "value.startswith(RESOURCE_PREFIX.get('aiplatform')):", 'prefix_str', '=', 'f"{RE...
770,740
weimin17/Object-Detection_HelmetDetection
core.py
compute_eps_from_delta
compute_eps_from_delta
Translates between RDP and (eps, delta)-DP.
[ "Translates", "between", "RDP", "and", "(eps,", "delta)-DP." ]
def compute_eps_from_delta(orders, rdp, delta): if len(orders) != len(rdp): raise ValueError('Input lists must have the same length.') eps = np.array(rdp) - math.log(delta) / (np.array(orders) - 1) idx_opt = np.argmin(eps) return (eps[idx_opt], orders[idx_opt])
['def', 'compute_eps_from_delta(orders,', 'rdp,', 'delta):', 'if', 'len(orders)', '!=', 'len(rdp):', 'raise', "ValueError('Input", 'lists', 'must', 'have', 'the', 'same', "length.')", 'eps', '=', 'np.array(rdp)', '-', 'math.log(delta)', '/', '(np.array(orders)', '-', '1)', 'idx_opt', '=', 'np.argmin(eps)', 'return', '(...
762,563
YanZiQinKevin/object_detection
test_case.py
TestCase.execute_cpu
execute_cpu
Constructs the graph, executes it on CPU and returns the result.
[ "Constructs", "the", "graph,", "executes", "it", "on", "CPU", "and", "returns", "the", "result." ]
def execute_cpu(self, graph_fn, inputs): with self.test_session(graph=tf.Graph()) as sess: placeholders = [tf.placeholder_with_default(v, v.shape) for v in inputs] results = graph_fn(*placeholders) sess.run([tf.global_variables_initializer(), tf.tables_initializer(), tf.local_variables_initi...
['def', 'execute_cpu(self,', 'graph_fn,', 'inputs):', 'with', 'self.test_session(graph=tf.Graph())', 'as', 'sess:', 'placeholders', '=', '[tf.placeholder_with_default(v,', 'v.shape)', 'for', 'v', 'in', 'inputs]', 'results', '=', 'graph_fn(*placeholders)', 'sess.run([tf.global_variables_initializer(),', 'tf.tables_initi...
793,888
jxhe/unify-parameter-efficient-tuning
release.py
clean_master_ref_in_model_list
clean_master_ref_in_model_list
Replace the links from master doc tp stable doc in the model list of the README.
[ "Replace", "the", "links", "from", "master", "doc", "tp", "stable", "doc", "in", "the", "model", "list", "of", "the", "README." ]
def clean_master_ref_in_model_list(): _start_prompt = 'ðÂ\x9f¤Â\x97 Transformers currently provides the following architectures' _end_prompt = '1. Want to contribute a new model?' with open(README_FILE, 'r', encoding='utf-8', newline='\n') as f: lines = f.readlines() start_index = 0 while ...
['def', 'clean_master_ref_in_model_list():', '_start_prompt', '=', "'ðÂ\\x9f¤Â\\x97", 'Transformers', 'currently', 'provides', 'the', 'following', "architectures'", '_end_prompt', '=', "'1.", 'Want', 'to', 'contribute', 'a', 'new', "model?'", 'with', 'open(README_FILE,', "'r',", "encoding='utf-8',", "newline='\\n')",...
949,600
weimin17/Object-Detection_HelmetDetection
train_mask_gan.py
evaluate_once
evaluate_once
Evaluate model for a number of steps.
[ "Evaluate", "model", "for", "a", "number", "of", "steps." ]
def evaluate_once(data, sv, model, sess, train_dir, log, id_to_word, data_ngram_counts, eval_saver): tf.logging.info('Evaluate Once.') model_save_path = tf.latest_checkpoint(train_dir) if not model_save_path: tf.logging.warning('No checkpoint yet in: %s', train_dir) return tf.logging.inf...
['def', 'evaluate_once(data,', 'sv,', 'model,', 'sess,', 'train_dir,', 'log,', 'id_to_word,', 'data_ngram_counts,', 'eval_saver):', "tf.logging.info('Evaluate", "Once.')", 'model_save_path', '=', 'tf.latest_checkpoint(train_dir)', 'if', 'not', 'model_save_path:', "tf.logging.warning('No", 'checkpoint', 'yet', 'in:', "%...
757,900
PacktPublishing/Hands-On-Artificial--for-Banking
filters.py
do_trim
do_trim
Strip leading and trailing characters, by default whitespace.
[ "Strip", "leading", "and", "trailing", "characters,", "by", "default", "whitespace." ]
def do_trim(value, chars=None): return soft_unicode(value).strip(chars)
['def', 'do_trim(value,', 'chars=None):', 'return', 'soft_unicode(value).strip(chars)']
235,059
nqanh/video2command
iit_v2c.py
load_annotations
load_annotations
Helper function to parse IIT-V2C dataset.
[ "Helper", "function", "to", "parse", "IIT-V2C", "dataset." ]
def load_annotations(dataset_path=os.path.join('datasets', 'IIT-V2C'), annotation_file='train.txt'): def get_frames_no(init_frame_no, end_frame_no): frames = [] for i in range(init_frame_no, end_frame_no + 1, 1): frames.append(i) return frames annotations = {} with open(...
['def', "load_annotations(dataset_path=os.path.join('datasets',", "'IIT-V2C'),", "annotation_file='train.txt'):", 'def', 'get_frames_no(init_frame_no,', 'end_frame_no):', 'frames', '=', '[]', 'for', 'i', 'in', 'range(init_frame_no,', 'end_frame_no', '+', '1,', '1):', 'frames.append(i)', 'return', 'frames', 'annotations...
379,831
scikit-learn/scikit-learn
test_openml.py
test_fetch_openml_requires_pandas_in_future
test_fetch_openml_requires_pandas_in_future
Check that we raise a warning that pandas will be required in the future.
[ "Check", "that", "we", "raise", "a", "warning", "that", "pandas", "will", "be", "required", "in", "the", "future." ]
def test_fetch_openml_requires_pandas_in_future(monkeypatch): params = {'as_frame': False, 'parser': 'auto'} data_id = 1119 try: check_pandas_support('test_fetch_openml_requires_pandas') except ImportError: _monkey_patch_webbased_functions(monkeypatch, data_id, True) warn_msg = "...
['def', 'test_fetch_openml_requires_pandas_in_future(monkeypatch):', 'params', '=', "{'as_frame':", 'False,', "'parser':", "'auto'}", 'data_id', '=', '1119', 'try:', "check_pandas_support('test_fetch_openml_requires_pandas')", 'except', 'ImportError:', '_monkey_patch_webbased_functions(monkeypatch,', 'data_id,', 'True)...
852,967
tensorflow/privacy
audit.py
compute_epsilon_and_acc
compute_epsilon_and_acc
For a given threshold, compute epsilon and accuracy.
[ "For", "a", "given", "threshold,", "compute", "epsilon", "and", "accuracy." ]
def compute_epsilon_and_acc(poison_arr, unpois_arr, threshold, alpha, pois_ct): poison_ct = (poison_arr > threshold).sum() unpois_ct = (unpois_arr > threshold).sum() (p1, _) = proportion.proportion_confint(poison_ct, poison_arr.size, alpha, method='beta') (_, p0) = proportion.proportion_confint(unpois_c...
['def', 'compute_epsilon_and_acc(poison_arr,', 'unpois_arr,', 'threshold,', 'alpha,', 'pois_ct):', 'poison_ct', '=', '(poison_arr', '>', 'threshold).sum()', 'unpois_ct', '=', '(unpois_arr', '>', 'threshold).sum()', '(p1,', '_)', '=', 'proportion.proportion_confint(poison_ct,', 'poison_arr.size,', 'alpha,', "method='bet...
824,453
Kvatsx/Artificial-Intelligence-Assignments
streamplot.py
Grid.within_grid
within_grid
Return True if point is a valid index of grid.
[ "Return", "True", "if", "point", "is", "a", "valid", "index", "of", "grid." ]
def within_grid(self, xi, yi): return xi >= 0 and xi <= self.nx - 1 and (yi >= 0) and (yi <= self.ny - 1)
['def', 'within_grid(self,', 'xi,', 'yi):', 'return', 'xi', '>=', '0', 'and', 'xi', '<=', 'self.nx', '-', '1', 'and', '(yi', '>=', '0)', 'and', '(yi', '<=', 'self.ny', '-', '1)']
878
SmallVagetable/reinforcement-learning
core.py
Episode.pop
pop
normally this method shouldn't be invoked.
[ "normally", "this", "method", "shouldn't", "be", "invoked." ]
def pop(self) -> Transition: if self.len > 1: trans = self.trans_list.pop() self.total_reward -= trans.reward return trans else: return None
['def', 'pop(self)', '->', 'Transition:', 'if', 'self.len', '>', '1:', 'trans', '=', 'self.trans_list.pop()', 'self.total_reward', '-=', 'trans.reward', 'return', 'trans', 'else:', 'return', 'None']
341,314
sarnsdev/social-alignment-data-mining
test__iotools.py
TestStringConverter.test_upgrade
test_upgrade
Tests the upgrade method.
[ "Tests", "the", "upgrade", "method." ]
def test_upgrade(self): converter = StringConverter() assert_equal(converter._status, 0) assert_equal(converter.upgrade('0'), 0) assert_equal(converter._status, 1) import numpy.core.numeric as nx status_offset = int(nx.dtype(nx.int_).itemsize < nx.dtype(nx.int64).itemsize) assert_equal(conve...
['def', 'test_upgrade(self):', 'converter', '=', 'StringConverter()', 'assert_equal(converter._status,', '0)', "assert_equal(converter.upgrade('0'),", '0)', 'assert_equal(converter._status,', '1)', 'import', 'numpy.core.numeric', 'as', 'nx', 'status_offset', '=', 'int(nx.dtype(nx.int_).itemsize', '<', 'nx.dtype(nx.int6...
389,395
cagbal/ros_people_object_detection_tensorflow
model_test.py
ModelTflearnTest.testModelFnInTrainMode
testModelFnInTrainMode
Tests the model function in TRAIN mode.
[ "Tests", "the", "model", "function", "in", "TRAIN", "mode." ]
def testModelFnInTrainMode(self): configs = _get_configs_for_model(MODEL_NAME_FOR_TEST) self._assert_outputs_for_train_eval(configs, tf.estimator.ModeKeys.TRAIN)
['def', 'testModelFnInTrainMode(self):', 'configs', '=', '_get_configs_for_model(MODEL_NAME_FOR_TEST)', 'self._assert_outputs_for_train_eval(configs,', 'tf.estimator.ModeKeys.TRAIN)']
827,349
HighnessAtharva/VocabCLI
vocabCLI.py
history
history
Get a lookup history of a word.
[ "Get", "a", "lookup", "history", "of", "a", "word." ]
def history(words: List[str]=typer.Argument(..., help='ðÂ\x9fÂ\x94Â\x81 Word to get [bold bright_magenta]lookup history[/bold bright_magenta] for')): from modules.Utils import fetch_word_history for word in words: fetch_word_history(word)
['def', 'history(words:', 'List[str]=typer.Argument(...,', "help='ðÂ\\x9fÂ\\x94Â\\x81", 'Word', 'to', 'get', '[bold', 'bright_magenta]lookup', 'history[/bold', 'bright_magenta]', "for')):", 'from', 'modules.Utils', 'import', 'fetch_word_history', 'for', 'word', 'in', 'words:', 'fetch_word_history(word)']
946,226
sek788432/Waymo-2D-Object-Detection
ncf_keras_main.py
run_ncf_custom_training
run_ncf_custom_training
Runs custom training loop.
[ "Runs", "custom", "training", "loop." ]
def run_ncf_custom_training(params, strategy, keras_model, optimizer, callbacks, train_input_dataset, eval_input_dataset, num_train_steps, num_eval_steps, generate_input_online=True): loss_object = tf.keras.losses.SparseCategoricalCrossentropy(reduction='sum', from_logits=True) train_input_iterator = iter(strat...
['def', 'run_ncf_custom_training(params,', 'strategy,', 'keras_model,', 'optimizer,', 'callbacks,', 'train_input_dataset,', 'eval_input_dataset,', 'num_train_steps,', 'num_eval_steps,', 'generate_input_online=True):', 'loss_object', '=', "tf.keras.losses.SparseCategoricalCrossentropy(reduction='sum',", 'from_logits=Tru...
972,970
google-research/scenic
registry.py
get_model_cls
get_model_cls
Returns the model class for training.
[ "Returns", "the", "model", "class", "for", "training." ]
def get_model_cls(model_name): if model_name == 'vit_multilabel_classification': return baseline_vit.ViTMultiLabelClassificationModel elif model_name == 'vit_multilabel_classification_mae': return vit.ViTMAEMultilabelFinetuning elif model_name == 'vit_classification_mae': return vit....
['def', 'get_model_cls(model_name):', 'if', 'model_name', '==', "'vit_multilabel_classification':", 'return', 'baseline_vit.ViTMultiLabelClassificationModel', 'elif', 'model_name', '==', "'vit_multilabel_classification_mae':", 'return', 'vit.ViTMAEMultilabelFinetuning', 'elif', 'model_name', '==', "'vit_classification_...
846,421
cvlab-yonsei/JoEm
parallel.py
allreduce
allreduce
Cross GPU all reduce autograd operation for calculate mean and variance in SyncBN.
[ "Cross", "GPU", "all", "reduce", "autograd", "operation", "for", "calculate", "mean", "and", "variance", "in", "SyncBN." ]
def allreduce(*inputs): return AllReduce.apply(*inputs)
['def', 'allreduce(*inputs):', 'return', 'AllReduce.apply(*inputs)']
577,952
43Carrig/recurrent_neural_networks_practice
gumbel.py
Gumbel.loc
loc
The `loc` in `Y = g(X) = exp(-exp(-(X - loc) / scale))`.
[ "The", "`loc`", "in", "`Y", "=", "g(X)", "=", "exp(-exp(-(X", "-", "loc)", "/", "scale))`." ]
def loc(self): return self._loc
['def', 'loc(self):', 'return', 'self._loc']
312,925
triaquae/triaquae
dates.py
BaseTodayArchiveView.get_dated_items
get_dated_items
Return (date_list, items, extra_context) for this request.
[ "Return", "(date_list,", "items,", "extra_context)", "for", "this", "request." ]
def get_dated_items(self): return self._get_dated_items(datetime.date.today())
['def', 'get_dated_items(self):', 'return', 'self._get_dated_items(datetime.date.today())']
424,368
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Misc.getvar
getvar
Return value of Tcl variable NAME.
[ "Return", "value", "of", "Tcl", "variable", "NAME." ]
def getvar(self, name='PY_VAR'): return self.tk.getvar(name)
['def', 'getvar(self,', "name='PY_VAR'):", 'return', 'self.tk.getvar(name)']
376,763
zihuitang/medical_AI_platform
operator.py
is_not
is_not
Same as a is not b.
[ "Same", "as", "a", "is", "not", "b." ]
def is_not(a, b): return a is not b
['def', 'is_not(a,', 'b):', 'return', 'a', 'is', 'not', 'b']
280,884
apletea/Computer-Vision
resneXt.py
resnext34
resnext34
Constructs a ResNeXt-34 model.
[ "Constructs", "a", "ResNeXt-34", "model." ]
def resnext34(**kwargs): model = ResNeXt(BasicBlock, [3, 4, 6, 3], **kwargs) return model
['def', 'resnext34(**kwargs):', 'model', '=', 'ResNeXt(BasicBlock,', '[3,', '4,', '6,', '3],', '**kwargs)', 'return', 'model']
460,023
facebookresearch/CompilerGym
env_without_bazel_test.py
test_reset_invalid_benchmark
test_reset_invalid_benchmark
Test requesting a specific benchmark.
[ "Test", "requesting", "a", "specific", "benchmark." ]
def test_reset_invalid_benchmark(env: CompilerEnv): with pytest.raises(LookupError) as ctx: env.reset(benchmark='unrolling-v2/foobar') assert str(ctx.value) == 'Unknown program name'
['def', 'test_reset_invalid_benchmark(env:', 'CompilerEnv):', 'with', 'pytest.raises(LookupError)', 'as', 'ctx:', "env.reset(benchmark='unrolling-v2/foobar')", 'assert', 'str(ctx.value)', '==', "'Unknown", 'program', "name'"]
135,634
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
desc2code.py
ProgrammingDesc2codePy.preprocess_target
preprocess_target
Simple tab to space replacement.
[ "Simple", "tab", "to", "space", "replacement." ]
def preprocess_target(self, target): return target.replace('\t', ' ')
['def', 'preprocess_target(self,', 'target):', 'return', "target.replace('\\t',", "'", "')"]
964,853
mj-will/nessai
test_flowmodel_base.py
test_sample_and_log_prob_not_initialised
test_sample_and_log_prob_not_initialised
Ensure user cannot call the method before the model initialise.
[ "Ensure", "user", "cannot", "call", "the", "method", "before", "the", "model", "initialise." ]
def test_sample_and_log_prob_not_initialised(flow_model, data_dim): with pytest.raises(RuntimeError) as excinfo: flow_model.sample_and_log_prob() assert 'Model is not initialised' in str(excinfo.value)
['def', 'test_sample_and_log_prob_not_initialised(flow_model,', 'data_dim):', 'with', 'pytest.raises(RuntimeError)', 'as', 'excinfo:', 'flow_model.sample_and_log_prob()', 'assert', "'Model", 'is', 'not', "initialised'", 'in', 'str(excinfo.value)']
292,475
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
visitor.py
MethodContent.acceptSwitch
acceptSwitch
Accept and process a switch block.
[ "Accept", "and", "process", "a", "switch", "block." ]
def acceptSwitch(self, node, memo): parNode = node.firstChildOfType(tokens.PARENTESIZED_EXPR) lblNode = node.firstChildOfType(tokens.SWITCH_BLOCK_LABEL_LIST) caseNodes = lblNode.children if not len(caseNodes): return parExpr = self.factory.expr(parent=self) parExpr.walk(parNode, memo) ...
['def', 'acceptSwitch(self,', 'node,', 'memo):', 'parNode', '=', 'node.firstChildOfType(tokens.PARENTESIZED_EXPR)', 'lblNode', '=', 'node.firstChildOfType(tokens.SWITCH_BLOCK_LABEL_LIST)', 'caseNodes', '=', 'lblNode.children', 'if', 'not', 'len(caseNodes):', 'return', 'parExpr', '=', 'self.factory.expr(parent=self)', '...
11,209
Katja-M/Python_NaturalLanguageProcessing
bezier.py
split_path_inout
split_path_inout
Divide a path into two segments at the point where ``inside(x, y)`` becomes False.
[ "Divide", "a", "path", "into", "two", "segments", "at", "the", "point", "where", "``inside(x,", "y)``", "becomes", "False." ]
def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False): path_iter = path.iter_segments() (ctl_points, command) = next(path_iter) begin_inside = inside(ctl_points[-2:]) ctl_points_old = ctl_points concat = np.concatenate iold = 0 i = 1 for (ctl_points, command) in path_it...
['def', 'split_path_inout(path,', 'inside,', 'tolerance=0.01,', 'reorder_inout=False):', 'path_iter', '=', 'path.iter_segments()', '(ctl_points,', 'command)', '=', 'next(path_iter)', 'begin_inside', '=', 'inside(ctl_points[-2:])', 'ctl_points_old', '=', 'ctl_points', 'concat', '=', 'np.concatenate', 'iold', '=', '0', '...
864,367
enuguru/artificial_intelligence_and_machine_
compiler.py
CodeGenerator.temporary_identifier
temporary_identifier
Get a new unique identifier.
[ "Get", "a", "new", "unique", "identifier." ]
def temporary_identifier(self): self._last_identifier += 1 return 't_%d' % self._last_identifier
['def', 'temporary_identifier(self):', 'self._last_identifier', '+=', '1', 'return', "'t_%d'", '%', 'self._last_identifier']
129,071
rudranil723/mini-main
data.py
SeekableUnicodeStreamReader.mode
mode
The mode of the underlying stream.
[ "The", "mode", "of", "the", "underlying", "stream." ]
def mode(self): return self.stream.mode
['def', 'mode(self):', 'return', 'self.stream.mode']
320,512
PRMorgan/State-of-the-Artificial-Intelligence
Enemy.py
Enemy.stop
stop
Called when the user lets off the keyboard.
[ "Called", "when", "the", "user", "lets", "off", "the", "keyboard." ]
def stop(self): self.direction = 'none' self.change_x = 0
['def', 'stop(self):', 'self.direction', '=', "'none'", 'self.change_x', '=', '0']
383,842
shijie-wu/crosslingual-nlp
util.py
MappingCheckpoint.on_validation_end
on_validation_end
Called when the validation loop ends.
[ "Called", "when", "the", "validation", "loop", "ends." ]
def on_validation_end(self, trainer, pl_module): if pl_module.hparams.task == 'alignment' and pl_module.hparams.aligner_sim == 'linear': metrics = trainer.callback_metrics new_best_mappings = [] for (i, mapping) in enumerate(pl_module.mappings): key = f'val_layer{i}_loss' ...
['def', 'on_validation_end(self,', 'trainer,', 'pl_module):', 'if', 'pl_module.hparams.task', '==', "'alignment'", 'and', 'pl_module.hparams.aligner_sim', '==', "'linear':", 'metrics', '=', 'trainer.callback_metrics', 'new_best_mappings', '=', '[]', 'for', '(i,', 'mapping)', 'in', 'enumerate(pl_module.mappings):', 'key...
492,032
sek788432/Waymo-2D-Object-Detection
sequence_layers.py
SequenceLayerBase.is_training
is_training
Returns True if the layer is created for training stage.
[ "Returns", "True", "if", "the", "layer", "is", "created", "for", "training", "stage." ]
def is_training(self): return self._labels_one_hot is not None
['def', 'is_training(self):', 'return', 'self._labels_one_hot', 'is', 'not', 'None']
973,956
rudranil723/mini-main
client.py
Client.session
session
Return the current session variables.
[ "Return", "the", "current", "session", "variables." ]
def session(self): engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() session.save() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key ...
['def', 'session(self):', 'engine', '=', 'import_module(settings.SESSION_ENGINE)', 'cookie', '=', 'self.cookies.get(settings.SESSION_COOKIE_NAME)', 'if', 'cookie:', 'return', 'engine.SessionStore(cookie.value)', 'session', '=', 'engine.SessionStore()', 'session.save()', 'self.cookies[settings.SESSION_COOKIE_NAME]', '='...
316,536
triaquae/triaquae
_version133.py
randomized_primality_testing
randomized_primality_testing
Calculates whether n is composite (which is always correct) or prime (which is incorrect with error probability 2**-k) Returns False if the number if composite, and True if it's probably prime.
[ "Calculates", "whether", "n", "is", "composite", "(which", "is", "always", "correct)", "or", "prime", "(which", "is", "incorrect", "with", "error", "probability", "2**-k)", "Returns", "False", "if", "the", "number", "if", "composite,", "and", "True", "if", "it...
def randomized_primality_testing(n, k): q = 0.5 t = ceil(k / math.log(1 / q, 2)) for i in range(t + 1): x = randint(1, n - 1) if jacobi_witness(x, n): return False return True
['def', 'randomized_primality_testing(n,', 'k):', 'q', '=', '0.5', 't', '=', 'ceil(k', '/', 'math.log(1', '/', 'q,', '2))', 'for', 'i', 'in', 'range(t', '+', '1):', 'x', '=', 'randint(1,', 'n', '-', '1)', 'if', 'jacobi_witness(x,', 'n):', 'return', 'False', 'return', 'True']
356,874
alugupta/ares
trainer.py
Trainer.eval_clean
eval_clean
Evaluate detection performance on clean data.
[ "Evaluate", "detection", "performance", "on", "clean", "data." ]
def eval_clean(self): if self.cfg.clean_image.save: clean_image_save_dir = os.path.join(self.cfg.log_dir, self.cfg.clean_image.save_folder) mkdirs_if_not_exists(clean_image_save_dir) self.logger.info('Evaluating detection performance on clean data...') model = self.model.module if self.is_di...
['def', 'eval_clean(self):', 'if', 'self.cfg.clean_image.save:', 'clean_image_save_dir', '=', 'os.path.join(self.cfg.log_dir,', 'self.cfg.clean_image.save_folder)', 'mkdirs_if_not_exists(clean_image_save_dir)', "self.logger.info('Evaluating", 'detection', 'performance', 'on', 'clean', "data...')", 'model', '=', 'self.m...
402,067
rifqind/Agent-Programs-3KS1
prefilter.py
PrefilterManager.unregister_handler
unregister_handler
Unregister a handler instance by name with esc_strings.
[ "Unregister", "a", "handler", "instance", "by", "name", "with", "esc_strings." ]
def unregister_handler(self, name, handler, esc_strings): try: del self._handlers[name] except KeyError: pass for esc_str in esc_strings: h = self._esc_handlers.get(esc_str) if h is handler: del self._esc_handlers[esc_str]
['def', 'unregister_handler(self,', 'name,', 'handler,', 'esc_strings):', 'try:', 'del', 'self._handlers[name]', 'except', 'KeyError:', 'pass', 'for', 'esc_str', 'in', 'esc_strings:', 'h', '=', 'self._esc_handlers.get(esc_str)', 'if', 'h', 'is', 'handler:', 'del', 'self._esc_handlers[esc_str]']
41,224
weimin17/Object-Detection_HelmetDetection
rdp_accountant.py
compute_rdp
compute_rdp
Compute RDP of Gaussian mechanism with sampling for given parameters.
[ "Compute", "RDP", "of", "Gaussian", "mechanism", "with", "sampling", "for", "given", "parameters." ]
def compute_rdp(q, sigma, steps, orders): if np.isscalar(orders): rdp = _compute_rdp(q, sigma, orders) else: rdp = np.array([_compute_rdp(q, sigma, order) for order in orders]) return rdp * steps
['def', 'compute_rdp(q,', 'sigma,', 'steps,', 'orders):', 'if', 'np.isscalar(orders):', 'rdp', '=', '_compute_rdp(q,', 'sigma,', 'orders)', 'else:', 'rdp', '=', 'np.array([_compute_rdp(q,', 'sigma,', 'order)', 'for', 'order', 'in', 'orders])', 'return', 'rdp', '*', 'steps']
749,818
MycroftAI/mycroft-core
environment.py
after_scenario
after_scenario
Wait for mycroft completion and reset any changed state.
[ "Wait", "for", "mycroft", "completion", "and", "reset", "any", "changed", "state." ]
def after_scenario(context, scenario): wait_while_speaking() context.bus.clear_all_messages() context.matched_message = None context.step_timeout = 10
['def', 'after_scenario(context,', 'scenario):', 'wait_while_speaking()', 'context.bus.clear_all_messages()', 'context.matched_message', '=', 'None', 'context.step_timeout', '=', '10']
290,840
rdipietro/miccai-2016-surgical-activity-rec
data.py
Dataset.classes
classes
A list of strings: the class names.
[ "A", "list", "of", "strings:", "the", "class", "names." ]
def classes(self): return self.pkl_dict['classes']
['def', 'classes(self):', 'return', "self.pkl_dict['classes']"]
286,326
wandb/wandb
kqueue.py
KeventDescriptorSet.paths
paths
List of paths for which kevents have been created.
[ "List", "of", "paths", "for", "which", "kevents", "have", "been", "created." ]
def paths(self): with self._lock: return list(self._descriptor_for_path.keys())
['def', 'paths(self):', 'with', 'self._lock:', 'return', 'list(self._descriptor_for_path.keys())']
942,170
jesolem/PCV
camera.py
Camera.factor
factor
Factorize the camera matrix into K,R,t as P = K[R|t].
[ "Factorize", "the", "camera", "matrix", "into", "K,R,t", "as", "P", "=", "K[R|t]." ]
def factor(self): (K, R) = linalg.rq(self.P[:, :3]) T = diag(sign(diag(K))) if linalg.det(T) < 0: T[1, 1] *= -1 self.K = dot(K, T) self.R = dot(T, R) self.t = dot(linalg.inv(self.K), self.P[:, 3]) return (self.K, self.R, self.t)
['def', 'factor(self):', '(K,', 'R)', '=', 'linalg.rq(self.P[:,', ':3])', 'T', '=', 'diag(sign(diag(K)))', 'if', 'linalg.det(T)', '<', '0:', 'T[1,', '1]', '*=', '-1', 'self.K', '=', 'dot(K,', 'T)', 'self.R', '=', 'dot(T,', 'R)', 'self.t', '=', 'dot(linalg.inv(self.K),', 'self.P[:,', '3])', 'return', '(self.K,', 'self.R...
765,677
jimtin/Stock_Comparison
ols.py
OLS.rmse
rmse
Returns the rmse value.
[ "Returns", "the", "rmse", "value." ]
def rmse(self): return self._rmse_raw
['def', 'rmse(self):', 'return', 'self._rmse_raw']
388,099
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
logic.py
simp
simp
Simplify the expression x.
[ "Simplify", "the", "expression", "x." ]
def simp(x): if isnumber(x) or not x.args: return x args = list(map(simp, x.args)) (u, op, v) = (args[0], x.op, args[-1]) if op == '+': if v == 0: return u if u == 0: return v if u == v: return 2 * u if u == -v or v == -u: ...
['def', 'simp(x):', 'if', 'isnumber(x)', 'or', 'not', 'x.args:', 'return', 'x', 'args', '=', 'list(map(simp,', 'x.args))', '(u,', 'op,', 'v)', '=', '(args[0],', 'x.op,', 'args[-1])', 'if', 'op', '==', "'+':", 'if', 'v', '==', '0:', 'return', 'u', 'if', 'u', '==', '0:', 'return', 'v', 'if', 'u', '==', 'v:', 'return', '2...
428,070
indrajithi/mgc-django
models.py
Picture.delete
delete
delete -- Remove to leave file.
[ "delete", "--", "Remove", "to", "leave", "file." ]
def delete(self, *args, **kwargs): self.file.delete(False) super(Picture, self).delete(*args, **kwargs)
['def', 'delete(self,', '*args,', '**kwargs):', 'self.file.delete(False)', 'super(Picture,', 'self).delete(*args,', '**kwargs)']
634,944
enuguru/artificial_intelligence_and_machine_
backward.py
byte_to_int
byte_to_int
Turn an element of a bytes object into an int.
[ "Turn", "an", "element", "of", "a", "bytes", "object", "into", "an", "int." ]
def byte_to_int(byte_value): return ord(byte_value)
['def', 'byte_to_int(byte_value):', 'return', 'ord(byte_value)']
157,208
FenHua/Robust_Logo_Detection
cityscapes.py
CityscapesDataset.results2txt
results2txt
Dump the detection results to a txt file.
[ "Dump", "the", "detection", "results", "to", "a", "txt", "file." ]
def results2txt(self, results, outfile_prefix): try: import cityscapesscripts.helpers.labels as CSLabels except ImportError: raise ImportError('Please run "pip install citscapesscripts" to install cityscapesscripts first.') result_files = [] os.makedirs(outfile_prefix, exist_ok=True) ...
['def', 'results2txt(self,', 'results,', 'outfile_prefix):', 'try:', 'import', 'cityscapesscripts.helpers.labels', 'as', 'CSLabels', 'except', 'ImportError:', 'raise', "ImportError('Please", 'run', '"pip', 'install', 'citscapesscripts"', 'to', 'install', 'cityscapesscripts', "first.')", 'result_files', '=', '[]', 'os.m...
826,621
tensorflow/agents
nest_utils.py
stack_nested_arrays
stack_nested_arrays
Stack/batch a list of nested numpy arrays.
[ "Stack/batch", "a", "list", "of", "nested", "numpy", "arrays." ]
def stack_nested_arrays(nested_arrays): nested_arrays_flattened = [tf.nest.flatten(a) for a in nested_arrays] batched_nested_array_flattened = [np.stack(a) for a in zip(*nested_arrays_flattened)] return tf.nest.pack_sequence_as(nested_arrays[0], batched_nested_array_flattened)
['def', 'stack_nested_arrays(nested_arrays):', 'nested_arrays_flattened', '=', '[tf.nest.flatten(a)', 'for', 'a', 'in', 'nested_arrays]', 'batched_nested_array_flattened', '=', '[np.stack(a)', 'for', 'a', 'in', 'zip(*nested_arrays_flattened)]', 'return', 'tf.nest.pack_sequence_as(nested_arrays[0],', 'batched_nested_arr...
23,135
enuguru/artificial_intelligence_and_machine_
python.py
PythonFileReporter.excluded_lines
excluded_lines
Return the line numbers of statements in the file.
[ "Return", "the", "line", "numbers", "of", "statements", "in", "the", "file." ]
def excluded_lines(self): if self._excluded is None: (self._statements, self._excluded) = self.parser.parse_source() return self._excluded
['def', 'excluded_lines(self):', 'if', 'self._excluded', 'is', 'None:', '(self._statements,', 'self._excluded)', '=', 'self.parser.parse_source()', 'return', 'self._excluded']
157,577
Oporto/CS4341_Artificial_Inteligence
dictconfig.py
DictConfigurator.configure_filter
configure_filter
Configure a filter from a dictionary.
[ "Configure", "a", "filter", "from", "a", "dictionary." ]
def configure_filter(self, config): if '()' in config: result = self.configure_custom(config) else: name = config.get('name', '') result = logging.Filter(name) return result
['def', 'configure_filter(self,', 'config):', 'if', "'()'", 'in', 'config:', 'result', '=', 'self.configure_custom(config)', 'else:', 'name', '=', "config.get('name',", "'')", 'result', '=', 'logging.Filter(name)', 'return', 'result']
190,820
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
_DictWrapper.Set
Set
Sets the freq/prob associated with the value x.
[ "Sets", "the", "freq/prob", "associated", "with", "the", "value", "x." ]
def Set(self, x, y=0): self.d[x] = y
['def', 'Set(self,', 'x,', 'y=0):', 'self.d[x]', '=', 'y']
13,081
tungk/OED
seq2seq.py
RLSTMCell.call
call
Long short-term memory cell (LSTM).
[ "Long", "short-term", "memory", "cell", "(LSTM)." ]
def call(self, inputs, state): sigmoid = tf.sigmoid if self._state_is_tuple: (c, h) = state else: (c, h) = tf.split(value=state, num_or_size_splits=2, axis=1) if self._linear is None: self._linear = _Linear([inputs, h], 4 * self._num_units, True) (i, j, f, o) = tf.split(value...
['def', 'call(self,', 'inputs,', 'state):', 'sigmoid', '=', 'tf.sigmoid', 'if', 'self._state_is_tuple:', '(c,', 'h)', '=', 'state', 'else:', '(c,', 'h)', '=', 'tf.split(value=state,', 'num_or_size_splits=2,', 'axis=1)', 'if', 'self._linear', 'is', 'None:', 'self._linear', '=', '_Linear([inputs,', 'h],', '4', '*', 'self...
755,392
flatironinstitute/deepblast
utils.py
clip_boundaries
clip_boundaries
Remove xs and ys from ends.
[ "Remove", "xs", "and", "ys", "from", "ends." ]
def clip_boundaries(X, Y, A, st): if A[0] == m: first = 0 else: first = A.index(m) if A[-1] == m: last = len(A) else: last = len(A) - A[::-1].index(m) (X, Y) = states2alignment(np.array(A), X, Y) X_ = X[first:last].replace('-', '') Y_ = Y[first:last].replace('...
['def', 'clip_boundaries(X,', 'Y,', 'A,', 'st):', 'if', 'A[0]', '==', 'm:', 'first', '=', '0', 'else:', 'first', '=', 'A.index(m)', 'if', 'A[-1]', '==', 'm:', 'last', '=', 'len(A)', 'else:', 'last', '=', 'len(A)', '-', 'A[::-1].index(m)', '(X,', 'Y)', '=', 'states2alignment(np.array(A),', 'X,', 'Y)', 'X_', '=', "X[firs...
520,038
eddylau328/fyp-artificial-intelligence-ac-control-device
credentials.py
Credentials.apply
apply
Apply the token to the authentication header.
[ "Apply", "the", "token", "to", "the", "authentication", "header." ]
def apply(self, headers, token=None): headers['authorization'] = 'Bearer {}'.format(_helpers.from_bytes(token or self.token))
['def', 'apply(self,', 'headers,', 'token=None):', "headers['authorization']", '=', "'Bearer", "{}'.format(_helpers.from_bytes(token", 'or', 'self.token))']
214,535
aws/sagemaker-python-sdk
session.py
Session.create_model_package_from_containers
create_model_package_from_containers
Get request dictionary for CreateModelPackage API.
[ "Get", "request", "dictionary", "for", "CreateModelPackage", "API." ]
def create_model_package_from_containers(self, containers=None, content_types=None, response_types=None, inference_instances=None, transform_instances=None, model_package_name=None, model_package_group_name=None, model_metrics=None, metadata_properties=None, marketplace_cert=False, approval_status='PendingManualApprova...
['def', 'create_model_package_from_containers(self,', 'containers=None,', 'content_types=None,', 'response_types=None,', 'inference_instances=None,', 'transform_instances=None,', 'model_package_name=None,', 'model_package_group_name=None,', 'model_metrics=None,', 'metadata_properties=None,', 'marketplace_cert=False,', ...
829,626
yoonc5536/computer_vision
net_spec.py
to_proto
to_proto
Generate a NetParameter that contains all layers needed to compute all arguments.
[ "Generate", "a", "NetParameter", "that", "contains", "all", "layers", "needed", "to", "compute", "all", "arguments." ]
def to_proto(*tops): if not isinstance(tops, tuple): tops = (tops,) layers = OrderedDict() autonames = {} for top in tops: top.fn._to_proto(layers, {}, autonames) net = caffe_pb2.NetParameter() net.layer.extend(layers.values()) return net
['def', 'to_proto(*tops):', 'if', 'not', 'isinstance(tops,', 'tuple):', 'tops', '=', '(tops,)', 'layers', '=', 'OrderedDict()', 'autonames', '=', '{}', 'for', 'top', 'in', 'tops:', 'top.fn._to_proto(layers,', '{},', 'autonames)', 'net', '=', 'caffe_pb2.NetParameter()', 'net.layer.extend(layers.values())', 'return', 'ne...
472,786
0x5eba/Anime-Character-Generator
utils_.py
hair_grad
hair_grad
Generate image samples with fixed eye class and noise, change hair color.
[ "Generate", "image", "samples", "with", "fixed", "eye", "class", "and", "noise,", "change", "hair", "color." ]
def hair_grad(model, device, latent_dim, hair_classes, eye_classes, sample_dir): eye = torch.zeros(eye_classes).to(device) eye[np.random.randint(eye_classes)] = 1 eye.unsqueeze_(0) z = torch.randn(latent_dim).unsqueeze(0).to(device) img_list = [] for i in range(hair_classes): hair = torc...
['def', 'hair_grad(model,', 'device,', 'latent_dim,', 'hair_classes,', 'eye_classes,', 'sample_dir):', 'eye', '=', 'torch.zeros(eye_classes).to(device)', 'eye[np.random.randint(eye_classes)]', '=', '1', 'eye.unsqueeze_(0)', 'z', '=', 'torch.randn(latent_dim).unsqueeze(0).to(device)', 'img_list', '=', '[]', 'for', 'i', ...
416,294
tobegit3hub/deep_image_model
feature_column.py
_WeightedSparseColumn.insert_transformed_feature
insert_transformed_feature
Inserts a tuple with the id and weight tensors.
[ "Inserts", "a", "tuple", "with", "the", "id", "and", "weight", "tensors." ]
def insert_transformed_feature(self, columns_to_tensors): if self.sparse_id_column not in columns_to_tensors: self.sparse_id_column.insert_transformed_feature(columns_to_tensors) columns_to_tensors[self] = tuple([columns_to_tensors[self.sparse_id_column], columns_to_tensors[self.weight_column_name]])
['def', 'insert_transformed_feature(self,', 'columns_to_tensors):', 'if', 'self.sparse_id_column', 'not', 'in', 'columns_to_tensors:', 'self.sparse_id_column.insert_transformed_feature(columns_to_tensors)', 'columns_to_tensors[self]', '=', 'tuple([columns_to_tensors[self.sparse_id_column],', 'columns_to_tensors[self.we...
181,464
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
base.py
TreeAdaptor.createWithPayload
createWithPayload
Returns a new tree for the calling parser.
[ "Returns", "a", "new", "tree", "for", "the", "calling", "parser." ]
def createWithPayload(self, payload): return LocalTree(payload, self.lexer, self.parser)
['def', 'createWithPayload(self,', 'payload):', 'return', 'LocalTree(payload,', 'self.lexer,', 'self.parser)']
17,486
flow-project/flow
kernel.py
Kernel.pass_api
pass_api
Pass the kernel API to all kernel subclasses.
[ "Pass", "the", "kernel", "API", "to", "all", "kernel", "subclasses." ]
def pass_api(self, kernel_api): self.kernel_api = kernel_api self.simulation.pass_api(kernel_api) self.network.pass_api(kernel_api) self.vehicle.pass_api(kernel_api) self.traffic_light.pass_api(kernel_api)
['def', 'pass_api(self,', 'kernel_api):', 'self.kernel_api', '=', 'kernel_api', 'self.simulation.pass_api(kernel_api)', 'self.network.pass_api(kernel_api)', 'self.vehicle.pass_api(kernel_api)', 'self.traffic_light.pass_api(kernel_api)']
211,570
viko-3/DiffSeqMol
microbatch.py
Batch.tensor
tensor
Retrieves the underlying tensor.
[ "Retrieves", "the", "underlying", "tensor." ]
def tensor(self) -> Tensor: if not self.atomic: raise AttributeError('not atomic batch') return cast(Tensor, self._values)
['def', 'tensor(self)', '->', 'Tensor:', 'if', 'not', 'self.atomic:', 'raise', "AttributeError('not", 'atomic', "batch')", 'return', 'cast(Tensor,', 'self._values)']
551,511
rudranil723/mini-main
regex.py
template
template
Compile a template pattern, returning a pattern object.
[ "Compile", "a", "template", "pattern,", "returning", "a", "pattern", "object." ]
def template(pattern, flags=0): return _compile(pattern, flags | TEMPLATE, False, {}, False)
['def', 'template(pattern,', 'flags=0):', 'return', '_compile(pattern,', 'flags', '|', 'TEMPLATE,', 'False,', '{},', 'False)']
269,775
Alexander-Parker/youtube_nlp
webelement.py
WebElement.size
size
The size of the element.
[ "The", "size", "of", "the", "element." ]
def size(self): size = {} if self._w3c: size = self._execute(Command.GET_ELEMENT_RECT)['value'] else: size = self._execute(Command.GET_ELEMENT_SIZE)['value'] new_size = {'height': size['height'], 'width': size['width']} return new_size
['def', 'size(self):', 'size', '=', '{}', 'if', 'self._w3c:', 'size', '=', "self._execute(Command.GET_ELEMENT_RECT)['value']", 'else:', 'size', '=', "self._execute(Command.GET_ELEMENT_SIZE)['value']", 'new_size', '=', "{'height':", "size['height'],", "'width':", "size['width']}", 'return', 'new_size']
971,028
weimin17/Object-Detection_HelmetDetection
neural_gpu_trainer.py
score_beams_prog
score_beams_prog
Score beams for program synthesis.
[ "Score", "beams", "for", "program", "synthesis." ]
def score_beams_prog(beams, target, inp, history, print_out=False, test_mode=False): tgt_prog = linearize(target, program_utils.prog_vocab, True, 1) hist_progs = [linearize(h, program_utils.prog_vocab, True, 1) for h in history] tgt_set = set(target) if print_out: print('target: ', tgt_prog) ...
['def', 'score_beams_prog(beams,', 'target,', 'inp,', 'history,', 'print_out=False,', 'test_mode=False):', 'tgt_prog', '=', 'linearize(target,', 'program_utils.prog_vocab,', 'True,', '1)', 'hist_progs', '=', '[linearize(h,', 'program_utils.prog_vocab,', 'True,', '1)', 'for', 'h', 'in', 'history]', 'tgt_set', '=', 'set(...
751,404
open-mmlab/mmrotate
rotated_reppoints_head.py
RotatedRepPointsHead.offset_to_pts
offset_to_pts
Change from point offset to point coordinate.
[ "Change", "from", "point", "offset", "to", "point", "coordinate." ]
def offset_to_pts(self, center_list, pred_list): pts_list = [] for (i_lvl, _) in enumerate(self.point_strides): pts_lvl = [] for (i_img, _) in enumerate(center_list): pts_center = center_list[i_img][i_lvl][:, :2].repeat(1, self.num_points) pts_shift = pred_list[i_lvl][i_i...
['def', 'offset_to_pts(self,', 'center_list,', 'pred_list):', 'pts_list', '=', '[]', 'for', '(i_lvl,', '_)', 'in', 'enumerate(self.point_strides):', 'pts_lvl', '=', '[]', 'for', '(i_img,', '_)', 'in', 'enumerate(center_list):', 'pts_center', '=', 'center_list[i_img][i_lvl][:,', ':2].repeat(1,', 'self.num_points)', 'pts...
625,146
Eric3911/OpenAGI
melgan.py
MelGANGenerator.remove_weight_norm
remove_weight_norm
Remove weight normalization module from all of the layers.
[ "Remove", "weight", "normalization", "module", "from", "all", "of", "the", "layers." ]
def remove_weight_norm(self): def _remove_weight_norm(m): try: logging.debug(f'Weight norm is removed from {m}.') torch.nn.utils.remove_weight_norm(m) except ValueError: return self.apply(_remove_weight_norm)
['def', 'remove_weight_norm(self):', 'def', '_remove_weight_norm(m):', 'try:', "logging.debug(f'Weight", 'norm', 'is', 'removed', 'from', "{m}.')", 'torch.nn.utils.remove_weight_norm(m)', 'except', 'ValueError:', 'return', 'self.apply(_remove_weight_norm)']
250,588
matsu0228/nlp-jp
pdf.py
PDFExporter.clean_temp_files
clean_temp_files
Remove temporary files created by xelatex/bibtex.
[ "Remove", "temporary", "files", "created", "by", "xelatex/bibtex." ]
def clean_temp_files(self, filename): self.log.info('Removing temporary LaTeX files') filename = os.path.splitext(filename)[0] for ext in self.temp_file_exts: try: os.remove(filename + ext) except OSError: pass
['def', 'clean_temp_files(self,', 'filename):', "self.log.info('Removing", 'temporary', 'LaTeX', "files')", 'filename', '=', 'os.path.splitext(filename)[0]', 'for', 'ext', 'in', 'self.temp_file_exts:', 'try:', 'os.remove(filename', '+', 'ext)', 'except', 'OSError:', 'pass']
790,127
zhengye1995/underwater-object-detection
train.py
build_optimizer
build_optimizer
Build optimizer from configs.
[ "Build", "optimizer", "from", "configs." ]
def build_optimizer(model, optimizer_cfg): if hasattr(model, 'module'): model = model.module optimizer_cfg = optimizer_cfg.copy() paramwise_options = optimizer_cfg.pop('paramwise_options', None) if paramwise_options is None: return obj_from_dict(optimizer_cfg, torch.optim, dict(params=mo...
['def', 'build_optimizer(model,', 'optimizer_cfg):', 'if', 'hasattr(model,', "'module'):", 'model', '=', 'model.module', 'optimizer_cfg', '=', 'optimizer_cfg.copy()', 'paramwise_options', '=', "optimizer_cfg.pop('paramwise_options',", 'None)', 'if', 'paramwise_options', 'is', 'None:', 'return', 'obj_from_dict(optimizer...
947,704
gunthercox/ChatterBot
auth.py
HTTPDigestAuth.handle_401
handle_401
Takes the given response and tries digest-auth, if needed.
[ "Takes", "the", "given", "response", "and", "tries", "digest-auth,", "if", "needed." ]
def handle_401(self, r, **kwargs): if self.pos is not None: r.request.body.seek(self.pos) num_401_calls = getattr(self, 'num_401_calls', 1) s_auth = r.headers.get('www-authenticate', '') if 'digest' in s_auth.lower() and num_401_calls < 2: setattr(self, 'num_401_calls', num_401_calls + 1...
['def', 'handle_401(self,', 'r,', '**kwargs):', 'if', 'self.pos', 'is', 'not', 'None:', 'r.request.body.seek(self.pos)', 'num_401_calls', '=', 'getattr(self,', "'num_401_calls',", '1)', 's_auth', '=', "r.headers.get('www-authenticate',", "'')", 'if', "'digest'", 'in', 's_auth.lower()', 'and', 'num_401_calls', '<', '2:'...
533,446
QData/deepWordBug
configprovider.py
ScopedConfigProvider.provide
provide
Provide a value from a config file property.
[ "Provide", "a", "value", "from", "a", "config", "file", "property." ]
def provide(self): config = self._session.get_scoped_config() value = config.get(self._config_var_name) return value
['def', 'provide(self):', 'config', '=', 'self._session.get_scoped_config()', 'value', '=', 'config.get(self._config_var_name)', 'return', 'value']
541,225
whatdhack/computer_vision
io.py
Transformer.deprocess
deprocess
Invert Caffe formatting; see preprocess().
[ "Invert", "Caffe", "formatting;", "see", "preprocess()." ]
def deprocess(self, in_, data): self.__check_input(in_) decaf_in = data.copy().squeeze() transpose = self.transpose.get(in_) channel_swap = self.channel_swap.get(in_) raw_scale = self.raw_scale.get(in_) mean = self.mean.get(in_) input_scale = self.input_scale.get(in_) if input_scale is n...
['def', 'deprocess(self,', 'in_,', 'data):', 'self.__check_input(in_)', 'decaf_in', '=', 'data.copy().squeeze()', 'transpose', '=', 'self.transpose.get(in_)', 'channel_swap', '=', 'self.channel_swap.get(in_)', 'raw_scale', '=', 'self.raw_scale.get(in_)', 'mean', '=', 'self.mean.get(in_)', 'input_scale', '=', 'self.inpu...
472,683
rudranil723/mini-main
retry_async.py
AsyncRetry.with_predicate
with_predicate
Return a copy of this retry with the given predicate.
[ "Return", "a", "copy", "of", "this", "retry", "with", "the", "given", "predicate." ]
def with_predicate(self, predicate): return self._replace(predicate=predicate)
['def', 'with_predicate(self,', 'predicate):', 'return', 'self._replace(predicate=predicate)']
317,687
Ruturaj123/Flowchart-Detection
metrics_test.py
MultiLabelSparsePrecisionTest.test_three_labels_at_k5_some_out_of_range
test_three_labels_at_k5_some_out_of_range
Tests that labels outside the [0, n_classes) range are ignored.
[ "Tests", "that", "labels", "outside", "the", "[0,", "n_classes)", "range", "are", "ignored." ]
def test_three_labels_at_k5_some_out_of_range(self): predictions = [[0.5, 0.1, 0.6, 0.3, 0.8, 0.0, 0.7, 0.2, 0.4, 0.9], [0.3, 0.0, 0.7, 0.2, 0.4, 0.9, 0.5, 0.8, 0.1, 0.6]] sp_labels = sparse_tensor.SparseTensorValue(indices=[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3]], values=np.array([2, 7,...
['def', 'test_three_labels_at_k5_some_out_of_range(self):', 'predictions', '=', '[[0.5,', '0.1,', '0.6,', '0.3,', '0.8,', '0.0,', '0.7,', '0.2,', '0.4,', '0.9],', '[0.3,', '0.0,', '0.7,', '0.2,', '0.4,', '0.9,', '0.5,', '0.8,', '0.1,', '0.6]]', 'sp_labels', '=', 'sparse_tensor.SparseTensorValue(indices=[[0,', '0],', '[...
605,636
cheind/gcsl
client.py
VrClient.close
close
Cleans up any resources used by the client.
[ "Cleans", "up", "any", "resources", "used", "by", "the", "client." ]
def close(self): if self._vr_system is not None: openvr.shutdown() self._vr_system = None
['def', 'close(self):', 'if', 'self._vr_system', 'is', 'not', 'None:', 'openvr.shutdown()', 'self._vr_system', '=', 'None']
201,833
open-mmlab/mmtracking
processing.py
TridentSampling.prepare_data
prepare_data
Prepare sampled training data according to the sampled index.
[ "Prepare", "sampled", "training", "data", "according", "to", "the", "sampled", "index." ]
def prepare_data(self, video_info, sampled_inds, with_label=False): extra_infos = {} for (key, info) in video_info.items(): if key in ['bbox_fields', 'mask_fields', 'seg_fields', 'img_prefix']: extra_infos[key] = info bboxes = video_info['bboxes'] results = [] for frame_ind in sa...
['def', 'prepare_data(self,', 'video_info,', 'sampled_inds,', 'with_label=False):', 'extra_infos', '=', '{}', 'for', '(key,', 'info)', 'in', 'video_info.items():', 'if', 'key', 'in', "['bbox_fields',", "'mask_fields',", "'seg_fields',", "'img_prefix']:", 'extra_infos[key]', '=', 'info', 'bboxes', '=', "video_info['bbox...
625,785
stefan-rz/udacity-aind
GameResources.py
load_image
load_image
A better load of images.
[ "A", "better", "load", "of", "images." ]
def load_image(name): fullname = os.path.join('images', name) try: image = pygame.image.load(fullname) if image.get_alpha() == None: image = image.convert() else: image = image.convert_alpha() except pygame.error: print('Oops! Could not load image:', f...
['def', 'load_image(name):', 'fullname', '=', "os.path.join('images',", 'name)', 'try:', 'image', '=', 'pygame.image.load(fullname)', 'if', 'image.get_alpha()', '==', 'None:', 'image', '=', 'image.convert()', 'else:', 'image', '=', 'image.convert_alpha()', 'except', 'pygame.error:', "print('Oops!", 'Could', 'not', 'loa...
427,919
zihuitang/medical_AI_platform
test_pulldom.py
PullDOMTestCase.test_comment
test_comment
PullDOM does not receive "comment" events.
[ "PullDOM", "does", "not", "receive", "\"comment\"", "events." ]
def test_comment(self): items = pulldom.parseString(SMALL_SAMPLE) for (evt, _) in items: if evt == pulldom.COMMENT: break else: self.fail('No comment was encountered')
['def', 'test_comment(self):', 'items', '=', 'pulldom.parseString(SMALL_SAMPLE)', 'for', '(evt,', '_)', 'in', 'items:', 'if', 'evt', '==', 'pulldom.COMMENT:', 'break', 'else:', "self.fail('No", 'comment', 'was', "encountered')"]
283,531
bnpy/bnpy
TestEntropyTargetDataset_Compound.py
MyTestN1K4.setUp
setUp
Create original R and a several compound hard merge proposals.
[ "Create", "original", "R", "and", "a", "several", "compound", "hard", "merge", "proposals." ]
def setUp(self, K=4, N=1, dtargetMinResp=0.01, nMoves=3, Rsource='random'): rng = np.random.RandomState(101) if Rsource == 'random': R = 1.0 / (K - nMoves) + rng.rand(N, K) R[:, -nMoves:] = dtargetMinResp assert R.sum(axis=1).min() > 1.0 elif Rsource == 'toydata': raise NotIm...
['def', 'setUp(self,', 'K=4,', 'N=1,', 'dtargetMinResp=0.01,', 'nMoves=3,', "Rsource='random'):", 'rng', '=', 'np.random.RandomState(101)', 'if', 'Rsource', '==', "'random':", 'R', '=', '1.0', '/', '(K', '-', 'nMoves)', '+', 'rng.rand(N,', 'K)', 'R[:,', '-nMoves:]', '=', 'dtargetMinResp', 'assert', 'R.sum(axis=1).min()...
465,462
PaddlePaddle/Paddle3D
scene_box.py
SceneBox.normalize_positions
normalize_positions
Normalize positions to [0, 1].
[ "Normalize", "positions", "to", "[0,", "1]." ]
def normalize_positions(positions: Union[np.ndarray, paddle.Tensor], aabb: Union[np.ndarray, paddle.Tensor]) -> Union[np.ndarray, paddle.Tensor]: min_xyz = aabb[:3] max_xyz = aabb[3:] return (positions - min_xyz) / (max_xyz - min_xyz)
['def', 'normalize_positions(positions:', 'Union[np.ndarray,', 'paddle.Tensor],', 'aabb:', 'Union[np.ndarray,', 'paddle.Tensor])', '->', 'Union[np.ndarray,', 'paddle.Tensor]:', 'min_xyz', '=', 'aabb[:3]', 'max_xyz', '=', 'aabb[3:]', 'return', '(positions', '-', 'min_xyz)', '/', '(max_xyz', '-', 'min_xyz)']
777,107
jbwang1997/CrossKD
fsaf_head.py
FSAFHead.calculate_pos_recall
calculate_pos_recall
Calculate positive recall with score threshold.
[ "Calculate", "positive", "recall", "with", "score", "threshold." ]
def calculate_pos_recall(self, cls_scores: List[Tensor], labels_list: List[Tensor], pos_inds: List[Tensor]) -> Tensor: with torch.no_grad(): num_class = self.num_classes scores = [cls.permute(0, 2, 3, 1).reshape(-1, num_class)[pos] for (cls, pos) in zip(cls_scores, pos_inds)] labels = [label...
['def', 'calculate_pos_recall(self,', 'cls_scores:', 'List[Tensor],', 'labels_list:', 'List[Tensor],', 'pos_inds:', 'List[Tensor])', '->', 'Tensor:', 'with', 'torch.no_grad():', 'num_class', '=', 'self.num_classes', 'scores', '=', '[cls.permute(0,', '2,', '3,', '1).reshape(-1,', 'num_class)[pos]', 'for', '(cls,', 'pos)...
491,071
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
core.py
UndirectedGraph.targets
targets
Returns all outgoing targets for a vertex.
[ "Returns", "all", "outgoing", "targets", "for", "a", "vertex." ]
def targets(self, v): return self.edges[v]
['def', 'targets(self,', 'v):', 'return', 'self.edges[v]']
18,217
megvii-research/MSCL
base.py
check_flip
check_flip
Check if the origin_imgs are flipped correctly into result_imgs in different flip_types.
[ "Check", "if", "the", "origin_imgs", "are", "flipped", "correctly", "into", "result_imgs", "in", "different", "flip_types." ]
def check_flip(origin_imgs, result_imgs, flip_type): (n, _, _, _) = np.shape(origin_imgs) if flip_type == 'horizontal': for i in range(n): if np.any(result_imgs[i] != np.fliplr(origin_imgs[i])): return False else: for i in range(n): if np.any(result_im...
['def', 'check_flip(origin_imgs,', 'result_imgs,', 'flip_type):', '(n,', '_,', '_,', '_)', '=', 'np.shape(origin_imgs)', 'if', 'flip_type', '==', "'horizontal':", 'for', 'i', 'in', 'range(n):', 'if', 'np.any(result_imgs[i]', '!=', 'np.fliplr(origin_imgs[i])):', 'return', 'False', 'else:', 'for', 'i', 'in', 'range(n):',...
264,977
zackmcnulty/CSE_446-Machine_Learning
image.py
_ImageBase.can_composite
can_composite
Returns `True` if the image can be composited with its neighbors.
[ "Returns", "`True`", "if", "the", "image", "can", "be", "composited", "with", "its", "neighbors." ]
def can_composite(self): trans = self.get_transform() return self._interpolation != 'none' and trans.is_affine and trans.is_separable
['def', 'can_composite(self):', 'trans', '=', 'self.get_transform()', 'return', 'self._interpolation', '!=', "'none'", 'and', 'trans.is_affine', 'and', 'trans.is_separable']
194,422
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
pathlib.py
Path.rename
rename
Rename this path to the given path.
[ "Rename", "this", "path", "to", "the", "given", "path." ]
def rename(self, target): if self._closed: self._raise_closed() self._accessor.rename(self, target)
['def', 'rename(self,', 'target):', 'if', 'self._closed:', 'self._raise_closed()', 'self._accessor.rename(self,', 'target)']
429,087
AISoltani/Improved-speed-boundary-seeking-generative---BGAN-
celeba_mn.py
update_dict_of_lists
update_dict_of_lists
Updates a dict of list with kwargs.
[ "Updates", "a", "dict", "of", "list", "with", "kwargs." ]
def update_dict_of_lists(d_to_update, **d): for (k, v) in d.iteritems(): if k in d_to_update.keys(): d_to_update[k].append(v) else: d_to_update[k] = [v]
['def', 'update_dict_of_lists(d_to_update,', '**d):', 'for', '(k,', 'v)', 'in', 'd.iteritems():', 'if', 'k', 'in', 'd_to_update.keys():', 'd_to_update[k].append(v)', 'else:', 'd_to_update[k]', '=', '[v]']
611,104
mikhaildubov/AST-text-analysis
ast.py
AnnotatedSuffixTree.traverse_depth_first_pre_order
traverse_depth_first_pre_order
Traverses the annotated suffix tree in depth-first pre-order.
[ "Traverses", "the", "annotated", "suffix", "tree", "in", "depth-first", "pre-order." ]
def traverse_depth_first_pre_order(self, callback): self.root.traverse_depth_first_pre_order(callback)
['def', 'traverse_depth_first_pre_order(self,', 'callback):', 'self.root.traverse_depth_first_pre_order(callback)']
402,537
danamyu/hedgehog_detector
model.py
Model.episode_step
episode_step
Performs training steps on episodic input.
[ "Performs", "training", "steps", "on", "episodic", "input." ]
def episode_step(self, sess, x, y, clear_memory=False): outputs = [self.loss, self.gradient_ops] if clear_memory: self.clear_memory(sess) losses = [] for (xx, yy) in zip(x, y): out = sess.run(outputs, feed_dict={self.x: xx, self.y: yy}) loss = out[0] losses.append(loss) ...
['def', 'episode_step(self,', 'sess,', 'x,', 'y,', 'clear_memory=False):', 'outputs', '=', '[self.loss,', 'self.gradient_ops]', 'if', 'clear_memory:', 'self.clear_memory(sess)', 'losses', '=', '[]', 'for', '(xx,', 'yy)', 'in', 'zip(x,', 'y):', 'out', '=', 'sess.run(outputs,', 'feed_dict={self.x:', 'xx,', 'self.y:', 'yy...
589,794
caiiiac/Machine-Learning-with-Python
test_forest.py
check_classification_toy
check_classification_toy
Check classification on a toy dataset.
[ "Check", "classification", "on", "a", "toy", "dataset." ]
def check_classification_toy(name): ForestClassifier = FOREST_CLASSIFIERS[name] clf = ForestClassifier(n_estimators=10, random_state=1) clf.fit(X, y) assert_array_equal(clf.predict(T), true_result) assert_equal(10, len(clf)) clf = ForestClassifier(n_estimators=10, max_features=1, random_state=1)...
['def', 'check_classification_toy(name):', 'ForestClassifier', '=', 'FOREST_CLASSIFIERS[name]', 'clf', '=', 'ForestClassifier(n_estimators=10,', 'random_state=1)', 'clf.fit(X,', 'y)', 'assert_array_equal(clf.predict(T),', 'true_result)', 'assert_equal(10,', 'len(clf))', 'clf', '=', 'ForestClassifier(n_estimators=10,', ...
720,637
nicknochnack/RealTimeSignLanguageTFJS
imagenet_preprocessing.py
input_fn
input_fn
Input function which provides batches for train or eval.
[ "Input", "function", "which", "provides", "batches", "for", "train", "or", "eval." ]
def input_fn(is_training, data_dir, batch_size, dtype=tf.float32, datasets_num_private_threads=None, parse_record_fn=parse_record, input_context=None, drop_remainder=False, tf_data_experimental_slack=False, training_dataset_cache=False, filenames=None): if filenames is None: filenames = get_filenames(is_tra...
['def', 'input_fn(is_training,', 'data_dir,', 'batch_size,', 'dtype=tf.float32,', 'datasets_num_private_threads=None,', 'parse_record_fn=parse_record,', 'input_context=None,', 'drop_remainder=False,', 'tf_data_experimental_slack=False,', 'training_dataset_cache=False,', 'filenames=None):', 'if', 'filenames', 'is', 'Non...
851,233
Eric3911/OpenAGI
helper.py
compression_preparation
compression_preparation
Prepare the compression techniques of a model.
[ "Prepare", "the", "compression", "techniques", "of", "a", "model." ]
def compression_preparation(model, compression_techinique_list, mpu): for (module_name, module) in model.named_modules(): if is_module_compressible(module, mpu): module_replacement(model, module_name, mpu=mpu) for (module_name_lists, _, compression_technique) in compression_techinique_list: ...
['def', 'compression_preparation(model,', 'compression_techinique_list,', 'mpu):', 'for', '(module_name,', 'module)', 'in', 'model.named_modules():', 'if', 'is_module_compressible(module,', 'mpu):', 'module_replacement(model,', 'module_name,', 'mpu=mpu)', 'for', '(module_name_lists,', '_,', 'compression_technique)', 'i...
252,022