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
bhrnjica/ObjectDetection
fp16util.py
model_grads_to_master_grads
model_grads_to_master_grads
Copy model gradients to master gradients.
[ "Copy", "model", "gradients", "to", "master", "gradients." ]
def model_grads_to_master_grads(model_params, master_params, flat_master=False): if flat_master: master_params[0].grad.data.copy_(_flatten_dense_tensors([p.grad.data for p in model_params])) else: for (model, master) in zip(model_params, master_params): if model.grad is not None: ...
['def', 'model_grads_to_master_grads(model_params,', 'master_params,', 'flat_master=False):', 'if', 'flat_master:', 'master_params[0].grad.data.copy_(_flatten_dense_tensors([p.grad.data', 'for', 'p', 'in', 'model_params]))', 'else:', 'for', '(model,', 'master)', 'in', 'zip(model_params,', 'master_params):', 'if', 'mode...
744,392
QinganZhao/Deep-Learning-Based-Structural-Damage-Detection
cpp_lint.py
ProcessFileData
ProcessFileData
Performs lint checks and reports any errors to the given error function.
[ "Performs", "lint", "checks", "and", "reports", "any", "errors", "to", "the", "given", "error", "function." ]
def ProcessFileData(filename, file_extension, lines, error, extra_check_functions=[]): lines = ['// marker so line numbers and indices both start at 1'] + lines + ['// marker so line numbers end in a known way'] include_state = _IncludeState() function_state = _FunctionState() nesting_state = _NestingSt...
['def', 'ProcessFileData(filename,', 'file_extension,', 'lines,', 'error,', 'extra_check_functions=[]):', 'lines', '=', "['//", 'marker', 'so', 'line', 'numbers', 'and', 'indices', 'both', 'start', 'at', "1']", '+', 'lines', '+', "['//", 'marker', 'so', 'line', 'numbers', 'end', 'in', 'a', 'known', "way']", 'include_st...
127,574
neokarn/computer_vision
yacs.py
CfgNode.defrost
defrost
Make this CfgNode and all of its children mutable.
[ "Make", "this", "CfgNode", "and", "all", "of", "its", "children", "mutable." ]
def defrost(self): self._immutable(False)
['def', 'defrost(self):', 'self._immutable(False)']
475,639
rlworkgroup/garage
test_tanh_gaussian_mlp_policy.py
TestTanhGaussianMLPPolicy.test_get_action_np
test_get_action_np
Test Policy get action function with numpy inputs.
[ "Test", "Policy", "get", "action", "function", "with", "numpy", "inputs." ]
def test_get_action_np(self, hidden_sizes): env_spec = GymEnv(DummyBoxEnv()) obs_dim = env_spec.observation_space.flat_dim act_dim = env_spec.action_space.flat_dim obs = np.ones((obs_dim,), dtype=np.float32) init_std = 2.0 policy = TanhGaussianMLPPolicy(env_spec=env_spec, hidden_sizes=hidden_siz...
['def', 'test_get_action_np(self,', 'hidden_sizes):', 'env_spec', '=', 'GymEnv(DummyBoxEnv())', 'obs_dim', '=', 'env_spec.observation_space.flat_dim', 'act_dim', '=', 'env_spec.action_space.flat_dim', 'obs', '=', 'np.ones((obs_dim,),', 'dtype=np.float32)', 'init_std', '=', '2.0', 'policy', '=', 'TanhGaussianMLPPolicy(e...
201,064
xiaoaleiBLUE/computer_vision
util.py
get_keypoints
get_keypoints
Get the COCO keypoints and their left/right flip coorespondence map.
[ "Get", "the", "COCO", "keypoints", "and", "their", "left/right", "flip", "coorespondence", "map." ]
def get_keypoints(): keypoints = ['nose', 'left_eye', 'right_eye', 'left_ear', 'right_ear', 'left_shoulder', 'right_shoulder', 'left_elbow', 'right_elbow', 'left_wrist', 'right_wrist', 'left_hip', 'right_hip', 'left_knee', 'right_knee', 'left_ankle', 'right_ankle'] keypoint_flip_map = {'left_eye': 'right_eye', ...
['def', 'get_keypoints():', 'keypoints', '=', "['nose',", "'left_eye',", "'right_eye',", "'left_ear',", "'right_ear',", "'left_shoulder',", "'right_shoulder',", "'left_elbow',", "'right_elbow',", "'left_wrist',", "'right_wrist',", "'left_hip',", "'right_hip',", "'left_knee',", "'right_knee',", "'left_ankle',", "'right_...
501,705
Shark-NLP/DiffuSeq
nn.py
mean_flat
mean_flat
Take the mean over all non-batch dimensions.
[ "Take", "the", "mean", "over", "all", "non-batch", "dimensions." ]
def mean_flat(tensor): return tensor.mean(dim=list(range(1, len(tensor.shape))))
['def', 'mean_flat(tensor):', 'return', 'tensor.mean(dim=list(range(1,', 'len(tensor.shape))))']
551,683
YiSyuanChen/MTL-ABS
data_builder.py
load_json
load_json
Construct sentences from tokenized json file.
[ "Construct", "sentences", "from", "tokenized", "json", "file." ]
def load_json(p, lower): source = [] tgt = [] flag = False for sent in json.load(open(p))['sentences']: tokens = [t['word'] for t in sent['tokens']] if lower: tokens = [t.lower() for t in tokens] if tokens[0] == '@highlight': flag = True tgt.ap...
['def', 'load_json(p,', 'lower):', 'source', '=', '[]', 'tgt', '=', '[]', 'flag', '=', 'False', 'for', 'sent', 'in', "json.load(open(p))['sentences']:", 'tokens', '=', "[t['word']", 'for', 't', 'in', "sent['tokens']]", 'if', 'lower:', 'tokens', '=', '[t.lower()', 'for', 't', 'in', 'tokens]', 'if', 'tokens[0]', '==', "'...
642,860
AEProgrammer/object_detection
train.py
create_model
create_model
Build the model and look for saved model checkpoints in case we can resume from one.
[ "Build", "the", "model", "and", "look", "for", "saved", "model", "checkpoints", "in", "case", "we", "can", "resume", "from", "one." ]
def create_model(): logger = logging.getLogger(__name__) start_iter = 0 checkpoints = {} output_dir = get_output_dir(cfg.TRAIN.DATASETS, training=True) weights_file = cfg.TRAIN.WEIGHTS if cfg.TRAIN.AUTO_RESUME: final_path = os.path.join(output_dir, 'model_final.pkl') if os.path.e...
['def', 'create_model():', 'logger', '=', 'logging.getLogger(__name__)', 'start_iter', '=', '0', 'checkpoints', '=', '{}', 'output_dir', '=', 'get_output_dir(cfg.TRAIN.DATASETS,', 'training=True)', 'weights_file', '=', 'cfg.TRAIN.WEIGHTS', 'if', 'cfg.TRAIN.AUTO_RESUME:', 'final_path', '=', 'os.path.join(output_dir,', "...
773,660
imoscovitz/wittgenstein
discretize.py
BinTransformer.find_continuous_feats
find_continuous_feats
Return names of df features that seem to be continuous.
[ "Return", "names", "of", "df", "features", "that", "seem", "to", "be", "continuous." ]
def find_continuous_feats(self, df, ignore_feats=[]): if not self.n_discretize_bins: return [] cont_feats = df.select_dtypes(np.number).columns cont_feats = [f for f in cont_feats if len(df[f].unique()) > self.n_discretize_bins] cont_feats = [f for f in cont_feats if f not in ignore_feats] r...
['def', 'find_continuous_feats(self,', 'df,', 'ignore_feats=[]):', 'if', 'not', 'self.n_discretize_bins:', 'return', '[]', 'cont_feats', '=', 'df.select_dtypes(np.number).columns', 'cont_feats', '=', '[f', 'for', 'f', 'in', 'cont_feats', 'if', 'len(df[f].unique())', '>', 'self.n_discretize_bins]', 'cont_feats', '=', '[...
959,890
sek788432/Waymo-2D-Object-Detection
common.py
define_clustering_flags
define_clustering_flags
Define flags for clustering methods.
[ "Define", "flags", "for", "clustering", "methods." ]
def define_clustering_flags(): flags.DEFINE_string('clustering_method', None, 'None (no clustering) or selective_clustering (cluster last three Conv2D layers of the model).')
['def', 'define_clustering_flags():', "flags.DEFINE_string('clustering_method',", 'None,', "'None", '(no', 'clustering)', 'or', 'selective_clustering', '(cluster', 'last', 'three', 'Conv2D', 'layers', 'of', 'the', "model).')"]
973,796
clvrai/spirl
train.py
RLTrainer.generate_rollouts
generate_rollouts
Generate rollouts and save to hdf5 files.
[ "Generate", "rollouts", "and", "save", "to", "hdf5", "files." ]
def generate_rollouts(self): print('Saving {} rollouts to directory {}...'.format(self.args.n_val_samples, self.args.save_dir)) saver = RolloutSaver(self.args.save_dir) n_success = 0 n_total = 0 with self.agent.val_mode(): with torch.no_grad(): for _ in tqdm(range(self.args.n_val...
['def', 'generate_rollouts(self):', "print('Saving", '{}', 'rollouts', 'to', 'directory', "{}...'.format(self.args.n_val_samples,", 'self.args.save_dir))', 'saver', '=', 'RolloutSaver(self.args.save_dir)', 'n_success', '=', '0', 'n_total', '=', '0', 'with', 'self.agent.val_mode():', 'with', 'torch.no_grad():', 'for', '...
896,983
bhateharsh/computer_vision
detection_inference.py
build_input
build_input
Builds the graph's input.
[ "Builds", "the", "graph's", "input." ]
def build_input(tfrecord_paths): filename_queue = tf.train.string_input_producer(tfrecord_paths, shuffle=False, num_epochs=1) tf_record_reader = tf.TFRecordReader() (_, serialized_example_tensor) = tf_record_reader.read(filename_queue) features = tf.parse_single_example(serialized_example_tensor, featur...
['def', 'build_input(tfrecord_paths):', 'filename_queue', '=', 'tf.train.string_input_producer(tfrecord_paths,', 'shuffle=False,', 'num_epochs=1)', 'tf_record_reader', '=', 'tf.TFRecordReader()', '(_,', 'serialized_example_tensor)', '=', 'tf_record_reader.read(filename_queue)', 'features', '=', 'tf.parse_single_example...
506,069
flightstar/Natural-Language-Processing
a2_test.py
TestA2.test_hmm_viterbi
test_hmm_viterbi
Test viterbi algorithm on 'time flies like an arrow' The given model should predict N,V,P,D,N tags.
[ "Test", "viterbi", "algorithm", "on", "'time", "flies", "like", "an", "arrow'", "The", "given", "model", "should", "predict", "N,V,P,D,N", "tags." ]
def test_hmm_viterbi(self): model = HMM() model.states = ['D', 'N', 'P', 'V'] model.start_probas = {'D': 0.3, 'N': 0.4, 'P': 0.1, 'V': 0.2} model.emission_probas = {'D': {'time': 0.0, 'flies': 0.0, 'like': 0.0, 'an': 1.0, 'arrow': 0.0}, 'V': {'time': 0.0, 'flies': 0.5, 'like': 0.5, 'an': 0.0, 'arrow': 0...
['def', 'test_hmm_viterbi(self):', 'model', '=', 'HMM()', 'model.states', '=', "['D',", "'N',", "'P',", "'V']", 'model.start_probas', '=', "{'D':", '0.3,', "'N':", '0.4,', "'P':", '0.1,', "'V':", '0.2}', 'model.emission_probas', '=', "{'D':", "{'time':", '0.0,', "'flies':", '0.0,', "'like':", '0.0,', "'an':", '1.0,', "...
703,612
kornia/kornia
renderer.py
RegularRenderer.forward
forward
Renders 3D regularly sampled points along rays.
[ "Renders", "3D", "regularly", "sampled", "points", "along", "rays." ]
def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor: num_ray_points = points_3d.shape[-2] delta_3d = points_3d.reshape(-1, num_ray_points, 3)[0, 1, :] - points_3d.reshape(-1, num_ray_points, 3)[0, 0, :] delta = torch.linalg.norm(delta_3d, dim=-1) alpha = 1 - torch.exp(-1.0 * ...
['def', 'forward(self,', 'rgbs:', 'Tensor,', 'densities:', 'Tensor,', 'points_3d:', 'Tensor)', '->', 'Tensor:', 'num_ray_points', '=', 'points_3d.shape[-2]', 'delta_3d', '=', 'points_3d.reshape(-1,', 'num_ray_points,', '3)[0,', '1,', ':]', '-', 'points_3d.reshape(-1,', 'num_ray_points,', '3)[0,', '0,', ':]', 'delta', '...
622,263
ripl-org/sockit
__init__.py
parse_job_posting
parse_job_posting
Parse a job posting description.
[ "Parse", "a", "job", "posting", "description." ]
def parse_job_posting(filename, extension=None, prediction=False): nonskills_trie = get_trie('nonskills') skills_trie = get_trie('skills') results = {'NonSkills': [], 'Skills': {}} lines = _extract(filename, extension) if len(lines) == 1: lines = _split_sentences(lines[0]) for line in li...
['def', 'parse_job_posting(filename,', 'extension=None,', 'prediction=False):', 'nonskills_trie', '=', "get_trie('nonskills')", 'skills_trie', '=', "get_trie('skills')", 'results', '=', "{'NonSkills':", '[],', "'Skills':", '{}}', 'lines', '=', '_extract(filename,', 'extension)', 'if', 'len(lines)', '==', '1:', 'lines',...
879,236
ds4dm/learn2branch
model.py
PreNormLayer.stop_updates
stop_updates
Ends pre-training for that layer, and fixes the layers's parameters.
[ "Ends", "pre-training", "for", "that", "layer,", "and", "fixes", "the", "layers's", "parameters." ]
def stop_updates(self): assert self.count > 0 if self.shift is not None: self.shift.assign(-self.avg) if self.scale is not None: self.var = tf.where(tf.equal(self.var, 0), tf.ones_like(self.var), self.var) self.scale.assign(1 / np.sqrt(self.var)) del self.avg, self.var, self.m2, ...
['def', 'stop_updates(self):', 'assert', 'self.count', '>', '0', 'if', 'self.shift', 'is', 'not', 'None:', 'self.shift.assign(-self.avg)', 'if', 'self.scale', 'is', 'not', 'None:', 'self.var', '=', 'tf.where(tf.equal(self.var,', '0),', 'tf.ones_like(self.var),', 'self.var)', 'self.scale.assign(1', '/', 'np.sqrt(self.va...
262,079
Victor-Martinez-Pozos/stacked_capsule_autoencoders
math_ops.py
geometric_transform
geometric_transform
Convers paramer tensor into an affine or similarity transform.
[ "Convers", "paramer", "tensor", "into", "an", "affine", "or", "similarity", "transform." ]
def geometric_transform(pose_tensor, similarity=False, nonlinear=True, as_matrix=False): (scale_x, scale_y, theta, shear, trans_x, trans_y) = tf.split(pose_tensor, 6, -1) if nonlinear: (scale_x, scale_y) = (tf.nn.sigmoid(i) + 0.01 for i in (scale_x, scale_y)) (trans_x, trans_y, shear) = (tf.nn.t...
['def', 'geometric_transform(pose_tensor,', 'similarity=False,', 'nonlinear=True,', 'as_matrix=False):', '(scale_x,', 'scale_y,', 'theta,', 'shear,', 'trans_x,', 'trans_y)', '=', 'tf.split(pose_tensor,', '6,', '-1)', 'if', 'nonlinear:', '(scale_x,', 'scale_y)', '=', '(tf.nn.sigmoid(i)', '+', '0.01', 'for', 'i', 'in', '...
873,316
google-research/batch-ppo
wrappers.py
ExternalProcess.call
call
Asynchronously call a method of the external environment.
[ "Asynchronously", "call", "a", "method", "of", "the", "external", "environment." ]
def call(self, name, *args, **kwargs): payload = (name, args, kwargs) self._conn.send((self._CALL, payload)) return self._receive
['def', 'call(self,', 'name,', '*args,', '**kwargs):', 'payload', '=', '(name,', 'args,', 'kwargs)', 'self._conn.send((self._CALL,', 'payload))', 'return', 'self._receive']
95,059
yongchi1992/NaturalLanguageProcessing
run_pretraining.py
get_next_sentence_output
get_next_sentence_output
Get loss and log probs for the next sentence prediction.
[ "Get", "loss", "and", "log", "probs", "for", "the", "next", "sentence", "prediction." ]
def get_next_sentence_output(bert_config, input_tensor, labels): with tf.variable_scope('cls/seq_relationship'): output_weights = tf.get_variable('output_weights', shape=[2, bert_config.hidden_size], initializer=modeling.create_initializer(bert_config.initializer_range)) output_bias = tf.get_variabl...
['def', 'get_next_sentence_output(bert_config,', 'input_tensor,', 'labels):', 'with', "tf.variable_scope('cls/seq_relationship'):", 'output_weights', '=', "tf.get_variable('output_weights',", 'shape=[2,', 'bert_config.hidden_size],', 'initializer=modeling.create_initializer(bert_config.initializer_range))', 'output_bia...
798,732
suarez12138/AI-Reversi_IMP_TextDichotomy
colorbar.py
ColorbarBase.set_label_text
set_label_text
Label the long axis of the colorbar.
[ "Label", "the", "long", "axis", "of", "the", "colorbar." ]
def set_label_text(self, label, **kw): self._label = label self._labelkw = kw self._set_label_text()
['def', 'set_label_text(self,', 'label,', '**kw):', 'self._label', '=', 'label', 'self._labelkw', '=', 'kw', 'self._set_label_text()']
97,490
aeon-toolkit/aeon
test_rocket.py
test_rocket
test_rocket
Test correct rocket variant is selected.
[ "Test", "correct", "rocket", "variant", "is", "selected." ]
def test_rocket(): (X_train, y_train) = make_2d_test_data(n_cases=20, n_timepoints=50) rocket = RocketClassifier(num_kernels=20) rocket.fit(X_train, y_train) assert isinstance(rocket._transformer, Rocket) rocket = RocketClassifier(num_kernels=100, rocket_transform='minirocket', max_dilations_per_ker...
['def', 'test_rocket():', '(X_train,', 'y_train)', '=', 'make_2d_test_data(n_cases=20,', 'n_timepoints=50)', 'rocket', '=', 'RocketClassifier(num_kernels=20)', 'rocket.fit(X_train,', 'y_train)', 'assert', 'isinstance(rocket._transformer,', 'Rocket)', 'rocket', '=', 'RocketClassifier(num_kernels=100,', "rocket_transform...
399,217
Farama-Foundation/Minari
setup.py
get_version
get_version
Gets the Minari version.
[ "Gets", "the", "Minari", "version." ]
def get_version(): path = CWD / 'minari' / '__init__.py' content = path.read_text() for line in content.splitlines(): if line.startswith('__version__'): return line.strip().split()[-1].strip().strip('"') raise RuntimeError('bad version data in __init__.py')
['def', 'get_version():', 'path', '=', 'CWD', '/', "'minari'", '/', "'__init__.py'", 'content', '=', 'path.read_text()', 'for', 'line', 'in', 'content.splitlines():', 'if', "line.startswith('__version__'):", 'return', 'line.strip().split()[-1].strip().strip(\'"\')', 'raise', "RuntimeError('bad", 'version', 'data', 'in'...
670,477
intra2net/guibot
test_region_expect.py
RegionTest.test_find_guess_target_steps
test_find_guess_target_steps
Test target guess from data file extension (target has no match config).
[ "Test", "target", "guess", "from", "data", "file", "extension", "(target", "has", "no", "match", "config)." ]
def test_find_guess_target_steps(self): self.show_image('all_shapes') imgroot = os.path.join(common_test.unittest_dir, 'images') self.assertFalse(os.path.exists(os.path.join(imgroot, 'circle.match'))) self.assertTrue(os.path.exists(os.path.join(imgroot, 'circle.steps'))) self.region.find('circle') ...
['def', 'test_find_guess_target_steps(self):', "self.show_image('all_shapes')", 'imgroot', '=', 'os.path.join(common_test.unittest_dir,', "'images')", 'self.assertFalse(os.path.exists(os.path.join(imgroot,', "'circle.match')))", 'self.assertTrue(os.path.exists(os.path.join(imgroot,', "'circle.steps')))", "self.region.f...
572,682
devashish-patel/webcam-motion-detector
libpython.py
PythonCodeExecutor.xdecref
xdecref
Decrement the reference count of a Python object in the inferior.
[ "Decrement", "the", "reference", "count", "of", "a", "Python", "object", "in", "the", "inferior." ]
def xdecref(self, pointer): gdb.parse_and_eval('Py_DecRef((PyObject *) %d)' % pointer)
['def', 'xdecref(self,', 'pointer):', "gdb.parse_and_eval('Py_DecRef((PyObject", '*)', "%d)'", '%', 'pointer)']
977,614
deepmind/acme
distributional.py
categorical
categorical
Implements the Categorical Distributional TD(0)-learning loss.
[ "Implements", "the", "Categorical", "Distributional", "TD(0)-learning", "loss." ]
def categorical(q_tm1: networks.DiscreteValuedDistribution, r_t: tf.Tensor, d_t: tf.Tensor, q_t: networks.DiscreteValuedDistribution) -> tf.Tensor: z_t = tf.reshape(r_t, (-1, 1)) + tf.reshape(d_t, (-1, 1)) * q_t.values p_t = tf.nn.softmax(q_t.logits) target = tf.stop_gradient(l2_project(z_t, p_t, q_t.values...
['def', 'categorical(q_tm1:', 'networks.DiscreteValuedDistribution,', 'r_t:', 'tf.Tensor,', 'd_t:', 'tf.Tensor,', 'q_t:', 'networks.DiscreteValuedDistribution)', '->', 'tf.Tensor:', 'z_t', '=', 'tf.reshape(r_t,', '(-1,', '1))', '+', 'tf.reshape(d_t,', '(-1,', '1))', '*', 'q_t.values', 'p_t', '=', 'tf.nn.softmax(q_t.log...
8,404
sek788432/Waymo-2D-Object-Detection
target_assigner_test.py
CenterNetBoxTargetAssignerTest.test_max_distance_for_overlap_centernet
test_max_distance_for_overlap_centernet
Test the version of the function used in the CenterNet paper.
[ "Test", "the", "version", "of", "the", "function", "used", "in", "the", "CenterNet", "paper." ]
def test_max_distance_for_overlap_centernet(self): def graph_fn(): distance = targetassigner.max_distance_for_overlap(10, 5, 0.5) return distance distance = self.execute(graph_fn, []) self.assertAlmostEqual(2.807764064, distance)
['def', 'test_max_distance_for_overlap_centernet(self):', 'def', 'graph_fn():', 'distance', '=', 'targetassigner.max_distance_for_overlap(10,', '5,', '0.5)', 'return', 'distance', 'distance', '=', 'self.execute(graph_fn,', '[])', 'self.assertAlmostEqual(2.807764064,', 'distance)']
974,927
rishab-sharma/object_detection
np_box_list_ops.py
scale
scale
Scale box coordinates in x and y dimensions.
[ "Scale", "box", "coordinates", "in", "x", "and", "y", "dimensions." ]
def scale(boxlist, y_scale, x_scale): (y_min, x_min, y_max, x_max) = np.array_split(boxlist.get(), 4, axis=1) y_min = y_scale * y_min y_max = y_scale * y_max x_min = x_scale * x_min x_max = x_scale * x_max scaled_boxlist = np_box_list.BoxList(np.hstack([y_min, x_min, y_max, x_max])) fields =...
['def', 'scale(boxlist,', 'y_scale,', 'x_scale):', '(y_min,', 'x_min,', 'y_max,', 'x_max)', '=', 'np.array_split(boxlist.get(),', '4,', 'axis=1)', 'y_min', '=', 'y_scale', '*', 'y_min', 'y_max', '=', 'y_scale', '*', 'y_max', 'x_min', '=', 'x_scale', '*', 'x_min', 'x_max', '=', 'x_scale', '*', 'x_max', 'scaled_boxlist',...
793,252
google-research/scenic
pretrain.py
get_config
get_config
Returns the ViT experiment configuration for ImageNet.
[ "Returns", "the", "ViT", "experiment", "configuration", "for", "ImageNet." ]
def get_config(runlocal=''): runlocal = bool(runlocal) config = ml_collections.ConfigDict() config.experiment_name = 'imagenet-mae-vit' config.dataset_name = 'bit' config.data_dtype_str = 'float32' config.dataset_configs = ml_collections.ConfigDict() config.dataset_configs.dataset = 'imagene...
['def', "get_config(runlocal=''):", 'runlocal', '=', 'bool(runlocal)', 'config', '=', 'ml_collections.ConfigDict()', 'config.experiment_name', '=', "'imagenet-mae-vit'", 'config.dataset_name', '=', "'bit'", 'config.data_dtype_str', '=', "'float32'", 'config.dataset_configs', '=', 'ml_collections.ConfigDict()', 'config....
846,476
shengwenliang/lpcvc2020_water
efficientnet_condconv_builder.py
build_model
build_model
A helper functiion to creates a model and returns predicted logits.
[ "A", "helper", "functiion", "to", "creates", "a", "model", "and", "returns", "predicted", "logits." ]
def build_model(images, model_name, training, override_params=None, model_dir=None, fine_tuning=False): assert isinstance(images, tf.Tensor) if not training or fine_tuning: if not override_params: override_params = {} override_params['batch_norm'] = utils.BatchNormalization (bloc...
['def', 'build_model(images,', 'model_name,', 'training,', 'override_params=None,', 'model_dir=None,', 'fine_tuning=False):', 'assert', 'isinstance(images,', 'tf.Tensor)', 'if', 'not', 'training', 'or', 'fine_tuning:', 'if', 'not', 'override_params:', 'override_params', '=', '{}', "override_params['batch_norm']", '=', ...
615,886
PacktPublishing/Hands-On-Artificial--for-Banking
test_arraypad.py
test_memory_layout_persistence
test_memory_layout_persistence
Test if C and F order is preserved for all pad modes.
[ "Test", "if", "C", "and", "F", "order", "is", "preserved", "for", "all", "pad", "modes." ]
def test_memory_layout_persistence(mode): x = np.ones((5, 10), order='C') assert np.pad(x, 5, mode).flags['C_CONTIGUOUS'] x = np.ones((5, 10), order='F') assert np.pad(x, 5, mode).flags['F_CONTIGUOUS']
['def', 'test_memory_layout_persistence(mode):', 'x', '=', 'np.ones((5,', '10),', "order='C')", 'assert', 'np.pad(x,', '5,', "mode).flags['C_CONTIGUOUS']", 'x', '=', 'np.ones((5,', '10),', "order='F')", 'assert', 'np.pad(x,', '5,', "mode).flags['F_CONTIGUOUS']"]
235,674
lhotse-speech/lhotse
tar.py
parse_tarinfo
parse_tarinfo
Parse a tarinfo object and return the data it points to as well as the internal path.
[ "Parse", "a", "tarinfo", "object", "and", "return", "the", "data", "it", "points", "to", "as", "well", "as", "the", "internal", "path." ]
def parse_tarinfo(tarinfo: tarfile.TarInfo, tar_file: tarfile.TarFile) -> Tuple[Optional[bytes], Path]: path = Path(tarinfo.path) if path.suffix == '.nodata' or path.suffix == '.nometa': return (None, path) data = tar_file.extractfile(tarinfo).read() return (data, path)
['def', 'parse_tarinfo(tarinfo:', 'tarfile.TarInfo,', 'tar_file:', 'tarfile.TarFile)', '->', 'Tuple[Optional[bytes],', 'Path]:', 'path', '=', 'Path(tarinfo.path)', 'if', 'path.suffix', '==', "'.nodata'", 'or', 'path.suffix', '==', "'.nometa':", 'return', '(None,', 'path)', 'data', '=', 'tar_file.extractfile(tarinfo).re...
601,032
PaddlePaddle/PaddleSpeech
fastspeech2midi.py
FastSpeech2MIDI.inference
inference
Generate the sequence of features given the sequences of characters.
[ "Generate", "the", "sequence", "of", "features", "given", "the", "sequences", "of", "characters." ]
def inference(self, text: paddle.Tensor, note: paddle.Tensor, note_dur: paddle.Tensor, is_slur: paddle.Tensor, durations: paddle.Tensor=None, pitch: paddle.Tensor=None, energy: paddle.Tensor=None, alpha: float=1.0, use_teacher_forcing: bool=False, spk_emb=None, spk_id=None) -> Tuple[paddle.Tensor, paddle.Tensor, paddle...
['def', 'inference(self,', 'text:', 'paddle.Tensor,', 'note:', 'paddle.Tensor,', 'note_dur:', 'paddle.Tensor,', 'is_slur:', 'paddle.Tensor,', 'durations:', 'paddle.Tensor=None,', 'pitch:', 'paddle.Tensor=None,', 'energy:', 'paddle.Tensor=None,', 'alpha:', 'float=1.0,', 'use_teacher_forcing:', 'bool=False,', 'spk_emb=No...
277,191
Eric3911/OpenAGI
test_wav.py
DeepSpeech2Tester_hub.setup_output_dir
setup_output_dir
Create a directory used for output.
[ "Create", "a", "directory", "used", "for", "output." ]
def setup_output_dir(self): if self.args.output: output_dir = Path(self.args.output).expanduser() output_dir.mkdir(parents=True, exist_ok=True) else: output_dir = Path(self.args.checkpoint_path).expanduser().parent.parent output_dir.mkdir(parents=True, exist_ok=True) self.out...
['def', 'setup_output_dir(self):', 'if', 'self.args.output:', 'output_dir', '=', 'Path(self.args.output).expanduser()', 'output_dir.mkdir(parents=True,', 'exist_ok=True)', 'else:', 'output_dir', '=', 'Path(self.args.checkpoint_path).expanduser().parent.parent', 'output_dir.mkdir(parents=True,', 'exist_ok=True)', 'self....
251,215
ryu-ed/SpaceInvaders_Ros
scrap_test.py
ScrapModuleTest.test_get__owned_empty_type
test_get__owned_empty_type
Ensures get works when there is no data of the requested type in the clipboard and the clipboard is owned by the pygame application.
[ "Ensures", "get", "works", "when", "there", "is", "no", "data", "of", "the", "requested", "type", "in", "the", "clipboard", "and", "the", "clipboard", "is", "owned", "by", "the", "pygame", "application." ]
def test_get__owned_empty_type(self): DATA_TYPE = 'test_get__owned_empty_type' if scrap.lost(): scrap.put(pygame.SCRAP_TEXT, b'text to clipboard') if scrap.lost(): self.skipTest('requires the pygame application to own the clipboard') data = scrap.get(DATA_TYPE) self.assertIsN...
['def', 'test_get__owned_empty_type(self):', 'DATA_TYPE', '=', "'test_get__owned_empty_type'", 'if', 'scrap.lost():', 'scrap.put(pygame.SCRAP_TEXT,', "b'text", 'to', "clipboard')", 'if', 'scrap.lost():', "self.skipTest('requires", 'the', 'pygame', 'application', 'to', 'own', 'the', "clipboard')", 'data', '=', 'scrap.ge...
369,145
alinlab/ifseg
progress_bar.py
TensorboardProgressBarWrapper.log
log
Log intermediate stats to tensorboard.
[ "Log", "intermediate", "stats", "to", "tensorboard." ]
def log(self, stats, tag=None, step=None): self._log_to_tensorboard(stats, tag, step) self.wrapped_bar.log(stats, tag=tag, step=step)
['def', 'log(self,', 'stats,', 'tag=None,', 'step=None):', 'self._log_to_tensorboard(stats,', 'tag,', 'step)', 'self.wrapped_bar.log(stats,', 'tag=tag,', 'step=step)']
598,113
Westlake-AI/openmixup
mvit.py
attention_pool
attention_pool
Pooling the feature tokens.
[ "Pooling", "the", "feature", "tokens." ]
def attention_pool(x: torch.Tensor, pool: nn.Module, in_size: tuple, norm: Optional[nn.Module]=None): ndim = x.ndim if ndim == 4: (B, num_heads, L, C) = x.shape elif ndim == 3: num_heads = 1 (B, L, C) = x.shape else: raise RuntimeError(f'Unsupported input dimension {x.sha...
['def', 'attention_pool(x:', 'torch.Tensor,', 'pool:', 'nn.Module,', 'in_size:', 'tuple,', 'norm:', 'Optional[nn.Module]=None):', 'ndim', '=', 'x.ndim', 'if', 'ndim', '==', '4:', '(B,', 'num_heads,', 'L,', 'C)', '=', 'x.shape', 'elif', 'ndim', '==', '3:', 'num_heads', '=', '1', '(B,', 'L,', 'C)', '=', 'x.shape', 'else:...
252,407
JonasLandman/QCNN
ipaddress.py
_BaseNetwork.overlaps
overlaps
Tell if self is partly contained in other.
[ "Tell", "if", "self", "is", "partly", "contained", "in", "other." ]
def overlaps(self, other): return self.network_address in other or (self.broadcast_address in other or (other.network_address in self or other.broadcast_address in self))
['def', 'overlaps(self,', 'other):', 'return', 'self.network_address', 'in', 'other', 'or', '(self.broadcast_address', 'in', 'other', 'or', '(other.network_address', 'in', 'self', 'or', 'other.broadcast_address', 'in', 'self))']
303,053
ADLab3Ds/TiG-BEV
cam_box3d.py
CameraInstance3DBoxes.rotate
rotate
Rotate boxes with points (optional) with the given angle or rotation matrix.
[ "Rotate", "boxes", "with", "points", "(optional)", "with", "the", "given", "angle", "or", "rotation", "matrix." ]
def rotate(self, angle, points=None): if not isinstance(angle, torch.Tensor): angle = self.tensor.new_tensor(angle) assert angle.shape == torch.Size([3, 3]) or angle.numel() == 1, f'invalid rotation angle shape {angle.shape}' if angle.numel() == 1: rot_sin = torch.sin(angle) rot_cos ...
['def', 'rotate(self,', 'angle,', 'points=None):', 'if', 'not', 'isinstance(angle,', 'torch.Tensor):', 'angle', '=', 'self.tensor.new_tensor(angle)', 'assert', 'angle.shape', '==', 'torch.Size([3,', '3])', 'or', 'angle.numel()', '==', '1,', "f'invalid", 'rotation', 'angle', 'shape', "{angle.shape}'", 'if', 'angle.numel...
916,763
danamyu/hedgehog_detector
sequence_layers.py
SequenceLayerBase.get_input
get_input
A wrapper for get_train_input and get_eval_input.
[ "A", "wrapper", "for", "get_train_input", "and", "get_eval_input." ]
def get_input(self, prev, i): if self.is_training(): return self.get_train_input(prev, i) else: return self.get_eval_input(prev, i)
['def', 'get_input(self,', 'prev,', 'i):', 'if', 'self.is_training():', 'return', 'self.get_train_input(prev,', 'i)', 'else:', 'return', 'self.get_eval_input(prev,', 'i)']
589,268
clvrai/spirl
environment.py
BaseEnvironment.reset
reset
Resets all internal variables of the environment.
[ "Resets", "all", "internal", "variables", "of", "the", "environment." ]
def reset(self): raise NotImplementedError
['def', 'reset(self):', 'raise', 'NotImplementedError']
897,009
yinyunie/ScenePriors
test_points_to_volumes.py
TestRawFunction.single_point
single_point
Check the outcome of _points_to_volumes where a single point exists which lines up with a single voxel.
[ "Check", "the", "outcome", "of", "_points_to_volumes", "where", "a", "single", "point", "exists", "which", "lines", "up", "with", "a", "single", "voxel." ]
def single_point(self, device, splat: bool, align_corners: bool): (D, H, W) = (6, 6, 11) if align_corners else (5, 5, 10) (N, C, P) = (1, 1, 1) if align_corners: points_3d = torch.tensor([[[-0.2, 0.2, -0.2]]], device=device) else: points_3d = torch.tensor([[[-0.3, 0.4, -0.4]]], device=de...
['def', 'single_point(self,', 'device,', 'splat:', 'bool,', 'align_corners:', 'bool):', '(D,', 'H,', 'W)', '=', '(6,', '6,', '11)', 'if', 'align_corners', 'else', '(5,', '5,', '10)', '(N,', 'C,', 'P)', '=', '(1,', '1,', '1)', 'if', 'align_corners:', 'points_3d', '=', 'torch.tensor([[[-0.2,', '0.2,', '-0.2]]],', 'device...
330,076
wuzheng-sjtu/FastFPN
gprof2dot.py
AXEParser.translate
translate
Extract a structure from a match object, while translating the types in the process.
[ "Extract", "a", "structure", "from", "a", "match", "object,", "while", "translating", "the", "types", "in", "the", "process." ]
def translate(self, mo): attrs = {} groupdict = mo.groupdict() for (name, value) in compat_iteritems(groupdict): if value is None: value = None elif self._int_re.match(value): value = int(value) elif self._float_re.match(value): value = float(value...
['def', 'translate(self,', 'mo):', 'attrs', '=', '{}', 'groupdict', '=', 'mo.groupdict()', 'for', '(name,', 'value)', 'in', 'compat_iteritems(groupdict):', 'if', 'value', 'is', 'None:', 'value', '=', 'None', 'elif', 'self._int_re.match(value):', 'value', '=', 'int(value)', 'elif', 'self._float_re.match(value):', 'value...
559,730
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
Hist.Freqs
Freqs
Gets frequencies for a sequence of values.
[ "Gets", "frequencies", "for", "a", "sequence", "of", "values." ]
def Freqs(self, xs): return [self.Freq(x) for x in xs]
['def', 'Freqs(self,', 'xs):', 'return', '[self.Freq(x)', 'for', 'x', 'in', 'xs]']
13,452
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
input_data.py
DataSet.next_batch
next_batch
Return the next `batch_size` examples from this data set.
[ "Return", "the", "next", "`batch_size`", "examples", "from", "this", "data", "set." ]
def next_batch(self, batch_size, fake_data=False): if fake_data: fake_image = [1.0 for _ in xrange(784)] fake_label = 0 return ([fake_image for _ in xrange(batch_size)], [fake_label for _ in xrange(batch_size)]) start = self._index_in_epoch self._index_in_epoch += batch_size if s...
['def', 'next_batch(self,', 'batch_size,', 'fake_data=False):', 'if', 'fake_data:', 'fake_image', '=', '[1.0', 'for', '_', 'in', 'xrange(784)]', 'fake_label', '=', '0', 'return', '([fake_image', 'for', '_', 'in', 'xrange(batch_size)],', '[fake_label', 'for', '_', 'in', 'xrange(batch_size)])', 'start', '=', 'self._index...
9,020
mseg-dataset/mseg-semantic
inference_task.py
InferenceTask.render_single_img_pred
render_single_img_pred
Since overlaid class text is difficult to read below 1080p, we upsample predictions.
[ "Since", "overlaid", "class", "text", "is", "difficult", "to", "read", "below", "1080p,", "we", "upsample", "predictions." ]
def render_single_img_pred(self, min_resolution: int=1080) -> None: in_fname_stem = Path(self.input_file).stem output_gray_fpath = f'{in_fname_stem}_gray.jpg' output_demo_fpath = f'{in_fname_stem}_overlaid_classes.jpg' logger.info(f'Write image prediction to {output_demo_fpath}') rgb_img = imread_rg...
['def', 'render_single_img_pred(self,', 'min_resolution:', 'int=1080)', '->', 'None:', 'in_fname_stem', '=', 'Path(self.input_file).stem', 'output_gray_fpath', '=', "f'{in_fname_stem}_gray.jpg'", 'output_demo_fpath', '=', "f'{in_fname_stem}_overlaid_classes.jpg'", "logger.info(f'Write", 'image', 'prediction', 'to', "{o...
642,445
tensorly/quantum
tfq_ps_util_ops_test.py
PSWeightsFromSymbolTest.test_many_values
test_many_values
Ensure that padding with few symbols and many values works.
[ "Ensure", "that", "padding", "with", "few", "symbols", "and", "many", "values", "works." ]
def test_many_values(self): bit = cirq.LineQubit(1) circuits = [cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('alpha') * 2.0), cirq.Y(bit) ** (sympy.Symbol('alpha') * 3.0), cirq.Z(bit) ** sympy.Symbol('alpha'), cirq.X(bit) ** (sympy.Symbol('alpha') * 4.0)), cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('alpha') * 9.0))...
['def', 'test_many_values(self):', 'bit', '=', 'cirq.LineQubit(1)', 'circuits', '=', '[cirq.Circuit(cirq.X(bit)', '**', "(sympy.Symbol('alpha')", '*', '2.0),', 'cirq.Y(bit)', '**', "(sympy.Symbol('alpha')", '*', '3.0),', 'cirq.Z(bit)', '**', "sympy.Symbol('alpha'),", 'cirq.X(bit)', '**', "(sympy.Symbol('alpha')", '*', ...
834,694
Trusted-AI/AIF360
classification_metric.py
ClassificationMetric.true_positive_rate
true_positive_rate
Return the ratio of true positives to positive examples in the dataset, :math:`TPR = TP/P`, optionally conditioned on protected attributes.
[ "Return", "the", "ratio", "of", "true", "positives", "to", "positive", "examples", "in", "the", "dataset,", ":math:`TPR", "=", "TP/P`,", "optionally", "conditioned", "on", "protected", "attributes." ]
def true_positive_rate(self, privileged=None): return self.performance_measures(privileged=privileged)['TPR']
['def', 'true_positive_rate(self,', 'privileged=None):', 'return', "self.performance_measures(privileged=privileged)['TPR']"]
412,325
sarnsdev/social-alignment-data-mining
test_iforest.py
test_iforest_sparse
test_iforest_sparse
Check IForest for various parameter settings on sparse input.
[ "Check", "IForest", "for", "various", "parameter", "settings", "on", "sparse", "input." ]
def test_iforest_sparse(): rng = check_random_state(0) (X_train, X_test, y_train, y_test) = train_test_split(boston.data[:50], boston.target[:50], random_state=rng) grid = ParameterGrid({'max_samples': [0.5, 1.0], 'bootstrap': [True, False]}) for sparse_format in [csc_matrix, csr_matrix]: X_trai...
['def', 'test_iforest_sparse():', 'rng', '=', 'check_random_state(0)', '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(boston.data[:50],', 'boston.target[:50],', 'random_state=rng)', 'grid', '=', "ParameterGrid({'max_samples':", '[0.5,', '1.0],', "'bootstrap':", '[True,', 'False]})', 'for', 'spars...
391,934
Trusted-AI/AIF360
mdss_classification_metric.py
MDSSClassificationMetric.score_groups
score_groups
Compute the bias score for a prespecified group of records.
[ "Compute", "the", "bias", "score", "for", "a", "prespecified", "group", "of", "records." ]
def score_groups(self, privileged=True, penalty=1e-17): groups = self.privileged_groups if privileged else self.unprivileged_groups subset = dict() for g in groups: for (k, v) in g.items(): if k in subset.keys(): subset[k].append(v) else: subse...
['def', 'score_groups(self,', 'privileged=True,', 'penalty=1e-17):', 'groups', '=', 'self.privileged_groups', 'if', 'privileged', 'else', 'self.unprivileged_groups', 'subset', '=', 'dict()', 'for', 'g', 'in', 'groups:', 'for', '(k,', 'v)', 'in', 'g.items():', 'if', 'k', 'in', 'subset.keys():', 'subset[k].append(v)', 'e...
412,364
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
shor.py
run_shor
run_shor
Runs the quantum subroutine of Shor's algorithm for factoring.
[ "Runs", "the", "quantum", "subroutine", "of", "Shor's", "algorithm", "for", "factoring." ]
def run_shor(eng, N, a, verbose=False): n = int(math.ceil(math.log(N, 2))) x = eng.allocate_qureg(n) X | x[0] measurements = [0] * (2 * n) ctrl_qubit = eng.allocate_qubit() for k in range(2 * n): current_a = pow(a, 1 << 2 * n - 1 - k, N) H | ctrl_qubit with Control(eng, c...
['def', 'run_shor(eng,', 'N,', 'a,', 'verbose=False):', 'n', '=', 'int(math.ceil(math.log(N,', '2)))', 'x', '=', 'eng.allocate_qureg(n)', 'X', '|', 'x[0]', 'measurements', '=', '[0]', '*', '(2', '*', 'n)', 'ctrl_qubit', '=', 'eng.allocate_qubit()', 'for', 'k', 'in', 'range(2', '*', 'n):', 'current_a', '=', 'pow(a,', '1...
20,022
facebookresearch/CompilerGym
gcc_env.py
GccEnv.source
source
Get the source code.
[ "Get", "the", "source", "code." ]
def source(self) -> str: return self.observation['source']
['def', 'source(self)', '->', 'str:', 'return', "self.observation['source']"]
125,457
clw5180/remote_sensing_object_detection_2019
polygon_wrapper.py
area_of_intersection
area_of_intersection
This helper calculates the area of intersection.
[ "This", "helper", "calculates", "the", "area", "of", "intersection." ]
def area_of_intersection(det_x, det_y, gt_x, gt_y): if approx_area_of_intersection(det_x, det_y, gt_x, gt_y) > 1: ymax = np.maximum(np.max(det_y), np.max(gt_y)) + 1 xmax = np.maximum(np.max(det_x), np.max(gt_x)) + 1 bin_mask = np.zeros((ymax, xmax)) det_bin_mask = np.zeros_like(bin_m...
['def', 'area_of_intersection(det_x,', 'det_y,', 'gt_x,', 'gt_y):', 'if', 'approx_area_of_intersection(det_x,', 'det_y,', 'gt_x,', 'gt_y)', '>', '1:', 'ymax', '=', 'np.maximum(np.max(det_y),', 'np.max(gt_y))', '+', '1', 'xmax', '=', 'np.maximum(np.max(det_x),', 'np.max(gt_x))', '+', '1', 'bin_mask', '=', 'np.zeros((yma...
840,057
weimin17/Object-Detection_HelmetDetection
neural_gpu_trainer.py
print_vectors
print_vectors
Print vectors from the given variable.
[ "Print", "vectors", "from", "the", "given", "variable." ]
def print_vectors(embedding_key, vocab_path, word_vector_file): (_, rev_vocab) = wmt.initialize_vocabulary(vocab_path) vectors_variable = [v for v in tf.trainable_variables() if embedding_key == v.name] if len(vectors_variable) != 1: data.print_out('Word vector variable not found or too many.') ...
['def', 'print_vectors(embedding_key,', 'vocab_path,', 'word_vector_file):', '(_,', 'rev_vocab)', '=', 'wmt.initialize_vocabulary(vocab_path)', 'vectors_variable', '=', '[v', 'for', 'v', 'in', 'tf.trainable_variables()', 'if', 'embedding_key', '==', 'v.name]', 'if', 'len(vectors_variable)', '!=', '1:', "data.print_out(...
751,388
keras-team/keras-cv
preprocessing.py
ensure_tensor
ensure_tensor
Ensures the input is a Tensor, SparseTensor or RaggedTensor.
[ "Ensures", "the", "input", "is", "a", "Tensor,", "SparseTensor", "or", "RaggedTensor." ]
def ensure_tensor(inputs, dtype=None): if not ops.is_tensor(inputs): inputs = ops.convert_to_tensor(inputs, dtype) if dtype is not None and inputs.dtype != dtype: inputs = ops.cast(inputs, dtype) return inputs
['def', 'ensure_tensor(inputs,', 'dtype=None):', 'if', 'not', 'ops.is_tensor(inputs):', 'inputs', '=', 'ops.convert_to_tensor(inputs,', 'dtype)', 'if', 'dtype', 'is', 'not', 'None', 'and', 'inputs.dtype', '!=', 'dtype:', 'inputs', '=', 'ops.cast(inputs,', 'dtype)', 'return', 'inputs']
595,383
muhanzhang/D-VAE
test_debugmode.py
test_badoptimization_opt_err
test_badoptimization_opt_err
This variant of test_badoptimization() replace the working code with a new apply node that will raise an error.
[ "This", "variant", "of", "test_badoptimization()", "replace", "the", "working", "code", "with", "a", "new", "apply", "node", "that", "will", "raise", "an", "error." ]
def test_badoptimization_opt_err(): @gof.local_optimizer([theano.tensor.add]) def insert_bigger_b_add(node): if node.op == theano.tensor.add: inputs = list(node.inputs) if inputs[-1].owner is None: inputs[-1] = theano.tensor.concatenate((inputs[-1], inputs[-1])) ...
['def', 'test_badoptimization_opt_err():', '@gof.local_optimizer([theano.tensor.add])', 'def', 'insert_bigger_b_add(node):', 'if', 'node.op', '==', 'theano.tensor.add:', 'inputs', '=', 'list(node.inputs)', 'if', 'inputs[-1].owner', 'is', 'None:', 'inputs[-1]', '=', 'theano.tensor.concatenate((inputs[-1],', 'inputs[-1])...
524,820
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
networks.py
generator
generator
Thin wrapper around CycleGAN generator to conform to the TFGAN API.
[ "Thin", "wrapper", "around", "CycleGAN", "generator", "to", "conform", "to", "the", "TFGAN", "API." ]
def generator(input_images): input_images.shape.assert_has_rank(4) with tf.contrib.framework.arg_scope(cyclegan.cyclegan_arg_scope()): (output_images, _) = cyclegan.cyclegan_generator_resnet(input_images) return output_images
['def', 'generator(input_images):', 'input_images.shape.assert_has_rank(4)', 'with', 'tf.contrib.framework.arg_scope(cyclegan.cyclegan_arg_scope()):', '(output_images,', '_)', '=', 'cyclegan.cyclegan_generator_resnet(input_images)', 'return', 'output_images']
54,907
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
vecs.py
Vecs.neighbors
neighbors
Returns the nearest neighbors to the query (a word or vector).
[ "Returns", "the", "nearest", "neighbors", "to", "the", "query", "(a", "word", "or", "vector)." ]
def neighbors(self, query): if isinstance(query, string_types): idx = self.word_to_idx.get(query) if idx is None: return None query = self.vecs[idx] neighbors = self.vecs * query.transpose() return sorted(zip(self.vocab, neighbors.flat), key=lambda kv: kv[1], reverse=True...
['def', 'neighbors(self,', 'query):', 'if', 'isinstance(query,', 'string_types):', 'idx', '=', 'self.word_to_idx.get(query)', 'if', 'idx', 'is', 'None:', 'return', 'None', 'query', '=', 'self.vecs[idx]', 'neighbors', '=', 'self.vecs', '*', 'query.transpose()', 'return', 'sorted(zip(self.vocab,', 'neighbors.flat),', 'ke...
27,964
avalonstrel/SketchBERT
utils.py
DataLoader.calculate_normalizing_scale_factor
calculate_normalizing_scale_factor
Calculate the normalizing factor explained in appendix of sketch-rnn.
[ "Calculate", "the", "normalizing", "factor", "explained", "in", "appendix", "of", "sketch-rnn." ]
def calculate_normalizing_scale_factor(self): data = [] for i in range(len(self.strokes)): if len(self.strokes[i]) > self.max_seq_length: continue for j in range(len(self.strokes[i])): data.append(self.strokes[i][j, 0]) data.append(self.strokes[i][j, 1]) d...
['def', 'calculate_normalizing_scale_factor(self):', 'data', '=', '[]', 'for', 'i', 'in', 'range(len(self.strokes)):', 'if', 'len(self.strokes[i])', '>', 'self.max_seq_length:', 'continue', 'for', 'j', 'in', 'range(len(self.strokes[i])):', 'data.append(self.strokes[i][j,', '0])', 'data.append(self.strokes[i][j,', '1])'...
350,939
IINemo/isanlp
processor_lemmatizer_nltk_en.py
get_wordnet_pos
get_wordnet_pos
Converts Penn treebank postag into WordNet postag.
[ "Converts", "Penn", "treebank", "postag", "into", "WordNet", "postag." ]
def get_wordnet_pos(treebank_tag): if treebank_tag.startswith('J'): return wordnet.ADJ elif treebank_tag.startswith('V'): return wordnet.VERB elif treebank_tag.startswith('N'): return wordnet.NOUN elif treebank_tag.startswith('R'): return wordnet.ADV else: ret...
['def', 'get_wordnet_pos(treebank_tag):', 'if', "treebank_tag.startswith('J'):", 'return', 'wordnet.ADJ', 'elif', "treebank_tag.startswith('V'):", 'return', 'wordnet.VERB', 'elif', "treebank_tag.startswith('N'):", 'return', 'wordnet.NOUN', 'elif', "treebank_tag.startswith('R'):", 'return', 'wordnet.ADV', 'else:', 'retu...
577,241
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
feature_io.py
ArraysToDelfFeatures
ArraysToDelfFeatures
Converts DELF features to DelfFeatures proto.
[ "Converts", "DELF", "features", "to", "DelfFeatures", "proto." ]
def ArraysToDelfFeatures(locations, scales, descriptors, attention, orientations=None): num_features = len(attention) assert num_features == locations.shape[0] assert num_features == len(scales) assert num_features == descriptors.shape[0] if orientations is None: orientations = np.zeros([num...
['def', 'ArraysToDelfFeatures(locations,', 'scales,', 'descriptors,', 'attention,', 'orientations=None):', 'num_features', '=', 'len(attention)', 'assert', 'num_features', '==', 'locations.shape[0]', 'assert', 'num_features', '==', 'len(scales)', 'assert', 'num_features', '==', 'descriptors.shape[0]', 'if', 'orientatio...
53,759
mfbx9da4/neuron-astrocyte-networks
table.py
Table.getValue
getValue
return the value at a certain location in the table.
[ "return", "the", "value", "at", "a", "certain", "location", "in", "the", "table." ]
def getValue(self, row, column): return self.params.reshape(self.numRows, self.numColumns)[row, column]
['def', 'getValue(self,', 'row,', 'column):', 'return', 'self.params.reshape(self.numRows,', 'self.numColumns)[row,', 'column]']
722,682
sek788432/Waymo-2D-Object-Detection
input_pipeline.py
decode_record
decode_record
Decodes a record to a TensorFlow example.
[ "Decodes", "a", "record", "to", "a", "TensorFlow", "example." ]
def decode_record(record, name_to_features): example = tf.io.parse_single_example(record, name_to_features) for name in list(example.keys()): t = example[name] if t.dtype == tf.int64: t = tf.cast(t, tf.int32) example[name] = t return example
['def', 'decode_record(record,', 'name_to_features):', 'example', '=', 'tf.io.parse_single_example(record,', 'name_to_features)', 'for', 'name', 'in', 'list(example.keys()):', 't', '=', 'example[name]', 'if', 't.dtype', '==', 'tf.int64:', 't', '=', 'tf.cast(t,', 'tf.int32)', 'example[name]', '=', 't', 'return', 'exampl...
972,425
sktime/sktime
test_fourier.py
test_fourier_list_length_missmatch
test_fourier_list_length_missmatch
Tests exception raised when sp_list & fourier_terms_list lengths don't match.
[ "Tests", "exception", "raised", "when", "sp_list", "&", "fourier_terms_list", "lengths", "don't", "match." ]
def test_fourier_list_length_missmatch(): with pytest.raises(ValueError) as ex: FourierFeatures(sp_list=[365, 52], fourier_terms_list=[1]) assert ex.value == 'In FourierFeatures the length of the sp_list needs to be equal to the length of fourier_terms_list.'
['def', 'test_fourier_list_length_missmatch():', 'with', 'pytest.raises(ValueError)', 'as', 'ex:', 'FourierFeatures(sp_list=[365,', '52],', 'fourier_terms_list=[1])', 'assert', 'ex.value', '==', "'In", 'FourierFeatures', 'the', 'length', 'of', 'the', 'sp_list', 'needs', 'to', 'be', 'equal', 'to', 'the', 'length', 'of',...
877,872
yanqi1811/transfer-learning
tf_dataset.py
TFDataset.shuffle_split
shuffle_split
Randomly split the dataset into train, validation, and test subsets with a pseudo-random seed option.
[ "Randomly", "split", "the", "dataset", "into", "train,", "validation,", "and", "test", "subsets", "with", "a", "pseudo-random", "seed", "option." ]
def shuffle_split(self, train_pct=0.75, val_pct=0.25, test_pct=0.0, shuffle_files=True, seed=None): if not (isinstance(train_pct, float) and isinstance(val_pct, float) and isinstance(test_pct, float)): raise ValueError('Percentage arguments must be floats.') if train_pct + val_pct + test_pct > 1.0: ...
['def', 'shuffle_split(self,', 'train_pct=0.75,', 'val_pct=0.25,', 'test_pct=0.0,', 'shuffle_files=True,', 'seed=None):', 'if', 'not', '(isinstance(train_pct,', 'float)', 'and', 'isinstance(val_pct,', 'float)', 'and', 'isinstance(test_pct,', 'float)):', 'raise', "ValueError('Percentage", 'arguments', 'must', 'be', "flo...
927,688
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data_utils.py
prepare_data
prepare_data
Preapre all necessary files that are required for the training.
[ "Preapre", "all", "necessary", "files", "that", "are", "required", "for", "the", "training." ]
def prepare_data(data_dir, from_train_path, to_train_path, from_dev_path, to_dev_path, from_vocabulary_size, to_vocabulary_size, tokenizer=None): to_vocab_path = os.path.join(data_dir, 'vocab%d.to' % to_vocabulary_size) from_vocab_path = os.path.join(data_dir, 'vocab%d.from' % from_vocabulary_size) create_v...
['def', 'prepare_data(data_dir,', 'from_train_path,', 'to_train_path,', 'from_dev_path,', 'to_dev_path,', 'from_vocabulary_size,', 'to_vocabulary_size,', 'tokenizer=None):', 'to_vocab_path', '=', 'os.path.join(data_dir,', "'vocab%d.to'", '%', 'to_vocabulary_size)', 'from_vocab_path', '=', 'os.path.join(data_dir,', "'vo...
30,487
liuzuxin/safe-mbrl
mpi_tf.py
MpiAdamOptimizer.apply_gradients
apply_gradients
Same as normal apply_gradients, except sync params after update.
[ "Same", "as", "normal", "apply_gradients,", "except", "sync", "params", "after", "update." ]
def apply_gradients(self, grads_and_vars, global_step=None, name=None): opt = super().apply_gradients(grads_and_vars, global_step, name) with tf.control_dependencies([opt]): sync = sync_params([v for (g, v) in grads_and_vars]) return tf.group([opt, sync])
['def', 'apply_gradients(self,', 'grads_and_vars,', 'global_step=None,', 'name=None):', 'opt', '=', 'super().apply_gradients(grads_and_vars,', 'global_step,', 'name)', 'with', 'tf.control_dependencies([opt]):', 'sync', '=', 'sync_params([v', 'for', '(g,', 'v)', 'in', 'grads_and_vars])', 'return', 'tf.group([opt,', 'syn...
828,862
matsu0228/nlp-jp
__init__.py
FCompiler.get_flags_fix
get_flags_fix
List of Fortran 90 fixed format specific flags.
[ "List", "of", "Fortran", "90", "fixed", "format", "specific", "flags." ]
def get_flags_fix(self): return self._get_command_flags('compiler_fix')
['def', 'get_flags_fix(self):', 'return', "self._get_command_flags('compiler_fix')"]
791,061
Jittor/JDet
coco.py
COCODataset.evaluate
evaluate
Evaluation in COCO protocol.
[ "Evaluation", "in", "COCO", "protocol." ]
def evaluate(self, results, work_dir, epoch, metric='bbox', logger=None, classwise=False, proposal_nums=(100, 300, 1000), iou_thrs=None, metric_items=None): save_file = build_file(work_dir, prefix=f'detections/val_{epoch}.json') self.save_results(results, save_file) metrics = metric if isinstance(metric, li...
['def', 'evaluate(self,', 'results,', 'work_dir,', 'epoch,', "metric='bbox',", 'logger=None,', 'classwise=False,', 'proposal_nums=(100,', '300,', '1000),', 'iou_thrs=None,', 'metric_items=None):', 'save_file', '=', 'build_file(work_dir,', "prefix=f'detections/val_{epoch}.json')", 'self.save_results(results,', 'save_fil...
577,643
YuriyGuts/snake-ai-reinforcement
environment.py
Environment.get_observation
get_observation
Observe the state of the environment.
[ "Observe", "the", "state", "of", "the", "environment." ]
def get_observation(self): return np.copy(self.field._cells)
['def', 'get_observation(self):', 'return', 'np.copy(self.field._cells)']
352,113
tobegit3hub/deep_image_model
server_test.py
TensorboardServerTest.testSampleScalars
testSampleScalars
Test the sample_count parameter of /data/scalars.
[ "Test", "the", "sample_count", "parameter", "of", "/data/scalars." ]
def testSampleScalars(self): for i in xrange(10, self._SCALAR_COUNT, 10): samples = self._getJson('/data/scalars?sample_count=%d' % i) values = samples['run1']['simple_values'] self.assertEqual(len(values), i) self.assertEqual(values[0], [100, 10, 1]) self.assertEqual(values[...
['def', 'testSampleScalars(self):', 'for', 'i', 'in', 'xrange(10,', 'self._SCALAR_COUNT,', '10):', 'samples', '=', "self._getJson('/data/scalars?sample_count=%d'", '%', 'i)', 'values', '=', "samples['run1']['simple_values']", 'self.assertEqual(len(values),', 'i)', 'self.assertEqual(values[0],', '[100,', '10,', '1])', '...
183,480
Ruturaj123/Flowchart-Detection
model_rotator.py
get_init_fn
get_init_fn
Initialization assignment operator function used while training.
[ "Initialization", "assignment", "operator", "function", "used", "while", "training." ]
def get_init_fn(scopes, params): if not params.init_model: return None is_trainable = lambda x: x in tf.trainable_variables() var_list = [] for scope in scopes: var_list.extend(filter(is_trainable, tf.contrib.framework.get_model_variables(scope))) (init_assign_op, init_feed_dict) = s...
['def', 'get_init_fn(scopes,', 'params):', 'if', 'not', 'params.init_model:', 'return', 'None', 'is_trainable', '=', 'lambda', 'x:', 'x', 'in', 'tf.trainable_variables()', 'var_list', '=', '[]', 'for', 'scope', 'in', 'scopes:', 'var_list.extend(filter(is_trainable,', 'tf.contrib.framework.get_model_variables(scope)))',...
586,302
RasaHQ/rasa
precomputation.py
MessageContainerForCoreFeaturization.all_messages
all_messages
Returns a list containing all messages.
[ "Returns", "a", "list", "containing", "all", "messages." ]
def all_messages(self) -> List[Message]: return [message for key_attribute_table in self._table.values() for message in key_attribute_table.values()]
['def', 'all_messages(self)', '->', 'List[Message]:', 'return', '[message', 'for', 'key_attribute_table', 'in', 'self._table.values()', 'for', 'message', 'in', 'key_attribute_table.values()]']
836,885
kwai/DouZero
env.py
DummyAgent.act
act
Simply return the action that is set previously.
[ "Simply", "return", "the", "action", "that", "is", "set", "previously." ]
def act(self, infoset): assert self.action in infoset.legal_actions return self.action
['def', 'act(self,', 'infoset):', 'assert', 'self.action', 'in', 'infoset.legal_actions', 'return', 'self.action']
166,841
deepmind/dm_control
control.py
Environment.step_spec
step_spec
May return a specification for the values returned by `step`.
[ "May", "return", "a", "specification", "for", "the", "values", "returned", "by", "`step`." ]
def step_spec(self): return self._task.step_spec(self._physics)
['def', 'step_spec(self):', 'return', 'self._task.step_spec(self._physics)']
165,347
janluke/cs188
util.py
arrayInvert
arrayInvert
Inverts a matrix stored as a list of lists.
[ "Inverts", "a", "matrix", "stored", "as", "a", "list", "of", "lists." ]
def arrayInvert(array): result = [[] for i in array] for outer in array: for inner in range(len(outer)): result[inner].append(outer[inner]) return result
['def', 'arrayInvert(array):', 'result', '=', '[[]', 'for', 'i', 'in', 'array]', 'for', 'outer', 'in', 'array:', 'for', 'inner', 'in', 'range(len(outer)):', 'result[inner].append(outer[inner])', 'return', 'result']
224,744
nicknochnack/RealTimeSignLanguageTFJS
image_classification.py
ImageClassificationTask.inference_step
inference_step
Performs the forward step.
[ "Performs", "the", "forward", "step." ]
def inference_step(self, inputs, model): return model(inputs, training=False)
['def', 'inference_step(self,', 'inputs,', 'model):', 'return', 'model(inputs,', 'training=False)']
850,910
ifwe/digsby
imagefx.py
rounded_mask
rounded_mask
Returns a grayscale image with the specified size, with alpha values dropping off at the corners.
[ "Returns", "a", "grayscale", "image", "with", "the", "specified", "size,", "with", "alpha", "values", "dropping", "off", "at", "the", "corners." ]
def rounded_mask(size, cornersize=1): img = Image.new('L', size, 255) (w, h) = size (p, r) = (img.paste, rounded_corners(cornersize)) i = r[0] p(i, (0, 0, i.size[0], i.size[1])) i = r[1] p(i, (w - i.size[0], 0, w, i.size[1])) i = r[2] p(i, (0, h - i.size[1], i.size[0], h)) i = r[...
['def', 'rounded_mask(size,', 'cornersize=1):', 'img', '=', "Image.new('L',", 'size,', '255)', '(w,', 'h)', '=', 'size', '(p,', 'r)', '=', '(img.paste,', 'rounded_corners(cornersize))', 'i', '=', 'r[0]', 'p(i,', '(0,', '0,', 'i.size[0],', 'i.size[1]))', 'i', '=', 'r[1]', 'p(i,', '(w', '-', 'i.size[0],', '0,', 'w,', 'i....
185,559
amazon-science/unified-ept
custom.py
CustomDataset.load_annotations
load_annotations
Load annotation from directory.
[ "Load", "annotation", "from", "directory." ]
def load_annotations(self, img_dir, img_suffix, ann_dir, dt_dir, seg_map_suffix, split): img_infos = [] if split is not None: with open(split) as f: for line in f: img_name = line.strip() img_info = dict(filename=img_name + img_suffix) if ann_d...
['def', 'load_annotations(self,', 'img_dir,', 'img_suffix,', 'ann_dir,', 'dt_dir,', 'seg_map_suffix,', 'split):', 'img_infos', '=', '[]', 'if', 'split', 'is', 'not', 'None:', 'with', 'open(split)', 'as', 'f:', 'for', 'line', 'in', 'f:', 'img_name', '=', 'line.strip()', 'img_info', '=', 'dict(filename=img_name', '+', 'i...
947,975
greydanus/mr_london
OleFileIO.py
OleFileIO.loadfat
loadfat
Load the FAT table.
[ "Load", "the", "FAT", "table." ]
def loadfat(self, header): sect = header[76:512] debug('len(sect)=%d, so %d integers' % (len(sect), len(sect) // 4)) self.fat = array.array(UINT32) self.loadfat_sect(sect) if self.csectDif != 0: if self.csectFat <= 109: self.raise_defect(DEFECT_INCORRECT, 'incorrect DIFAT, not en...
['def', 'loadfat(self,', 'header):', 'sect', '=', 'header[76:512]', "debug('len(sect)=%d,", 'so', '%d', "integers'", '%', '(len(sect),', 'len(sect)', '//', '4))', 'self.fat', '=', 'array.array(UINT32)', 'self.loadfat_sect(sect)', 'if', 'self.csectDif', '!=', '0:', 'if', 'self.csectFat', '<=', '109:', 'self.raise_defect...
263,271
intel/neural-compressor
graph_util.py
GraphAnalyzer.remove_node_with_single_input_output
remove_node_with_single_input_output
Remove node with one input and rebuild internal graph data structure.
[ "Remove", "node", "with", "one", "input", "and", "rebuild", "internal", "graph", "data", "structure." ]
def remove_node_with_single_input_output(self, node_name): if node_name not in self.node_name_details: logger.debug('The {} is not a valid node name.'.format(node_name)) return False non_const_node_count = len([GraphRewriterHelper.node_name_from_input(i) for i in self.node_name_details[node_name...
['def', 'remove_node_with_single_input_output(self,', 'node_name):', 'if', 'node_name', 'not', 'in', 'self.node_name_details:', "logger.debug('The", '{}', 'is', 'not', 'a', 'valid', 'node', "name.'.format(node_name))", 'return', 'False', 'non_const_node_count', '=', 'len([GraphRewriterHelper.node_name_from_input(i)', '...
737,590
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkplot.py
Cdf
Cdf
Plots a CDF as a line.
[ "Plots", "a", "CDF", "as", "a", "line." ]
def Cdf(cdf, complement=False, transform=None, **options): (xs, ps) = cdf.Render() xs = np.asarray(xs) ps = np.asarray(ps) scale = dict(xscale='linear', yscale='linear') for s in ['xscale', 'yscale']: if s in options: scale[s] = options.pop(s) if transform == 'exponential': ...
['def', 'Cdf(cdf,', 'complement=False,', 'transform=None,', '**options):', '(xs,', 'ps)', '=', 'cdf.Render()', 'xs', '=', 'np.asarray(xs)', 'ps', '=', 'np.asarray(ps)', 'scale', '=', "dict(xscale='linear',", "yscale='linear')", 'for', 's', 'in', "['xscale',", "'yscale']:", 'if', 's', 'in', 'options:', 'scale[s]', '=', ...
12,739
caiiiac/Machine-Learning-with-Python
test_waveforms.py
TestSweepPoly.test_sweep_poly_cubic3
test_sweep_poly_cubic3
Use a list of coefficients instead of a poly1d.
[ "Use", "a", "list", "of", "coefficients", "instead", "of", "a", "poly1d." ]
def test_sweep_poly_cubic3(self): p = [2.0, 1.0, 0.0, -2.0] t = np.linspace(0, 2.0, 10000) phase = waveforms._sweep_poly_phase(t, p) (tf, f) = compute_frequency(t, phase) expected = np.poly1d(p)(tf) abserr = np.max(np.abs(f - expected)) assert_(abserr < 1e-06)
['def', 'test_sweep_poly_cubic3(self):', 'p', '=', '[2.0,', '1.0,', '0.0,', '-2.0]', 't', '=', 'np.linspace(0,', '2.0,', '10000)', 'phase', '=', 'waveforms._sweep_poly_phase(t,', 'p)', '(tf,', 'f)', '=', 'compute_frequency(t,', 'phase)', 'expected', '=', 'np.poly1d(p)(tf)', 'abserr', '=', 'np.max(np.abs(f', '-', 'expec...
719,876
voxel51/fiftyone
manager.py
PlotManager.remove
remove
Removes the plot from this manager.
[ "Removes", "the", "plot", "from", "this", "manager." ]
def remove(self, name): self.pop(name)
['def', 'remove(self,', 'name):', 'self.pop(name)']
583,628
sek788432/Waymo-2D-Object-Detection
base_config.py
Config.from_args
from_args
Builds a config from the given list of arguments.
[ "Builds", "a", "config", "from", "the", "given", "list", "of", "arguments." ]
def from_args(cls, *args, **kwargs): attributes = list(cls.__annotations__.keys()) default_params = {a: p for (a, p) in zip(attributes, args)} default_params.update(kwargs) return cls(default_params)
['def', 'from_args(cls,', '*args,', '**kwargs):', 'attributes', '=', 'list(cls.__annotations__.keys())', 'default_params', '=', '{a:', 'p', 'for', '(a,', 'p)', 'in', 'zip(attributes,', 'args)}', 'default_params.update(kwargs)', 'return', 'cls(default_params)']
972,356
CQCL/lambeq
parser.py
Chart.min_score
min_score
Get the lowest score needed to add a tree to the given cell.
[ "Get", "the", "lowest", "score", "needed", "to", "add", "a", "tree", "to", "the", "given", "cell." ]
def min_score(self, start: int, end: int) -> float: try: return self.chart[start, end].min_score except KeyError: return NEGATIVE_INFINITY
['def', 'min_score(self,', 'start:', 'int,', 'end:', 'int)', '->', 'float:', 'try:', 'return', 'self.chart[start,', 'end].min_score', 'except', 'KeyError:', 'return', 'NEGATIVE_INFINITY']
623,190
devashish-patel/webcam-motion-detector
prefilter.py
PrefilterManager.register_handler
register_handler
Register a handler instance by name with esc_strings.
[ "Register", "a", "handler", "instance", "by", "name", "with", "esc_strings." ]
def register_handler(self, name, handler, esc_strings): self._handlers[name] = handler for esc_str in esc_strings: self._esc_handlers[esc_str] = handler
['def', 'register_handler(self,', 'name,', 'handler,', 'esc_strings):', 'self._handlers[name]', '=', 'handler', 'for', 'esc_str', 'in', 'esc_strings:', 'self._esc_handlers[esc_str]', '=', 'handler']
978,804
gunthercox/ChatterBot
schema.py
ChangesetColumn.copy_fixed
copy_fixed
Create a copy of this ``Column``, with all attributes.
[ "Create", "a", "copy", "of", "this", "``Column``,", "with", "all", "attributes." ]
def copy_fixed(self, **kw): return sqlalchemy.Column(self.name, self.type, self.default, *[c.copy(**kw) for c in self.constraints], key=self.key, primary_key=self.primary_key, nullable=self.nullable, quote=self.quote, index=self.index, unique=self.unique, onupdate=self.onupdate, autoincrement=self.autoincrement, se...
['def', 'copy_fixed(self,', '**kw):', 'return', 'sqlalchemy.Column(self.name,', 'self.type,', 'self.default,', '*[c.copy(**kw)', 'for', 'c', 'in', 'self.constraints],', 'key=self.key,', 'primary_key=self.primary_key,', 'nullable=self.nullable,', 'quote=self.quote,', 'index=self.index,', 'unique=self.unique,', 'onupdate...
479,485
Eric3911/OpenAGI
rnnt_pytorch.py
RNNTLossPytorch.input_types
input_types
Input types definitions for CTCLoss.
[ "Input", "types", "definitions", "for", "CTCLoss." ]
def input_types(self): return {'acts': NeuralType(('B', 'T', 'T', 'D'), LogprobsType()), 'labels': NeuralType(('B', 'T'), LabelsType()), 'act_lens': NeuralType(tuple('B'), LengthsType()), 'label_lens': NeuralType(tuple('B'), LengthsType())}
['def', 'input_types(self):', 'return', "{'acts':", "NeuralType(('B',", "'T',", "'T',", "'D'),", 'LogprobsType()),', "'labels':", "NeuralType(('B',", "'T'),", 'LabelsType()),', "'act_lens':", "NeuralType(tuple('B'),", 'LengthsType()),', "'label_lens':", "NeuralType(tuple('B'),", 'LengthsType())}']
272,327
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
beam_reader_ops_test.py
ParsingReaderOpsTest.testPathScoresAgree
testPathScoresAgree
Ensures that path scores computed in the beam are same in the net.
[ "Ensures", "that", "path", "scores", "computed", "in", "the", "beam", "are", "same", "in", "the", "net." ]
def testPathScoresAgree(self): (all_path_scores, beam_path_scores) = self.PathScores(iterations=1, beam_size=130, max_steps=5, batch_size=1) self.assertArrayNear(all_path_scores[0], beam_path_scores[0], 1e-06)
['def', 'testPathScoresAgree(self):', '(all_path_scores,', 'beam_path_scores)', '=', 'self.PathScores(iterations=1,', 'beam_size=130,', 'max_steps=5,', 'batch_size=1)', 'self.assertArrayNear(all_path_scores[0],', 'beam_path_scores[0],', '1e-06)']
28,848
WHU-ZQH/E2S2
polynomial_decay_schedule.py
PolynomialDecayLRSchedule.step_update
step_update
Update the learning rate after each update.
[ "Update", "the", "learning", "rate", "after", "each", "update." ]
def step_update(self, num_updates): if self.cfg.warmup_updates > 0 and num_updates <= self.cfg.warmup_updates: self.warmup_factor = num_updates / float(self.cfg.warmup_updates) lr = self.warmup_factor * self.lr elif num_updates >= self.total_num_update: lr = self.end_learning_rate el...
['def', 'step_update(self,', 'num_updates):', 'if', 'self.cfg.warmup_updates', '>', '0', 'and', 'num_updates', '<=', 'self.cfg.warmup_updates:', 'self.warmup_factor', '=', 'num_updates', '/', 'float(self.cfg.warmup_updates)', 'lr', '=', 'self.warmup_factor', '*', 'self.lr', 'elif', 'num_updates', '>=', 'self.total_num_...
556,136
ancasag/ensembleObjectDetection
common.py
Generator.get_augmented_data
get_augmented_data
Compute inputs and target outputs for the network.
[ "Compute", "inputs", "and", "target", "outputs", "for", "the", "network." ]
def get_augmented_data(self, group): image_group = self.load_image_group(group) annotations_group = self.load_annotations_group(group) (image_group, annotations_group) = self.filter_annotations(image_group, annotations_group, group) (image_group, annotations_group) = self.random_visual_effect_group(imag...
['def', 'get_augmented_data(self,', 'group):', 'image_group', '=', 'self.load_image_group(group)', 'annotations_group', '=', 'self.load_annotations_group(group)', '(image_group,', 'annotations_group)', '=', 'self.filter_annotations(image_group,', 'annotations_group,', 'group)', '(image_group,', 'annotations_group)', '=...
562,124
deepmind/dm_control
swimmer.py
Physics.body_velocities
body_velocities
Returns local body velocities: x,y linear, z rotational.
[ "Returns", "local", "body", "velocities:", "x,y", "linear,", "z", "rotational." ]
def body_velocities(self): xvel_local = self.data.sensordata[12:].reshape((-1, 6)) vx_vy_wz = [0, 1, 5] return xvel_local[:, vx_vy_wz].ravel()
['def', 'body_velocities(self):', 'xvel_local', '=', 'self.data.sensordata[12:].reshape((-1,', '6))', 'vx_vy_wz', '=', '[0,', '1,', '5]', 'return', 'xvel_local[:,', 'vx_vy_wz].ravel()']
165,587
tswsxk/CangJie
bert.py
BertEmbedding.data_loader
data_loader
Load, tokenize and prepare the input sentences.
[ "Load,", "tokenize", "and", "prepare", "the", "input", "sentences." ]
def data_loader(self, sentences, shuffle=False): dataset = BertEmbeddingDataset(sentences, self.transform) return DataLoader(dataset=dataset, batch_size=self.batch_size, shuffle=shuffle)
['def', 'data_loader(self,', 'sentences,', 'shuffle=False):', 'dataset', '=', 'BertEmbeddingDataset(sentences,', 'self.transform)', 'return', 'DataLoader(dataset=dataset,', 'batch_size=self.batch_size,', 'shuffle=shuffle)']
454,798
ishtiaq1495/Generative_adversarial_networks
CycleGAN.py
to_var
to_var
Converts numpy to variable.
[ "Converts", "numpy", "to", "variable." ]
def to_var(x): if torch.cuda.is_available(): x = x.cuda() return Variable(x)
['def', 'to_var(x):', 'if', 'torch.cuda.is_available():', 'x', '=', 'x.cuda()', 'return', 'Variable(x)']
556,598
interpretml/DiCE
public_data_interface.py
PublicData.prepare_query_instance
prepare_query_instance
Prepares user defined test input(s) for DiCE.
[ "Prepares", "user", "defined", "test", "input(s)", "for", "DiCE." ]
def prepare_query_instance(self, query_instance): if isinstance(query_instance, list): if isinstance(query_instance[0], dict): test = pd.DataFrame(query_instance, columns=self.feature_names) else: query_instance = {'row1': query_instance} test = pd.DataFrame.from_...
['def', 'prepare_query_instance(self,', 'query_instance):', 'if', 'isinstance(query_instance,', 'list):', 'if', 'isinstance(query_instance[0],', 'dict):', 'test', '=', 'pd.DataFrame(query_instance,', 'columns=self.feature_names)', 'else:', 'query_instance', '=', "{'row1':", 'query_instance}', 'test', '=', 'pd.DataFrame...
550,206
vanderschaarlab/mlforhealthlabpub
adsgan.py
adsgan
adsgan
Generate synthetic data for ADSGAN framework.
[ "Generate", "synthetic", "data", "for", "ADSGAN", "framework." ]
def adsgan(orig_data, params): tf.reset_default_graph() x_dim = len(orig_data.columns) no = len(orig_data) mb_size = params['mb_size'] z_dim = params['z_dim'] h_dim = params['h_dim'] lamda = params['lamda'] iterations = params['iterations'] lam = 10 lr = 0.0001 orig_data = np...
['def', 'adsgan(orig_data,', 'params):', 'tf.reset_default_graph()', 'x_dim', '=', 'len(orig_data.columns)', 'no', '=', 'len(orig_data)', 'mb_size', '=', "params['mb_size']", 'z_dim', '=', "params['z_dim']", 'h_dim', '=', "params['h_dim']", 'lamda', '=', "params['lamda']", 'iterations', '=', "params['iterations']", 'la...
239,956
amzn/xfer
metalogger.py
MetaLogger.report
report
Report results at end of epoch/task/metastep using hook function.
[ "Report", "results", "at", "end", "of", "epoch/task/metastep", "using", "hook", "function." ]
def report(self, end, hook=None): if hook is None: hook = logging.info reporter = {self.EPOCH: self._report_epoch, self.TASK: self._report_task, self.METASTEP: self._report_metastep} reporter[end](hook)
['def', 'report(self,', 'end,', 'hook=None):', 'if', 'hook', 'is', 'None:', 'hook', '=', 'logging.info', 'reporter', '=', '{self.EPOCH:', 'self._report_epoch,', 'self.TASK:', 'self._report_task,', 'self.METASTEP:', 'self._report_metastep}', 'reporter[end](hook)']
961,926
Stable-Baselines-Team/stable-baselines
run_mujoco.py
train
train
Train PPO2 model for Mujoco environment, for testing purposes :param env_id: (str) the environment id string :param num_timesteps: (int) the number of timesteps to run :param seed: (int) Used to seed the random generator.
[ "Train", "PPO2", "model", "for", "Mujoco", "environment,", "for", "testing", "purposes", ":param", "env_id:", "(str)", "the", "environment", "id", "string", ":param", "num_timesteps:", "(int)", "the", "number", "of", "timesteps", "to", "run", ":param", "seed:", ...
def train(env_id, num_timesteps, seed): def make_env(): env_out = gym.make(env_id) env_out = bench.Monitor(env_out, logger.get_dir(), allow_early_resets=True) return env_out env = DummyVecEnv([make_env]) env = VecNormalize(env) set_global_seeds(seed) policy = MlpPolicy m...
['def', 'train(env_id,', 'num_timesteps,', 'seed):', 'def', 'make_env():', 'env_out', '=', 'gym.make(env_id)', 'env_out', '=', 'bench.Monitor(env_out,', 'logger.get_dir(),', 'allow_early_resets=True)', 'return', 'env_out', 'env', '=', 'DummyVecEnv([make_env])', 'env', '=', 'VecNormalize(env)', 'set_global_seeds(seed)',...
873,204
marysia/thesis
augmentation.py
crop_volume
crop_volume
Crops the volume to the desired shape, with translations from the center.
[ "Crops", "the", "volume", "to", "the", "desired", "shape,", "with", "translations", "from", "the", "center." ]
def crop_volume(x, shape): center = {'x': x.shape[2] / 2 + np.random.randint(-3, 4), 'y': x.shape[1] / 2 + np.random.randint(-3, 4), 'z': x.shape[0] / 2 + np.random.randint(0, 1)} dif = {'x': shape[2] / 2, 'y': shape[1] / 2, 'z': shape[0] / 2} return x[center['z'] - dif['z']:center['z'] + dif['z'], center['...
['def', 'crop_volume(x,', 'shape):', 'center', '=', "{'x':", 'x.shape[2]', '/', '2', '+', 'np.random.randint(-3,', '4),', "'y':", 'x.shape[1]', '/', '2', '+', 'np.random.randint(-3,', '4),', "'z':", 'x.shape[0]', '/', '2', '+', 'np.random.randint(0,', '1)}', 'dif', '=', "{'x':", 'shape[2]', '/', '2,', "'y':", 'shape[1]...
354,672
LucasAlegre/morl-baselines
linear_support.py
LinearSupport.remove_obsolete_weights
remove_obsolete_weights
Remove from the queue the weight vectors for which the new value vector is better than previous values.
[ "Remove", "from", "the", "queue", "the", "weight", "vectors", "for", "which", "the", "new", "value", "vector", "is", "better", "than", "previous", "values." ]
def remove_obsolete_weights(self, new_value: np.ndarray) -> List[np.ndarray]: if len(self.ccs) == 0: return [] W_del = [] inds_remove = [] for (i, (priority, cw)) in enumerate(self.queue): if np.dot(cw, new_value) > self.max_scalarized_value(cw): W_del.append(cw) ...
['def', 'remove_obsolete_weights(self,', 'new_value:', 'np.ndarray)', '->', 'List[np.ndarray]:', 'if', 'len(self.ccs)', '==', '0:', 'return', '[]', 'W_del', '=', '[]', 'inds_remove', '=', '[]', 'for', '(i,', '(priority,', 'cw))', 'in', 'enumerate(self.queue):', 'if', 'np.dot(cw,', 'new_value)', '>', 'self.max_scalarize...
655,906