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
Knowledge-Precipitation-Tribe/Recurrent--network
ptb_word_lm.py
run_epoch
run_epoch
Runs the model on the given data.
[ "Runs", "the", "model", "on", "the", "given", "data." ]
def run_epoch(session, model, eval_op=None, verbose=False): start_time = time.time() costs = 0.0 iters = 0 state = session.run(model.initial_state) fetches = {'cost': model.cost, 'final_state': model.final_state} if eval_op is not None: fetches['eval_op'] = eval_op for step in range(...
['def', 'run_epoch(session,', 'model,', 'eval_op=None,', 'verbose=False):', 'start_time', '=', 'time.time()', 'costs', '=', '0.0', 'iters', '=', '0', 'state', '=', 'session.run(model.initial_state)', 'fetches', '=', "{'cost':", 'model.cost,', "'final_state':", 'model.final_state}', 'if', 'eval_op', 'is', 'not', 'None:'...
309,334
sshleifer/object_detection_kitti
synthetic_data_utils.py
split_list_by_inds
split_list_by_inds
Take the data, a list, and split it up based on the indices in inds1 and inds2.
[ "Take", "the", "data,", "a", "list,", "and", "split", "it", "up", "based", "on", "the", "indices", "in", "inds1", "and", "inds2." ]
def split_list_by_inds(data, inds1, inds2): if data is None or len(data) == 0: return ([], []) else: dout1 = [data[i] for i in inds1] dout2 = [data[i] for i in inds2] return (dout1, dout2)
['def', 'split_list_by_inds(data,', 'inds1,', 'inds2):', 'if', 'data', 'is', 'None', 'or', 'len(data)', '==', '0:', 'return', '([],', '[])', 'else:', 'dout1', '=', '[data[i]', 'for', 'i', 'in', 'inds1]', 'dout2', '=', '[data[i]', 'for', 'i', 'in', 'inds2]', 'return', '(dout1,', 'dout2)']
795,015
dongliangcao/Self-Supervised-Multimodal-Shape-Matching
misc.py
make_exp_dirs
make_exp_dirs
Make dirs for experiments.
[ "Make", "dirs", "for", "experiments." ]
def make_exp_dirs(opt): path_opt = opt['path'].copy() if opt['is_train']: mkdir_and_rename(path_opt['experiments_root']) os.makedirs(path_opt['models'], exist_ok=True) os.makedirs(path_opt['log'], exist_ok=True) else: mkdir_and_rename(path_opt['results_root']) os.make...
['def', 'make_exp_dirs(opt):', 'path_opt', '=', "opt['path'].copy()", 'if', "opt['is_train']:", "mkdir_and_rename(path_opt['experiments_root'])", "os.makedirs(path_opt['models'],", 'exist_ok=True)', "os.makedirs(path_opt['log'],", 'exist_ok=True)', 'else:', "mkdir_and_rename(path_opt['results_root'])", "os.makedirs(pat...
342,154
Speedwagon13/CS-3600-Introduction-to--
test_docxmlrpc.py
DocXMLRPCHTTPGETServer.test_autolink_dotted_methods
test_autolink_dotted_methods
Test that selfdot values are made strong automatically in the documentation.
[ "Test", "that", "selfdot", "values", "are", "made", "strong", "automatically", "in", "the", "documentation." ]
def test_autolink_dotted_methods(self): self.client.request('GET', '/') response = self.client.getresponse() self.assertIn('Try&nbsp;self.<strong>add</strong>,&nbsp;too.', response.read())
['def', 'test_autolink_dotted_methods(self):', "self.client.request('GET',", "'/')", 'response', '=', 'self.client.getresponse()', "self.assertIn('Try&nbsp;self.<strong>add</strong>,&nbsp;too.',", 'response.read())']
219,600
ChenhongyiYang/PPAL
sabl_head.py
SABLHead.side_aware_split
side_aware_split
Split side-aware features aligned with orders of bucketing targets.
[ "Split", "side-aware", "features", "aligned", "with", "orders", "of", "bucketing", "targets." ]
def side_aware_split(self, feat): l_end = int(np.ceil(self.up_reg_feat_size / 2)) r_start = int(np.floor(self.up_reg_feat_size / 2)) feat_fl = feat[:, :l_end] feat_fr = feat[:, r_start:].flip(dims=(1,)) feat_fl = feat_fl.contiguous() feat_fr = feat_fr.contiguous() feat = torch.cat([feat_fl, ...
['def', 'side_aware_split(self,', 'feat):', 'l_end', '=', 'int(np.ceil(self.up_reg_feat_size', '/', '2))', 'r_start', '=', 'int(np.floor(self.up_reg_feat_size', '/', '2))', 'feat_fl', '=', 'feat[:,', ':l_end]', 'feat_fr', '=', 'feat[:,', 'r_start:].flip(dims=(1,))', 'feat_fl', '=', 'feat_fl.contiguous()', 'feat_fr', '=...
821,778
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
network_units.py
NetworkUnitInterface.get_layer_size
get_layer_size
Gets the size of the given named layer of the network.
[ "Gets", "the", "size", "of", "the", "given", "named", "layer", "of", "the", "network." ]
def get_layer_size(self, layer_name): for layer in self.layers: if layer.name == layer_name: return layer.dim raise KeyError('Layer {} not found in component {}'.format(layer_name, self._component.name))
['def', 'get_layer_size(self,', 'layer_name):', 'for', 'layer', 'in', 'self.layers:', 'if', 'layer.name', '==', 'layer_name:', 'return', 'layer.dim', 'raise', "KeyError('Layer", '{}', 'not', 'found', 'in', 'component', "{}'.format(layer_name,", 'self._component.name))']
111,373
xXuHaiyang/USTC_Artificial-Intelligence_2022
searchAgents.py
FoodSearchProblem.expand
expand
Returns child states, the actions they require, and a cost of 1.
[ "Returns", "child", "states,", "the", "actions", "they", "require,", "and", "a", "cost", "of", "1." ]
def expand(self, state): children = [] self._expanded += 1 for action in self.getActions(state): next_state = self.getNextState(state, action) action_cost = self.getActionCost(state, action, next_state) children.append((next_state, action, action_cost)) return children
['def', 'expand(self,', 'state):', 'children', '=', '[]', 'self._expanded', '+=', '1', 'for', 'action', 'in', 'self.getActions(state):', 'next_state', '=', 'self.getNextState(state,', 'action)', 'action_cost', '=', 'self.getActionCost(state,', 'action,', 'next_state)', 'children.append((next_state,', 'action,', 'action...
439,070
SamsungLabs/fcaf3d
box_np_ops.py
points_in_convex_polygon_3d_jit
points_in_convex_polygon_3d_jit
Check points is in 3d convex polygons.
[ "Check", "points", "is", "in", "3d", "convex", "polygons." ]
def points_in_convex_polygon_3d_jit(points, polygon_surfaces, num_surfaces=None): (max_num_surfaces, max_num_points_of_surface) = polygon_surfaces.shape[1:3] num_polygons = polygon_surfaces.shape[0] if num_surfaces is None: num_surfaces = np.full((num_polygons,), 9999999, dtype=np.int64) (normal...
['def', 'points_in_convex_polygon_3d_jit(points,', 'polygon_surfaces,', 'num_surfaces=None):', '(max_num_surfaces,', 'max_num_points_of_surface)', '=', 'polygon_surfaces.shape[1:3]', 'num_polygons', '=', 'polygon_surfaces.shape[0]', 'if', 'num_surfaces', 'is', 'None:', 'num_surfaces', '=', 'np.full((num_polygons,),', '...
560,127
YuriyGuts/snake-ai-reinforcement
wrappers.py
make_openai_gym_environment
make_openai_gym_environment
Create an OpenAI Gym environment for the Snake game.
[ "Create", "an", "OpenAI", "Gym", "environment", "for", "the", "Snake", "game." ]
def make_openai_gym_environment(config_filename): with open(config_filename) as cfg: env_config = json.load(cfg) env_raw = Environment(config=env_config, verbose=1) env = OpenAIGymEnvAdapter(env_raw, ALL_SNAKE_ACTIONS, np.zeros((10, 10))) return env
['def', 'make_openai_gym_environment(config_filename):', 'with', 'open(config_filename)', 'as', 'cfg:', 'env_config', '=', 'json.load(cfg)', 'env_raw', '=', 'Environment(config=env_config,', 'verbose=1)', 'env', '=', 'OpenAIGymEnvAdapter(env_raw,', 'ALL_SNAKE_ACTIONS,', 'np.zeros((10,', '10)))', 'return', 'env']
352,124
0xumarkhatab/Artificial-Intelligence
search.py
GraphProblem.result
result
The result of going to a neighbor is just that neighbor.
[ "The", "result", "of", "going", "to", "a", "neighbor", "is", "just", "that", "neighbor." ]
def result(self, state, action): return action
['def', 'result(self,', 'state,', 'action):', 'return', 'action']
118,516
LonglongaaaGo/ComputerVision
camera.py
rotation_matrix
rotation_matrix
Creates a 3D rotation matrix for rotation around the axis of the vector a.
[ "Creates", "a", "3D", "rotation", "matrix", "for", "rotation", "around", "the", "axis", "of", "the", "vector", "a." ]
def rotation_matrix(a): R = eye(4) R[:3, :3] = linalg.expm([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]]) return R
['def', 'rotation_matrix(a):', 'R', '=', 'eye(4)', 'R[:3,', ':3]', '=', 'linalg.expm([[0,', '-a[2],', 'a[1]],', '[a[2],', '0,', '-a[0]],', '[-a[1],', 'a[0],', '0]])', 'return', 'R']
471,481
meganlsmith/phyloGAN
utils.py
simulatePseudo
simulatePseudo
Simulate data in IQTree under some lambda and a random tree topology.
[ "Simulate", "data", "in", "IQTree", "under", "some", "lambda", "and", "a", "random", "tree", "topology." ]
def simulatePseudo(iqTree, birthRate, model, numTaxa, length, output): print(output) os.system('%s --alisim %s -t RANDOM{bd{%r/0}/%r} -m %s --length %r --redo >/dev/null 2>&1 --redo' % (iqTree, output, birthRate, numTaxa, model, length)) thetree = open('%s.treefile' % output, 'r').readlines()[0].strip() ...
['def', 'simulatePseudo(iqTree,', 'birthRate,', 'model,', 'numTaxa,', 'length,', 'output):', 'print(output)', "os.system('%s", '--alisim', '%s', '-t', 'RANDOM{bd{%r/0}/%r}', '-m', '%s', '--length', '%r', '--redo', '>/dev/null', '2>&1', "--redo'", '%', '(iqTree,', 'output,', 'birthRate,', 'numTaxa,', 'model,', 'length))...
769,320
weimin17/Object-Detection_HelmetDetection
trainer_lib_test.py
TrainerLibTest.testTrainingScheduleGenerationAndDeterminism
testTrainingScheduleGenerationAndDeterminism
Non-trivial schedule, check generation and determinism.
[ "Non-trivial", "schedule,", "check", "generation", "and", "determinism." ]
def testTrainingScheduleGenerationAndDeterminism(self): pretrain_steps = [1, 2, 3] train_steps = [5, 5, 5] generated_schedule = trainer_lib.generate_target_per_step_schedule(pretrain_steps, train_steps) expected_schedule = [0, 1, 1, 2, 2, 2, 1, 0, 2, 1, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 2] self.assertEq...
['def', 'testTrainingScheduleGenerationAndDeterminism(self):', 'pretrain_steps', '=', '[1,', '2,', '3]', 'train_steps', '=', '[5,', '5,', '5]', 'generated_schedule', '=', 'trainer_lib.generate_target_per_step_schedule(pretrain_steps,', 'train_steps)', 'expected_schedule', '=', '[0,', '1,', '1,', '2,', '2,', '2,', '1,',...
753,507
OpenMDAO/OpenMDAO-Framework
hasconstraints.py
HasConstraints.eval_eq_constraints
eval_eq_constraints
Returns a list of constraint values.
[ "Returns", "a", "list", "of", "constraint", "values." ]
def eval_eq_constraints(self, scope=None): return self._eq.eval_eq_constraints(scope)
['def', 'eval_eq_constraints(self,', 'scope=None):', 'return', 'self._eq.eval_eq_constraints(scope)']
275,723
jeromewang-github/computer_vision
test_case.py
TestCase.execute_tpu
execute_tpu
Constructs the graph, executes it on TPU and returns the result.
[ "Constructs", "the", "graph,", "executes", "it", "on", "TPU", "and", "returns", "the", "result." ]
def execute_tpu(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] tpu_computation = tpu.rewrite(graph_fn, placeholders) sess.run(tpu.initialize_system()) sess.run([tf.global_variables_in...
['def', 'execute_tpu(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]', 'tpu_computation', '=', 'tpu.rewrite(graph_fn,', 'placeholders)', 'sess.run(tpu.initialize_system())', 'ses...
513,799
Ruturaj123/Flowchart-Detection
pandas_io.py
extract_pandas_matrix
extract_pandas_matrix
Extracts numpy matrix from pandas DataFrame.
[ "Extracts", "numpy", "matrix", "from", "pandas", "DataFrame." ]
def extract_pandas_matrix(data): if not isinstance(data, pd.DataFrame): return data return data.as_matrix()
['def', 'extract_pandas_matrix(data):', 'if', 'not', 'isinstance(data,', 'pd.DataFrame):', 'return', 'data', 'return', 'data.as_matrix()']
604,123
MycroftAI/mycroft-core
test_audio_utils.py
TestPlaySounds.test_play_wav_file_not_found
test_play_wav_file_not_found
Test that simple log is raised when subprocess can't find command.
[ "Test", "that", "simple", "log", "is", "raised", "when", "subprocess", "can't", "find", "command." ]
def test_play_wav_file_not_found(self, mock_log, mock_subprocess, mock_conf): def raise_filenotfound(*arg, **kwarg): raise FileNotFoundError('TEST FILE NOT FOUND') mock_subprocess.Popen.side_effect = raise_filenotfound mock_conf.get.return_value = test_config self.assertEqual(play_wav('indiffer...
['def', 'test_play_wav_file_not_found(self,', 'mock_log,', 'mock_subprocess,', 'mock_conf):', 'def', 'raise_filenotfound(*arg,', '**kwarg):', 'raise', "FileNotFoundError('TEST", 'FILE', 'NOT', "FOUND')", 'mock_subprocess.Popen.side_effect', '=', 'raise_filenotfound', 'mock_conf.get.return_value', '=', 'test_config', "s...
290,996
nicknochnack/RealTimeSignLanguageTFJS
image_classification.py
ImageClassificationTask.build_metrics
build_metrics
Gets streaming metrics for training/validation.
[ "Gets", "streaming", "metrics", "for", "training/validation." ]
def build_metrics(self, training=True): if self.task_config.losses.one_hot: metrics = [tf.keras.metrics.CategoricalAccuracy(name='accuracy'), tf.keras.metrics.TopKCategoricalAccuracy(k=5, name='top_5_accuracy')] else: metrics = [tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy'), tf.ker...
['def', 'build_metrics(self,', 'training=True):', 'if', 'self.task_config.losses.one_hot:', 'metrics', '=', "[tf.keras.metrics.CategoricalAccuracy(name='accuracy'),", 'tf.keras.metrics.TopKCategoricalAccuracy(k=5,', "name='top_5_accuracy')]", 'else:', 'metrics', '=', "[tf.keras.metrics.SparseCategoricalAccuracy(name='a...
850,908
facebookresearch/minihack
base.py
NetHackNet.get_running_std
get_running_std
Returns standard deviation of the running mean of the reward.
[ "Returns", "standard", "deviation", "of", "the", "running", "mean", "of", "the", "reward." ]
def get_running_std(self): return torch.sqrt(self.reward_m2 / self.reward_count)
['def', 'get_running_std(self):', 'return', 'torch.sqrt(self.reward_m2', '/', 'self.reward_count)']
670,752
jbwang1997/CrossKD
wrappers.py
ProposalBroadcaster.transform
transform
Apply wrapped transform functions to process both `gt_bboxes` and `proposals`.
[ "Apply", "wrapped", "transform", "functions", "to", "process", "both", "`gt_bboxes`", "and", "`proposals`." ]
def transform(self, results: dict) -> dict: assert results.get('proposals', None) is not None, '`proposals` should be in the results, please delete `ProposalBroadcaster` in your configs, or check whether you have load proposals successfully.' inputs = self._process_input(results) outputs = self._apply_trans...
['def', 'transform(self,', 'results:', 'dict)', '->', 'dict:', 'assert', "results.get('proposals',", 'None)', 'is', 'not', 'None,', "'`proposals`", 'should', 'be', 'in', 'the', 'results,', 'please', 'delete', '`ProposalBroadcaster`', 'in', 'your', 'configs,', 'or', 'check', 'whether', 'you', 'have', 'load', 'proposals'...
490,798
enlite-ai/maze
inventory.py
Inventory.replenish_piece
replenish_piece
Add a fresh raw piece to inventory.
[ "Add", "a", "fresh", "raw", "piece", "to", "inventory." ]
def replenish_piece(self) -> None: self.store_piece(self.raw_piece_size) self.inventory_events.piece_replenished()
['def', 'replenish_piece(self)', '->', 'None:', 'self.store_piece(self.raw_piece_size)', 'self.inventory_events.piece_replenished()']
647,640
takuseno/d3rlpy
base.py
TransformerAlgoBase.fit
fit
Trains with given dataset.
[ "Trains", "with", "given", "dataset." ]
def fit(self, dataset: ReplayBuffer, n_steps: int, n_steps_per_epoch: int=10000, experiment_name: Optional[str]=None, with_timestamp: bool=True, logger_adapter: LoggerAdapterFactory=FileAdapterFactory(), show_progress: bool=True, eval_env: Optional[GymEnv]=None, eval_target_return: Optional[float]=None, save_interval: ...
['def', 'fit(self,', 'dataset:', 'ReplayBuffer,', 'n_steps:', 'int,', 'n_steps_per_epoch:', 'int=10000,', 'experiment_name:', 'Optional[str]=None,', 'with_timestamp:', 'bool=True,', 'logger_adapter:', 'LoggerAdapterFactory=FileAdapterFactory(),', 'show_progress:', 'bool=True,', 'eval_env:', 'Optional[GymEnv]=None,', 'e...
197,795
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
input_data.py
extract_images
extract_images
Extract the images into a 4D uint8 numpy array [index, y, x, depth].
[ "Extract", "the", "images", "into", "a", "4D", "uint8", "numpy", "array", "[index,", "y,", "x,", "depth]." ]
def extract_images(filename): print('Extracting', filename) with gzip.open(filename) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError('Invalid magic number %d in MNIST image file: %s' % (magic, filename)) num_images = _read32(bytestream) r...
['def', 'extract_images(filename):', "print('Extracting',", 'filename)', 'with', 'gzip.open(filename)', 'as', 'bytestream:', 'magic', '=', '_read32(bytestream)', 'if', 'magic', '!=', '2051:', 'raise', "ValueError('Invalid", 'magic', 'number', '%d', 'in', 'MNIST', 'image', 'file:', "%s'", '%', '(magic,', 'filename))', '...
15,143
sooftware/nlp-tasks
utils.py
normalize_answer
normalize_answer
From Parlai, lower text and remove punctuation, articles and extra whitespace.
[ "From", "Parlai,", "lower", "text", "and", "remove", "punctuation,", "articles", "and", "extra", "whitespace." ]
def normalize_answer(s): s = s.lower() s = re_punc.sub(' ', s) s = s.strip() s = ' '.join(s.split()) return s
['def', 'normalize_answer(s):', 's', '=', 's.lower()', 's', '=', "re_punc.sub('", "',", 's)', 's', '=', 's.strip()', 's', '=', "'", "'.join(s.split())", 'return', 's']
731,364
instadeepai/jumanji
types_test.py
test_timestep__transition
test_timestep__transition
Validates that transition function returns the desired TimeStep.
[ "Validates", "that", "transition", "function", "returns", "the", "desired", "TimeStep." ]
def test_timestep__transition() -> None: observation = jnp.ones(5, float) reward = jnp.array(2.0, float) timestep = transition(reward, observation) assert jnp.all(timestep.observation == observation) assert timestep.step_type == StepType.MID assert timestep.reward == reward assert timestep.d...
['def', 'test_timestep__transition()', '->', 'None:', 'observation', '=', 'jnp.ones(5,', 'float)', 'reward', '=', 'jnp.array(2.0,', 'float)', 'timestep', '=', 'transition(reward,', 'observation)', 'assert', 'jnp.all(timestep.observation', '==', 'observation)', 'assert', 'timestep.step_type', '==', 'StepType.MID', 'asse...
593,880
Xianpeng919/MonoCon
hrfpn.py
HRFPN.init_weights
init_weights
Initialize the weights of module.
[ "Initialize", "the", "weights", "of", "module." ]
def init_weights(self): for m in self.modules(): if isinstance(m, nn.Conv2d): caffe2_xavier_init(m)
['def', 'init_weights(self):', 'for', 'm', 'in', 'self.modules():', 'if', 'isinstance(m,', 'nn.Conv2d):', 'caffe2_xavier_init(m)']
654,052
mrahtz/learning-from-human-preferences
reward_predictor_test.py
TestRewardPredictor.test_batchnorm_sharing
test_batchnorm_sharing
Check that batchnorm statistics are the same between the two legs of the network.
[ "Check", "that", "batchnorm", "statistics", "are", "the", "same", "between", "the", "two", "legs", "of", "the", "network." ]
def test_batchnorm_sharing(self): n_frames = 20 s1 = 255 * np.random.normal(loc=1.0, size=(n_frames, 84, 84, 4)) s2 = 255 * np.random.normal(loc=-1.0, size=(n_frames, 84, 84, 4)) feed_dict = {self.rpn.s1: [s1], self.rpn.s2: [s2], self.rpn.pref: [[0.0, 1.0]], self.rpn.training: True} self.sess.run(se...
['def', 'test_batchnorm_sharing(self):', 'n_frames', '=', '20', 's1', '=', '255', '*', 'np.random.normal(loc=1.0,', 'size=(n_frames,', '84,', '84,', '4))', 's2', '=', '255', '*', 'np.random.normal(loc=-1.0,', 'size=(n_frames,', '84,', '84,', '4))', 'feed_dict', '=', '{self.rpn.s1:', '[s1],', 'self.rpn.s2:', '[s2],', 's...
262,137
wzwtrevor/Multi-Scale-One-Class-Recurrent--
utils.py
Corpus.vectorize
vectorize
Tokenizes a text file.
[ "Tokenizes", "a", "text", "file." ]
def vectorize(self, seqs, bad): n_seq = len(seqs) data = torch.zeros((n_seq, self.max_len), dtype=torch.long) label = torch.zeros(n_seq, dtype=torch.long) for (i, word_ids) in enumerate(seqs): if i < bad: label[i] = 1 else: label[i] = 0 for (j, word_id) in...
['def', 'vectorize(self,', 'seqs,', 'bad):', 'n_seq', '=', 'len(seqs)', 'data', '=', 'torch.zeros((n_seq,', 'self.max_len),', 'dtype=torch.long)', 'label', '=', 'torch.zeros(n_seq,', 'dtype=torch.long)', 'for', '(i,', 'word_ids)', 'in', 'enumerate(seqs):', 'if', 'i', '<', 'bad:', 'label[i]', '=', '1', 'else:', 'label[i...
265,765
open-mmlab/OpenPCDet
hungarian_assigner.py
height_overlaps
height_overlaps
Calculate height overlaps of two boxes.
[ "Calculate", "height", "overlaps", "of", "two", "boxes." ]
def height_overlaps(boxes1, boxes2): boxes1_top_height = (boxes1[:, 2] + boxes1[:, 5]).view(-1, 1) boxes1_bottom_height = boxes1[:, 2].view(-1, 1) boxes2_top_height = (boxes2[:, 2] + boxes2[:, 5]).view(1, -1) boxes2_bottom_height = boxes2[:, 2].view(1, -1) heighest_of_bottom = torch.max(boxes1_botto...
['def', 'height_overlaps(boxes1,', 'boxes2):', 'boxes1_top_height', '=', '(boxes1[:,', '2]', '+', 'boxes1[:,', '5]).view(-1,', '1)', 'boxes1_bottom_height', '=', 'boxes1[:,', '2].view(-1,', '1)', 'boxes2_top_height', '=', '(boxes2[:,', '2]', '+', 'boxes2[:,', '5]).view(1,', '-1)', 'boxes2_bottom_height', '=', 'boxes2[:...
757,377
ddbourgin/numpy-ml
w2v.py
Word2Vec.backward
backward
Compute the gradient of the loss wrt the current network parameters.
[ "Compute", "the", "gradient", "of", "the", "loss", "wrt", "the", "current", "network", "parameters." ]
def backward(self): dX_emb = self.loss.grad(retain_grads=True, update_params=False) self.embeddings.backward(dX_emb)
['def', 'backward(self):', 'dX_emb', '=', 'self.loss.grad(retain_grads=True,', 'update_params=False)', 'self.embeddings.backward(dX_emb)']
730,227
matsu0228/nlp-jp
widget.py
Widget.add_traits
add_traits
Dynamically add trait attributes to the Widget.
[ "Dynamically", "add", "trait", "attributes", "to", "the", "Widget." ]
def add_traits(self, **traits): super(Widget, self).add_traits(**traits) for (name, trait) in traits.items(): if trait.get_metadata('sync'): self.keys.append(name) self.send_state(name)
['def', 'add_traits(self,', '**traits):', 'super(Widget,', 'self).add_traits(**traits)', 'for', '(name,', 'trait)', 'in', 'traits.items():', 'if', "trait.get_metadata('sync'):", 'self.keys.append(name)', 'self.send_state(name)']
787,618
TheCurryMan/MedicAI
test_basic.py
test_findable
test_findable
Make sure pkg_resources can find us.
[ "Make", "sure", "pkg_resources", "can", "find", "us." ]
def test_findable(): assert pkg_resources.working_set.by_key['wheel'].version
['def', 'test_findable():', 'assert', "pkg_resources.working_set.by_key['wheel'].version"]
649,957
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
wmt_utils.py
get_wmt_enfr_train_set
get_wmt_enfr_train_set
Download the WMT en-fr training corpus to directory unless it's there.
[ "Download", "the", "WMT", "en-fr", "training", "corpus", "to", "directory", "unless", "it's", "there." ]
def get_wmt_enfr_train_set(directory): train_path = os.path.join(directory, 'giga-fren.release2.fixed') if not (tf.gfile.Exists(train_path + '.fr') and tf.gfile.Exists(train_path + '.en')): corpus_file = maybe_download(directory, 'training-giga-fren.tar', _WMT_ENFR_TRAIN_URL) print('Extracting t...
['def', 'get_wmt_enfr_train_set(directory):', 'train_path', '=', 'os.path.join(directory,', "'giga-fren.release2.fixed')", 'if', 'not', '(tf.gfile.Exists(train_path', '+', "'.fr')", 'and', 'tf.gfile.Exists(train_path', '+', "'.en')):", 'corpus_file', '=', 'maybe_download(directory,', "'training-giga-fren.tar',", '_WMT_...
56,525
famura/SimuRLacra
stopping_criterion.py
StoppingCriterion.suppress_next_reset
suppress_next_reset
Suppresses the next reset call as described in `reset`.
[ "Suppresses", "the", "next", "reset", "call", "as", "described", "in", "`reset`." ]
def suppress_next_reset(self) -> NoReturn: self._suppress_next_reset = True
['def', 'suppress_next_reset(self)', '->', 'NoReturn:', 'self._suppress_next_reset', '=', 'True']
883,578
SamsungLabs/fcaf3d
box_np_ops.py
camera_to_lidar
camera_to_lidar
Convert points in camera coordinate to lidar coordinate.
[ "Convert", "points", "in", "camera", "coordinate", "to", "lidar", "coordinate." ]
def camera_to_lidar(points, r_rect, velo2cam): points_shape = list(points.shape[0:-1]) if points.shape[-1] == 3: points = np.concatenate([points, np.ones(points_shape + [1])], axis=-1) lidar_points = points @ np.linalg.inv((r_rect @ velo2cam).T) return lidar_points[..., :3]
['def', 'camera_to_lidar(points,', 'r_rect,', 'velo2cam):', 'points_shape', '=', 'list(points.shape[0:-1])', 'if', 'points.shape[-1]', '==', '3:', 'points', '=', 'np.concatenate([points,', 'np.ones(points_shape', '+', '[1])],', 'axis=-1)', 'lidar_points', '=', 'points', '@', 'np.linalg.inv((r_rect', '@', 'velo2cam).T)'...
560,102
lloydwindrim/hyperspectral-autoencoders
autoencoder.py
cnn_1D_network.decoder
decoder
Extract the reconstruction of some dataSamples from their latent representation encoding using a trained model.
[ "Extract", "the", "reconstruction", "of", "some", "dataSamples", "from", "their", "latent", "representation", "encoding", "using", "a", "trained", "model." ]
def decoder(self, modelName, dataZ): with tf.Session() as sess: net_ops.load_model(self.modelsAddrs[modelName], sess) dataY_recon = sess.run(self.y_recon, feed_dict={self.z: dataZ}) return dataY_recon
['def', 'decoder(self,', 'modelName,', 'dataZ):', 'with', 'tf.Session()', 'as', 'sess:', 'net_ops.load_model(self.modelsAddrs[modelName],', 'sess)', 'dataY_recon', '=', 'sess.run(self.y_recon,', 'feed_dict={self.z:', 'dataZ})', 'return', 'dataY_recon']
228,151
megvii-research/MSCL
test_head.py
test_fbo_head
test_fbo_head
Test layer construction, attributes and forward function in fbo head.
[ "Test", "layer", "construction,", "attributes", "and", "forward", "function", "in", "fbo", "head." ]
def test_fbo_head(): lfb_prefix_path = osp.normpath(osp.join(osp.dirname(__file__), '../data/lfb')) st_feat_shape = (1, 16, 1, 8, 8) st_feat = generate_backbone_demo_inputs(st_feat_shape) rois = torch.randn(1, 5) rois[0][0] = 0 img_metas = [dict(img_key='video_1, 930')] fbo_head = FBOHead(lf...
['def', 'test_fbo_head():', 'lfb_prefix_path', '=', 'osp.normpath(osp.join(osp.dirname(__file__),', "'../data/lfb'))", 'st_feat_shape', '=', '(1,', '16,', '1,', '8,', '8)', 'st_feat', '=', 'generate_backbone_demo_inputs(st_feat_shape)', 'rois', '=', 'torch.randn(1,', '5)', 'rois[0][0]', '=', '0', 'img_metas', '=', "[di...
264,995
flavioschneider/rl-transfer-
ddpg_pendulum.py
ddpg_pendulum
ddpg_pendulum
Train DDPG with InvertedDoublePendulum-v2 environment.
[ "Train", "DDPG", "with", "InvertedDoublePendulum-v2", "environment." ]
def ddpg_pendulum(ctxt=None, seed=1, lr=0.0001): set_seed(seed) trainer = Trainer(ctxt) env = normalize(GymEnv('InvertedDoublePendulum-v2')) policy = DeterministicMLPPolicy(env_spec=env.spec, hidden_sizes=[64, 64], hidden_nonlinearity=F.relu, output_nonlinearity=torch.tanh) exploration_policy = AddO...
['def', 'ddpg_pendulum(ctxt=None,', 'seed=1,', 'lr=0.0001):', 'set_seed(seed)', 'trainer', '=', 'Trainer(ctxt)', 'env', '=', "normalize(GymEnv('InvertedDoublePendulum-v2'))", 'policy', '=', 'DeterministicMLPPolicy(env_spec=env.spec,', 'hidden_sizes=[64,', '64],', 'hidden_nonlinearity=F.relu,', 'output_nonlinearity=torc...
861,119
enlite-ai/maze
replay_recorded_actions_policy.py
ReplayRecordedActionsPolicy.needs_env
needs_env
This policy does not require the env object to compute the action.
[ "This", "policy", "does", "not", "require", "the", "env", "object", "to", "compute", "the", "action." ]
def needs_env(self) -> bool: return True
['def', 'needs_env(self)', '->', 'bool:', 'return', 'True']
646,505
syrusakbary/interpy
six.py
iterlists
iterlists
Return an iterator over the (key, [values]) pairs of a dictionary.
[ "Return", "an", "iterator", "over", "the", "(key,", "[values])", "pairs", "of", "a", "dictionary." ]
def iterlists(d, **kw): return iter(getattr(d, _iterlists)(**kw))
['def', 'iterlists(d,', '**kw):', 'return', 'iter(getattr(d,', '_iterlists)(**kw))']
245,709
POSTECH-IMLAB/LaneSegmentationNetwork
preprocessing.py
flip_left_right_image_and_label
flip_left_right_image_and_label
Randomly flip an image and label horizontally (left to right).
[ "Randomly", "flip", "an", "image", "and", "label", "horizontally", "(left", "to", "right)." ]
def flip_left_right_image_and_label(image, label): image = tf.reverse(image, [1]) label = tf.reverse(label, [1]) return (image, label)
['def', 'flip_left_right_image_and_label(image,', 'label):', 'image', '=', 'tf.reverse(image,', '[1])', 'label', '=', 'tf.reverse(label,', '[1])', 'return', '(image,', 'label)']
623,419
sunishsheth2009/ChatterBot
dynamic.py
mixin_user_query
mixin_user_query
Return a new class with AppenderQuery functionality layered over.
[ "Return", "a", "new", "class", "with", "AppenderQuery", "functionality", "layered", "over." ]
def mixin_user_query(cls): name = 'Appender' + cls.__name__ return type(name, (AppenderMixin, cls), {'query_class': cls})
['def', 'mixin_user_query(cls):', 'name', '=', "'Appender'", '+', 'cls.__name__', 'return', 'type(name,', '(AppenderMixin,', 'cls),', "{'query_class':", 'cls})']
534,553
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
controller.py
Controller.convert_from_batched_episodes
convert_from_batched_episodes
Convert time-major batch of episodes to batch-major list of episodes.
[ "Convert", "time-major", "batch", "of", "episodes", "to", "batch-major", "list", "of", "episodes." ]
def convert_from_batched_episodes(self, initial_state, observations, actions, rewards, terminated, pads): rewards = np.array(rewards) pads = np.array(pads) observations = [np.array(obs) for obs in observations] actions = [np.array(act) for act in actions] total_rewards = np.sum(rewards * (1 - pads),...
['def', 'convert_from_batched_episodes(self,', 'initial_state,', 'observations,', 'actions,', 'rewards,', 'terminated,', 'pads):', 'rewards', '=', 'np.array(rewards)', 'pads', '=', 'np.array(pads)', 'observations', '=', '[np.array(obs)', 'for', 'obs', 'in', 'observations]', 'actions', '=', '[np.array(act)', 'for', 'act...
26,066
bryonkucharski/Language-Modeling-to-Generate-Lyrics-for-Hip-Hop-and-Gospel-Songs
generate.py
read_file
read_file
Read the full text of a file.
[ "Read", "the", "full", "text", "of", "a", "file." ]
def read_file(filename): with open(filename, encoding='latin-1') as f: return f.read()
['def', 'read_file(filename):', 'with', 'open(filename,', "encoding='latin-1')", 'as', 'f:', 'return', 'f.read()']
623,581
GGmorello/fl_gan
mnist_shard_descriptor.py
MnistShardDescriptor.sample_shape
sample_shape
Return the sample shape info.
[ "Return", "the", "sample", "shape", "info." ]
def sample_shape(self): return ['784']
['def', 'sample_shape(self):', 'return', "['784']"]
607,929
43Carrig/recurrent_neural_networks_practice
math_utils.py
clip_covariance
clip_covariance
Enforce constraints on a covariance matrix to improve numerical stability.
[ "Enforce", "constraints", "on", "a", "covariance", "matrix", "to", "improve", "numerical", "stability." ]
def clip_covariance(covariance_matrix, maximum_variance_ratio, minimum_variance): diagonal = array_ops.matrix_diag_part(covariance_matrix) maximum = math_ops.reduce_max(diagonal, axis=-1, keepdims=True) new_diagonal = gen_math_ops.maximum(diagonal, maximum / maximum_variance_ratio) return array_ops.matr...
['def', 'clip_covariance(covariance_matrix,', 'maximum_variance_ratio,', 'minimum_variance):', 'diagonal', '=', 'array_ops.matrix_diag_part(covariance_matrix)', 'maximum', '=', 'math_ops.reduce_max(diagonal,', 'axis=-1,', 'keepdims=True)', 'new_diagonal', '=', 'gen_math_ops.maximum(diagonal,', 'maximum', '/', 'maximum_...
335,415
deepmind/dm_control
acrobot.py
swingup_sparse
swingup_sparse
Returns Acrobot sparse balance.
[ "Returns", "Acrobot", "sparse", "balance." ]
def swingup_sparse(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None): physics = Physics.from_xml_string(*get_model_and_assets()) task = Balance(sparse=True, random=random) environment_kwargs = environment_kwargs or {} return control.Environment(physics, task, time_limit=time_limit, *...
['def', 'swingup_sparse(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None):', 'physics', '=', 'Physics.from_xml_string(*get_model_and_assets())', 'task', '=', 'Balance(sparse=True,', 'random=random)', 'environment_kwargs', '=', 'environment_kwargs', 'or', '{}', 'return', 'control.Environment(ph...
165,368
gunthercox/ChatterBot
sorting.py
Facets.add_facets
add_facets
Adds the contents of the given ``Facets`` or ``dict`` object to this object.
[ "Adds", "the", "contents", "of", "the", "given", "``Facets``", "or", "``dict``", "object", "to", "this", "object." ]
def add_facets(self, facets, replace=True): if not isinstance(facets, (dict, Facets)): raise Exception('%r is not a Facets object or dict' % facets) for (name, facet) in facets.items(): if replace or name not in self.facets: self.facets[name] = facet return self
['def', 'add_facets(self,', 'facets,', 'replace=True):', 'if', 'not', 'isinstance(facets,', '(dict,', 'Facets)):', 'raise', "Exception('%r", 'is', 'not', 'a', 'Facets', 'object', 'or', "dict'", '%', 'facets)', 'for', '(name,', 'facet)', 'in', 'facets.items():', 'if', 'replace', 'or', 'name', 'not', 'in', 'self.facets:'...
484,218
implus/GFocalV2
test_mixins.py
MaskTestMixin.aug_test_mask
aug_test_mask
Test for mask head with test time augmentation.
[ "Test", "for", "mask", "head", "with", "test", "time", "augmentation." ]
def aug_test_mask(self, feats, img_metas, det_bboxes, det_labels): if det_bboxes.shape[0] == 0: segm_result = [[] for _ in range(self.mask_head.num_classes)] else: aug_masks = [] for (x, img_meta) in zip(feats, img_metas): img_shape = img_meta[0]['img_shape'] scal...
['def', 'aug_test_mask(self,', 'feats,', 'img_metas,', 'det_bboxes,', 'det_labels):', 'if', 'det_bboxes.shape[0]', '==', '0:', 'segm_result', '=', '[[]', 'for', '_', 'in', 'range(self.mask_head.num_classes)]', 'else:', 'aug_masks', '=', '[]', 'for', '(x,', 'img_meta)', 'in', 'zip(feats,', 'img_metas):', 'img_shape', '=...
557,749
dfalveargOT/Artificial-Intelligence
utils.py
element_wise_product
element_wise_product
Return vector as an element-wise product of vectors x and y.
[ "Return", "vector", "as", "an", "element-wise", "product", "of", "vectors", "x", "and", "y." ]
def element_wise_product(x, y): assert len(x) == len(y) return np.multiply(x, y)
['def', 'element_wise_product(x,', 'y):', 'assert', 'len(x)', '==', 'len(y)', 'return', 'np.multiply(x,', 'y)']
120,877
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
thinkplot.py
_Brewer.ClearIter
ClearIter
Sets the color iterator to None.
[ "Sets", "the", "color", "iterator", "to", "None." ]
def ClearIter(cls): cls.color_iter = None
['def', 'ClearIter(cls):', 'cls.color_iter', '=', 'None']
18,934
FreshAirTonight/af2complex
all_atom_multimer.py
atom37_to_atom14
atom37_to_atom14
Convert Atom37 positions to Atom14 positions.
[ "Convert", "Atom37", "positions", "to", "Atom14", "positions." ]
def atom37_to_atom14(aatype, all_atom_pos, all_atom_mask): residx_atom14_to_atom37 = utils.batched_gather(jnp.asarray(RESTYPE_ATOM14_TO_ATOM37), aatype) atom14_mask = utils.batched_gather(all_atom_mask, residx_atom14_to_atom37, batch_dims=1).astype(jnp.float32) atom14_mask *= utils.batched_gather(jnp.asarra...
['def', 'atom37_to_atom14(aatype,', 'all_atom_pos,', 'all_atom_mask):', 'residx_atom14_to_atom37', '=', 'utils.batched_gather(jnp.asarray(RESTYPE_ATOM14_TO_ATOM37),', 'aatype)', 'atom14_mask', '=', 'utils.batched_gather(all_atom_mask,', 'residx_atom14_to_atom37,', 'batch_dims=1).astype(jnp.float32)', 'atom14_mask', '*=...
400,615
TJU-DRL-LAB/AI-Optimizer
bnn.py
BNN.create_prediction_tensors
create_prediction_tensors
See predict() above for documentation.
[ "See", "predict()", "above", "for", "documentation." ]
def create_prediction_tensors(self, inputs, expand_dimension, factored=False, *args, **kwargs): (factored_mean, factored_variance) = self._compile_outputs(inputs, expand_dimension) if inputs.shape.ndims == 2 and (not factored): mean = tf.reduce_mean(factored_mean, axis=0) variance = tf.reduce_me...
['def', 'create_prediction_tensors(self,', 'inputs,', 'expand_dimension,', 'factored=False,', '*args,', '**kwargs):', '(factored_mean,', 'factored_variance)', '=', 'self._compile_outputs(inputs,', 'expand_dimension)', 'if', 'inputs.shape.ndims', '==', '2', 'and', '(not', 'factored):', 'mean', '=', 'tf.reduce_mean(facto...
70,281
sktime/sktime
test_segment.py
test_bad_input_args
test_bad_input_args
Check that exception is raised for bad input args.
[ "Check", "that", "exception", "is", "raised", "for", "bad", "input", "args." ]
def test_bad_input_args(bad_interval): X = _make_nested_from_array(np.ones(10), n_instances=10, n_columns=2) with pytest.raises(ValueError): RandomIntervalSegmenter(n_intervals=bad_interval).fit(X)
['def', 'test_bad_input_args(bad_interval):', 'X', '=', '_make_nested_from_array(np.ones(10),', 'n_instances=10,', 'n_columns=2)', 'with', 'pytest.raises(ValueError):', 'RandomIntervalSegmenter(n_intervals=bad_interval).fit(X)']
877,756
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
conftest.py
as_series
as_series
Boolean fixture to support arr and Series(arr) comparison testing.
[ "Boolean", "fixture", "to", "support", "arr", "and", "Series(arr)", "comparison", "testing." ]
def as_series(request): return request.param
['def', 'as_series(request):', 'return', 'request.param']
83,391
shiwentao00/Molecule-RNN
train.py
sample
sample
Sample a batch of SMILES from current model.
[ "Sample", "a", "batch", "of", "SMILES", "from", "current", "model." ]
def sample(model, vocab, batch_size): model.eval() sampled_ints = model.sample(batch_size=batch_size, vocab=vocab, device=device) molecules = [] sampled_ints = sampled_ints.tolist() for ints in sampled_ints: molecule = [] for x in ints: if vocab.int2tocken[x] == '<eos>': ...
['def', 'sample(model,', 'vocab,', 'batch_size):', 'model.eval()', 'sampled_ints', '=', 'model.sample(batch_size=batch_size,', 'vocab=vocab,', 'device=device)', 'molecules', '=', '[]', 'sampled_ints', '=', 'sampled_ints.tolist()', 'for', 'ints', 'in', 'sampled_ints:', 'molecule', '=', '[]', 'for', 'x', 'in', 'ints:', '...
240,909
melfm/avod-ssd
avod_ssd_model.py
AvodSSDModel.create_path_drop_masks
create_path_drop_masks
Determines global path drop decision based on given probabilities.
[ "Determines", "global", "path", "drop", "decision", "based", "on", "given", "probabilities." ]
def create_path_drop_masks(self, p_img, p_bev, random_values): def keep_branch(): return tf.constant(1.0) def kill_branch(): return tf.constant(0.0) img_chances = tf.case([(tf.less(random_values[0], p_img), keep_branch)], default=kill_branch) bev_chances = tf.case([(tf.less(random_valu...
['def', 'create_path_drop_masks(self,', 'p_img,', 'p_bev,', 'random_values):', 'def', 'keep_branch():', 'return', 'tf.constant(1.0)', 'def', 'kill_branch():', 'return', 'tf.constant(0.0)', 'img_chances', '=', 'tf.case([(tf.less(random_values[0],', 'p_img),', 'keep_branch)],', 'default=kill_branch)', 'bev_chances', '=',...
420,960
scotthuang1989/object_detection_with_tensorflow
resnet_v1_test.py
ResnetUtilsTest.testEndPointsV1
testEndPointsV1
Test the end points of a tiny v1 bottleneck network.
[ "Test", "the", "end", "points", "of", "a", "tiny", "v1", "bottleneck", "network." ]
def testEndPointsV1(self): blocks = [resnet_v1.resnet_v1_block('block1', base_depth=1, num_units=2, stride=2), resnet_v1.resnet_v1_block('block2', base_depth=2, num_units=2, stride=1)] inputs = create_test_input(2, 32, 16, 3) with slim.arg_scope(resnet_utils.resnet_arg_scope()): (_, end_points) = se...
['def', 'testEndPointsV1(self):', 'blocks', '=', "[resnet_v1.resnet_v1_block('block1',", 'base_depth=1,', 'num_units=2,', 'stride=2),', "resnet_v1.resnet_v1_block('block2',", 'base_depth=2,', 'num_units=2,', 'stride=1)]', 'inputs', '=', 'create_test_input(2,', '32,', '16,', '3)', 'with', 'slim.arg_scope(resnet_utils.re...
739,663
CMihai998/Artificial-Intelligence
search.py
PlanRoute.h
h
Return the heuristic value for a given state.
[ "Return", "the", "heuristic", "value", "for", "a", "given", "state." ]
def h(self, node): (x1, y1) = node.state.get_location() (x2, y2) = self.goal return abs(x2 - x1) + abs(y2 - y1)
['def', 'h(self,', 'node):', '(x1,', 'y1)', '=', 'node.state.get_location()', '(x2,', 'y2)', '=', 'self.goal', 'return', 'abs(x2', '-', 'x1)', '+', 'abs(y2', '-', 'y1)']
117,982
danamyu/hedgehog_detector
data_utils.py
crawl_directory
crawl_directory
Crawls data directory and returns stuff.
[ "Crawls", "data", "directory", "and", "returns", "stuff." ]
def crawl_directory(directory, augment_with_rotations=False, first_label=0): label_idx = first_label images = [] labels = [] info = [] for (root, _, files) in os.walk(directory): logging.info('Reading files from %s', root) fileflag = 0 for file_name in files: full...
['def', 'crawl_directory(directory,', 'augment_with_rotations=False,', 'first_label=0):', 'label_idx', '=', 'first_label', 'images', '=', '[]', 'labels', '=', '[]', 'info', '=', '[]', 'for', '(root,', '_,', 'files)', 'in', 'os.walk(directory):', "logging.info('Reading", 'files', 'from', "%s',", 'root)', 'fileflag', '='...
589,781
akandykeller/NeuralWaveMachines
experiment.py
AbstractExperiment.restore_from_snapshot
restore_from_snapshot
Restores experiment state from a snapshot.
[ "Restores", "experiment", "state", "from", "a", "snapshot." ]
def restore_from_snapshot(self, snapshot_state: Mapping[str, jnp.ndarray]) -> None: def clear(attributes): for attr_name in attributes: if hasattr(self, attr_name): delattr(self, attr_name) def write(attributes, broadcast=False): for (attr_name, chk_name) in attribu...
['def', 'restore_from_snapshot(self,', 'snapshot_state:', 'Mapping[str,', 'jnp.ndarray])', '->', 'None:', 'def', 'clear(attributes):', 'for', 'attr_name', 'in', 'attributes:', 'if', 'hasattr(self,', 'attr_name):', 'delattr(self,', 'attr_name)', 'def', 'write(attributes,', 'broadcast=False):', 'for', '(attr_name,', 'chk...
293,611
arshpreetsingh/quantopian-machinelearning
popen_spawn.py
PopenSpawn.write
write
This is similar to send() except that there is no return value.
[ "This", "is", "similar", "to", "send()", "except", "that", "there", "is", "no", "return", "value." ]
def write(self, s): self.send(s)
['def', 'write(self,', 's):', 'self.send(s)']
890,938
ashwanitanwar/nmt-transfer-learning-xlm-r
metrics.py
reset
reset
Reset all metrics aggregators.
[ "Reset", "all", "metrics", "aggregators." ]
def reset() -> None: _aggregators.clear() _active_aggregators.clear() _active_aggregators_cnt.clear() _aggregators['default'] = MetersDict() _active_aggregators['default'] = _aggregators['default'] _active_aggregators_cnt['default'] = 1
['def', 'reset()', '->', 'None:', '_aggregators.clear()', '_active_aggregators.clear()', '_active_aggregators_cnt.clear()', "_aggregators['default']", '=', 'MetersDict()', "_active_aggregators['default']", '=', "_aggregators['default']", "_active_aggregators_cnt['default']", '=', '1']
731,987
openvinotoolkit/training_extensions
hpo.py
run_hpo
run_hpo
Run HPO and load optimized hyper parameter and best HPO model weight.
[ "Run", "HPO", "and", "load", "optimized", "hyper", "parameter", "and", "best", "HPO", "model", "weight." ]
def run_hpo(hpo_time_ratio: int, output: Path, environment: TaskEnvironment, dataset: DatasetEntity, data_roots: Dict[str, Dict]) -> Optional[TaskEnvironment]: task_type = environment.model_template.task_type if not _check_hpo_enabled_task(task_type): logger.warning(f'Currently supported task types are ...
['def', 'run_hpo(hpo_time_ratio:', 'int,', 'output:', 'Path,', 'environment:', 'TaskEnvironment,', 'dataset:', 'DatasetEntity,', 'data_roots:', 'Dict[str,', 'Dict])', '->', 'Optional[TaskEnvironment]:', 'task_type', '=', 'environment.model_template.task_type', 'if', 'not', '_check_hpo_enabled_task(task_type):', "logger...
918,968
qncsn2016/DeepGWC
utils.py
load_json_result
load_json_result
Load json from a path (directory + filename).
[ "Load", "json", "from", "a", "path", "(directory", "+", "filename)." ]
def load_json_result(best_result_name): result_path = os.path.join(RESULTS_DIR, best_result_name) with open(result_path, 'r') as f: return json.JSONDecoder().decode(f.read())
['def', 'load_json_result(best_result_name):', 'result_path', '=', 'os.path.join(RESULTS_DIR,', 'best_result_name)', 'with', 'open(result_path,', "'r')", 'as', 'f:', 'return', 'json.JSONDecoder().decode(f.read())']
520,693
ahthie7u/cockpit
plot.py
compute_markevery
compute_markevery
Compute number of points that will be dropped to compress the plot.
[ "Compute", "number", "of", "points", "that", "will", "be", "dropped", "to", "compress", "the", "plot." ]
def compute_markevery(data, max_points=200): num_points = len(data) markevery = max(num_points // max_points, 1) return markevery
['def', 'compute_markevery(data,', 'max_points=200):', 'num_points', '=', 'len(data)', 'markevery', '=', 'max(num_points', '//', 'max_points,', '1)', 'return', 'markevery']
493,206
pytorch/rl
tensor_specs.py
OneHotDiscreteTensorSpec.to_categorical
to_categorical
Converts a given one-hot tensor in categorical format.
[ "Converts", "a", "given", "one-hot", "tensor", "in", "categorical", "format." ]
def to_categorical(self, val: torch.Tensor, safe: bool=None) -> torch.Tensor: if safe is None: safe = _CHECK_SPEC_ENCODE if safe: self.assert_is_in(val) return val.long().argmax(-1)
['def', 'to_categorical(self,', 'val:', 'torch.Tensor,', 'safe:', 'bool=None)', '->', 'torch.Tensor:', 'if', 'safe', 'is', 'None:', 'safe', '=', '_CHECK_SPEC_ENCODE', 'if', 'safe:', 'self.assert_is_in(val)', 'return', 'val.long().argmax(-1)']
858,662
intel/neural-compressor
main.py
COCOmAPv2.reset
reset
Reset the prediction and labels.
[ "Reset", "the", "prediction", "and", "labels." ]
def reset(self): self.image_ids = [] self.ground_truth_list = [] self.detection_list = [] self.annotation_id = 1
['def', 'reset(self):', 'self.image_ids', '=', '[]', 'self.ground_truth_list', '=', '[]', 'self.detection_list', '=', '[]', 'self.annotation_id', '=', '1']
736,563
thaines/helit
model.py
Model.absorbModel
absorbModel
Given another model this absorbs all its samples, leaving the given model baren.
[ "Given", "another", "model", "this", "absorbs", "all", "its", "samples,", "leaving", "the", "given", "model", "baren." ]
def absorbModel(self, model): self.sample += model.sample model.sample = []
['def', 'absorbModel(self,', 'model):', 'self.sample', '+=', 'model.sample', 'model.sample', '=', '[]']
591,458
quantumiracle/Reinforcement_Learning_for_Traffic_Light_Control
mpi_util.py
setup_mpi_gpus
setup_mpi_gpus
Set CUDA_VISIBLE_DEVICES using MPI.
[ "Set", "CUDA_VISIBLE_DEVICES", "using", "MPI." ]
def setup_mpi_gpus(): num_gpus = gpu_count() if num_gpus == 0: return (local_rank, _) = get_local_rank_size(MPI.COMM_WORLD) os.environ['CUDA_VISIBLE_DEVICES'] = str(local_rank % num_gpus)
['def', 'setup_mpi_gpus():', 'num_gpus', '=', 'gpu_count()', 'if', 'num_gpus', '==', '0:', 'return', '(local_rank,', '_)', '=', 'get_local_rank_size(MPI.COMM_WORLD)', "os.environ['CUDA_VISIBLE_DEVICES']", '=', 'str(local_rank', '%', 'num_gpus)']
834,101
utiasASRL/hero_radar_odometry
radar.py
radar_polar_to_cartesian
radar_polar_to_cartesian
Convert a polar radar scan to cartesian.
[ "Convert", "a", "polar", "radar", "scan", "to", "cartesian." ]
def radar_polar_to_cartesian(azimuths, fft_data, radar_resolution, cart_resolution, cart_pixel_width, interpolate_crossover=True, navtech_version=CTS350): if cart_pixel_width % 2 == 0: cart_min_range = (cart_pixel_width / 2 - 0.5) * cart_resolution else: cart_min_range = cart_pixel_width // 2 * ...
['def', 'radar_polar_to_cartesian(azimuths,', 'fft_data,', 'radar_resolution,', 'cart_resolution,', 'cart_pixel_width,', 'interpolate_crossover=True,', 'navtech_version=CTS350):', 'if', 'cart_pixel_width', '%', '2', '==', '0:', 'cart_min_range', '=', '(cart_pixel_width', '/', '2', '-', '0.5)', '*', 'cart_resolution', '...
205,935
irdanish11/Seq2Seq-UrduChatBot
chat_command_handler.py
append_to_chatlog
append_to_chatlog
Append a question and answer to the chat log.
[ "Append", "a", "question", "and", "answer", "to", "the", "chat", "log." ]
def append_to_chatlog(chatlog_filepath, question, answer): chatlog_dir = os.path.dirname(chatlog_filepath) if not os.path.isdir(chatlog_dir): os.makedirs(chatlog_dir) with open(chatlog_filepath, 'a', encoding='utf-8') as file: file.write('You: {0}'.format(question)) file.write('\n') ...
['def', 'append_to_chatlog(chatlog_filepath,', 'question,', 'answer):', 'chatlog_dir', '=', 'os.path.dirname(chatlog_filepath)', 'if', 'not', 'os.path.isdir(chatlog_dir):', 'os.makedirs(chatlog_dir)', 'with', 'open(chatlog_filepath,', "'a',", "encoding='utf-8')", 'as', 'file:', "file.write('You:", "{0}'.format(question...
876,461
muhanzhang/D-VAE
opt.py
scalarconsts_rest
scalarconsts_rest
Partition a list of variables into two kinds: scalar constants, and the rest.
[ "Partition", "a", "list", "of", "variables", "into", "two", "kinds:", "scalar", "constants,", "and", "the", "rest." ]
def scalarconsts_rest(inputs): consts = [] origconsts = [] nonconsts = [] for i in inputs: try: v = get_scalar_constant_value(i) consts.append(v) origconsts.append(i) except NotScalarConstantError: nonconsts.append(i) return (consts, or...
['def', 'scalarconsts_rest(inputs):', 'consts', '=', '[]', 'origconsts', '=', '[]', 'nonconsts', '=', '[]', 'for', 'i', 'in', 'inputs:', 'try:', 'v', '=', 'get_scalar_constant_value(i)', 'consts.append(v)', 'origconsts.append(i)', 'except', 'NotScalarConstantError:', 'nonconsts.append(i)', 'return', '(consts,', 'origco...
525,512
zcablii/LSKNet
gaussian_dist_loss.py
jd_loss
jd_loss
Symmetrical Kullback-Leibler Divergence loss.
[ "Symmetrical", "Kullback-Leibler", "Divergence", "loss." ]
def jd_loss(pred, target, fun='log1p', tau=1.0, alpha=1.0, sqrt=True): jd = kld_loss(pred, target, fun='none', tau=0, alpha=alpha, sqrt=False, reduction='none') jd = jd + kld_loss(target, pred, fun='none', tau=0, alpha=alpha, sqrt=False, reduction='none') jd = jd * 0.5 if sqrt: jd = jd.clamp(1e-...
['def', 'jd_loss(pred,', 'target,', "fun='log1p',", 'tau=1.0,', 'alpha=1.0,', 'sqrt=True):', 'jd', '=', 'kld_loss(pred,', 'target,', "fun='none',", 'tau=0,', 'alpha=alpha,', 'sqrt=False,', "reduction='none')", 'jd', '=', 'jd', '+', 'kld_loss(target,', 'pred,', "fun='none',", 'tau=0,', 'alpha=alpha,', 'sqrt=False,', "re...
616,210
ForrestPi/ObjectDetection
augmentations.py
up_down_flip
up_down_flip
Randomly flip the given PIL Image.
[ "Randomly", "flip", "the", "given", "PIL", "Image." ]
def up_down_flip(img, boxes): if random.random() < 0.5: img = img.transpose(Image.FLIP_TOP_BOTTOM) h = img.height ymin = h - boxes[:, 3] ymax = h - boxes[:, 1] boxes[:, 1] = ymin boxes[:, 3] = ymax return (img, boxes)
['def', 'up_down_flip(img,', 'boxes):', 'if', 'random.random()', '<', '0.5:', 'img', '=', 'img.transpose(Image.FLIP_TOP_BOTTOM)', 'h', '=', 'img.height', 'ymin', '=', 'h', '-', 'boxes[:,', '3]', 'ymax', '=', 'h', '-', 'boxes[:,', '1]', 'boxes[:,', '1]', '=', 'ymin', 'boxes[:,', '3]', '=', 'ymax', 'return', '(img,', 'bo...
754,584
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
dist.py
fix_help_options
fix_help_options
Convert a 4-tuple 'help_options' list as found in various command classes to the 3-tuple form required by FancyGetopt.
[ "Convert", "a", "4-tuple", "'help_options'", "list", "as", "found", "in", "various", "command", "classes", "to", "the", "3-tuple", "form", "required", "by", "FancyGetopt." ]
def fix_help_options(options): new_options = [] for help_tuple in options: new_options.append(help_tuple[0:3]) return new_options
['def', 'fix_help_options(options):', 'new_options', '=', '[]', 'for', 'help_tuple', 'in', 'options:', 'new_options.append(help_tuple[0:3])', 'return', 'new_options']
430,304
triaquae/triaquae
views.py
Feed.item_extra_kwargs
item_extra_kwargs
Returns an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator.
[ "Returns", "an", "extra", "keyword", "arguments", "dictionary", "that", "is", "used", "with", "the", "`add_item`", "call", "of", "the", "feed", "generator." ]
def item_extra_kwargs(self, item): return {}
['def', 'item_extra_kwargs(self,', 'item):', 'return', '{}']
358,224
lancopku/Graph-to-seq-comment-generation
girvan_newman.py
stop_condition
stop_condition
Given a graph, decide whether stop community detection or not.
[ "Given", "a", "graph,", "decide", "whether", "stop", "community", "detection", "or", "not." ]
def stop_condition(g): graph_size = g.num_vertices() max_c_size = 10 min_c_size = 3 if graph_size <= min_c_size: return True possible_path = min(graph_size * (graph_size - 1) / 2, max_c_size * (max_c_size - 1) / 2) threshold = 1.0 * math.log(possible_path) / math.log(2) + 1 (bv, be) ...
['def', 'stop_condition(g):', 'graph_size', '=', 'g.num_vertices()', 'max_c_size', '=', '10', 'min_c_size', '=', '3', 'if', 'graph_size', '<=', 'min_c_size:', 'return', 'True', 'possible_path', '=', 'min(graph_size', '*', '(graph_size', '-', '1)', '/', '2,', 'max_c_size', '*', '(max_c_size', '-', '1)', '/', '2)', 'thre...
580,374
microsoft/nni
flop_utils.py
conv_flop_jit
conv_flop_jit
Count flops for convolution.
[ "Count", "flops", "for", "convolution." ]
def conv_flop_jit(inputs: List[Any], outputs: List[Any]): (x, w) = inputs[:2] (x_shape, w_shape, out_shape) = (x.shape, w.shape, outputs[0].shape) transposed = inputs[6] return conv_flop_count(x_shape, w_shape, out_shape, transposed=transposed)
['def', 'conv_flop_jit(inputs:', 'List[Any],', 'outputs:', 'List[Any]):', '(x,', 'w)', '=', 'inputs[:2]', '(x_shape,', 'w_shape,', 'out_shape)', '=', '(x.shape,', 'w.shape,', 'outputs[0].shape)', 'transposed', '=', 'inputs[6]', 'return', 'conv_flop_count(x_shape,', 'w_shape,', 'out_shape,', 'transposed=transposed)']
728,474
jgwak/GSDN
utils.py
evaluate_temporal_average
evaluate_temporal_average
Take average of output across temporal dimension for the same 3D coordinates.
[ "Take", "average", "of", "output", "across", "temporal", "dimension", "for", "the", "same", "3D", "coordinates." ]
def evaluate_temporal_average(output, coords): for i in range(coords[:, -1].max().item() + 1): batch_mask = coords[:, -1] == i batch_coords = coords[batch_mask, :3].numpy() batch_temporal = coords[batch_mask, -2].numpy() assert batch_coords.min() >= 0 ravel_idx = np.ravel_mul...
['def', 'evaluate_temporal_average(output,', 'coords):', 'for', 'i', 'in', 'range(coords[:,', '-1].max().item()', '+', '1):', 'batch_mask', '=', 'coords[:,', '-1]', '==', 'i', 'batch_coords', '=', 'coords[batch_mask,', ':3].numpy()', 'batch_temporal', '=', 'coords[batch_mask,', '-2].numpy()', 'assert', 'batch_coords.mi...
571,909
hamza-murad/AALU
discovery_v2.py
Notice.from_dict
from_dict
Initialize a Notice object from a json dictionary.
[ "Initialize", "a", "Notice", "object", "from", "a", "json", "dictionary." ]
def from_dict(cls, _dict: Dict) -> 'Notice': args = {} valid_keys = ['notice_id', 'created', 'document_id', 'collection_id', 'query_id', 'severity', 'step', 'description'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError('Unrecognized keys detected in dictionary for c...
['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'Notice':", 'args', '=', '{}', 'valid_keys', '=', "['notice_id',", "'created',", "'document_id',", "'collection_id',", "'query_id',", "'severity',", "'step',", "'description']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', ...
5,754
jimtin/Stock_Comparison
sysinfo.py
get_sys_info
get_sys_info
Return useful information about IPython and the system, as a dict.
[ "Return", "useful", "information", "about", "IPython", "and", "the", "system,", "as", "a", "dict." ]
def get_sys_info(): p = os.path path = p.realpath(p.dirname(p.abspath(p.join(__file__, '..')))) return pkg_info(path)
['def', 'get_sys_info():', 'p', '=', 'os.path', 'path', '=', 'p.realpath(p.dirname(p.abspath(p.join(__file__,', "'..'))))", 'return', 'pkg_info(path)']
385,514
caiiiac/Machine-Learning-with-Python
git.py
Git.get_url
get_url
Return URL of the first remote encountered.
[ "Return", "URL", "of", "the", "first", "remote", "encountered." ]
def get_url(self, location): remotes = self.run_command(['config', '--get-regexp', 'remote\\..*\\.url'], show_stdout=False, cwd=location) remotes = remotes.splitlines() found_remote = remotes[0] for remote in remotes: if remote.startswith('remote.origin.url '): found_remote = remote ...
['def', 'get_url(self,', 'location):', 'remotes', '=', "self.run_command(['config',", "'--get-regexp',", "'remote\\\\..*\\\\.url'],", 'show_stdout=False,', 'cwd=location)', 'remotes', '=', 'remotes.splitlines()', 'found_remote', '=', 'remotes[0]', 'for', 'remote', 'in', 'remotes:', 'if', "remote.startswith('remote.orig...
718,746
JonasLandman/QCNN
msvc.py
RegistryInfo.microsoft_sdk
microsoft_sdk
Microsoft SDK registry key.
[ "Microsoft", "SDK", "registry", "key." ]
def microsoft_sdk(self): return 'Microsoft SDKs'
['def', 'microsoft_sdk(self):', 'return', "'Microsoft", "SDKs'"]
303,684
Erfanafshar/Principles-and-Applications-of---graph-coloring
backend_bases.py
GraphicsContextBase.get_hatch_linewidth
get_hatch_linewidth
Get the hatch linewidth.
[ "Get", "the", "hatch", "linewidth." ]
def get_hatch_linewidth(self): return self._hatch_linewidth
['def', 'get_hatch_linewidth(self):', 'return', 'self._hatch_linewidth']
306,409
ruhyadi/yolo3d-lightning
kitti_dataset.py
DetectedObject.calc_theta_ray
calc_theta_ray
Calculate global angle of object, see paper.
[ "Calculate", "global", "angle", "of", "object,", "see", "paper." ]
def calc_theta_ray(self, img, box_2d, proj_matrix): width = img.shape[1] fovx = 2 * np.arctan(width / (2 * proj_matrix[0][0])) center = (box_2d[1][0] + box_2d[0][0]) / 2 dx = center - width / 2 mult = 1 if dx < 0: mult = -1 dx = abs(dx) angle = np.arctan(2 * dx * np.tan(fovx / 2)...
['def', 'calc_theta_ray(self,', 'img,', 'box_2d,', 'proj_matrix):', 'width', '=', 'img.shape[1]', 'fovx', '=', '2', '*', 'np.arctan(width', '/', '(2', '*', 'proj_matrix[0][0]))', 'center', '=', '(box_2d[1][0]', '+', 'box_2d[0][0])', '/', '2', 'dx', '=', 'center', '-', 'width', '/', '2', 'mult', '=', '1', 'if', 'dx', '<...
969,184
HDI-Project/ATM
test_data.py
test_download_demo_datasets_with_path
test_download_demo_datasets_with_path
Test downloading a demo dataset by giving a path.
[ "Test", "downloading", "a", "demo", "dataset", "by", "giving", "a", "path." ]
def test_download_demo_datasets_with_path(mock_boto3, mock_config, mock_mkdirs, mock_exists, mock_join): mock_exists.return_value = False datasets = 'test_dataset' result = data.download_demo(datasets, path='test_dir') mock_boto3.client.assert_called_once_with('s3', config=mock_config.return_value) ...
['def', 'test_download_demo_datasets_with_path(mock_boto3,', 'mock_config,', 'mock_mkdirs,', 'mock_exists,', 'mock_join):', 'mock_exists.return_value', '=', 'False', 'datasets', '=', "'test_dataset'", 'result', '=', 'data.download_demo(datasets,', "path='test_dir')", "mock_boto3.client.assert_called_once_with('s3',", '...
402,734
PaddlePaddle/Paddle3D
anchor3d_head.py
Anchor3DHead.get_bboxes_single
get_bboxes_single
Get bboxes of single branch.
[ "Get", "bboxes", "of", "single", "branch." ]
def get_bboxes_single(self, cls_scores, bbox_preds, dir_cls_preds, mlvl_anchors, input_meta, cfg=None, rescale=False): cfg = self.test_cfg if cfg is None else cfg assert len(cls_scores) == len(bbox_preds) == len(mlvl_anchors) mlvl_bboxes = [] mlvl_scores = [] mlvl_dir_scores = [] for (cls_score,...
['def', 'get_bboxes_single(self,', 'cls_scores,', 'bbox_preds,', 'dir_cls_preds,', 'mlvl_anchors,', 'input_meta,', 'cfg=None,', 'rescale=False):', 'cfg', '=', 'self.test_cfg', 'if', 'cfg', 'is', 'None', 'else', 'cfg', 'assert', 'len(cls_scores)', '==', 'len(bbox_preds)', '==', 'len(mlvl_anchors)', 'mlvl_bboxes', '=', '...
777,621
KalleHallden/InstaAutomator
__init__.py
BaseThread.stop
stop
Signals the thread to stop.
[ "Signals", "the", "thread", "to", "stop." ]
def stop(self): self._stopped_event.set() self.on_thread_stop()
['def', 'stop(self):', 'self._stopped_event.set()', 'self.on_thread_stop()']
245,174
NoGameNoLife00/mybolg
compiler.py
CodeGenerator.return_buffer_contents
return_buffer_contents
Return the buffer contents of the frame.
[ "Return", "the", "buffer", "contents", "of", "the", "frame." ]
def return_buffer_contents(self, frame): if frame.eval_ctx.volatile: self.writeline('if context.eval_ctx.autoescape:') self.indent() self.writeline('return Markup(concat(%s))' % frame.buffer) self.outdent() self.writeline('else:') self.indent() self.writeline(...
['def', 'return_buffer_contents(self,', 'frame):', 'if', 'frame.eval_ctx.volatile:', "self.writeline('if", "context.eval_ctx.autoescape:')", 'self.indent()', "self.writeline('return", "Markup(concat(%s))'", '%', 'frame.buffer)', 'self.outdent()', "self.writeline('else:')", 'self.indent()', "self.writeline('return", "co...
289,420
BillZito/transfer-learning
test_platform_util.py
test_platform_util_lscpu_parsing
test_platform_util_lscpu_parsing
Verifies that platform_utils gives us the proper values that we expect based on the lscpu_output string provided.
[ "Verifies", "that", "platform_utils", "gives", "us", "the", "proper", "values", "that", "we", "expect", "based", "on", "the", "lscpu_output", "string", "provided." ]
def test_platform_util_lscpu_parsing(get_cpuset_mock, platform_mock, subprocess_mock, os_mock): platform_mock.return_value = platform_config.SYSTEM_TYPE os_mock.return_value = True get_cpuset_mock.return_value = '0-111' subprocess_mock.return_value = platform_config.LSCPU_OUTPUT platform_util = Plat...
['def', 'test_platform_util_lscpu_parsing(get_cpuset_mock,', 'platform_mock,', 'subprocess_mock,', 'os_mock):', 'platform_mock.return_value', '=', 'platform_config.SYSTEM_TYPE', 'os_mock.return_value', '=', 'True', 'get_cpuset_mock.return_value', '=', "'0-111'", 'subprocess_mock.return_value', '=', 'platform_config.LSC...
927,480
opendilab/DI-star
remote_controller.py
RemoteController.observe
observe
Get a current observation.
[ "Get", "a", "current", "observation." ]
def observe(self, disable_fog=False, target_game_loop=0): obs = self._client.send(observation=sc_pb.RequestObservation(game_loop=target_game_loop, disable_fog=disable_fog)) if obs.observation.game_loop == 2 ** 32 - 1: logging.info('Received stub observation.') if not obs.player_result: ...
['def', 'observe(self,', 'disable_fog=False,', 'target_game_loop=0):', 'obs', '=', 'self._client.send(observation=sc_pb.RequestObservation(game_loop=target_game_loop,', 'disable_fog=disable_fog))', 'if', 'obs.observation.game_loop', '==', '2', '**', '32', '-', '1:', "logging.info('Received", 'stub', "observation.')", '...
184,747
fundamentalvision/Auto-Seg-Loss
test.py
single_gpu_test
single_gpu_test
Test with single GPU.
[ "Test", "with", "single", "GPU." ]
def single_gpu_test(model, data_loader, show=False, out_dir=None, efficient_test=False, opacity=0.5): model.eval() results = [] dataset = data_loader.dataset prog_bar = mmcv.ProgressBar(len(dataset)) for (i, data) in enumerate(data_loader): with torch.no_grad(): result = model(re...
['def', 'single_gpu_test(model,', 'data_loader,', 'show=False,', 'out_dir=None,', 'efficient_test=False,', 'opacity=0.5):', 'model.eval()', 'results', '=', '[]', 'dataset', '=', 'data_loader.dataset', 'prog_bar', '=', 'mmcv.ProgressBar(len(dataset))', 'for', '(i,', 'data)', 'in', 'enumerate(data_loader):', 'with', 'tor...
416,337
sek788432/Waymo-2D-Object-Detection
evaluator.py
MultiTaskEvaluator.evaluate
evaluate
Performs evaluation for each `EvalTask`.
[ "Performs", "evaluation", "for", "each", "`EvalTask`." ]
def evaluate(self, num_steps: tf.Tensor): for metric in self.validation_losses.values(): metric.reset_states() for metrics in self.validation_metrics.values(): for metric in metrics: metric.reset_states() results = {} eval_iters = tf.nest.map_structure(iter, self.eval_dataset...
['def', 'evaluate(self,', 'num_steps:', 'tf.Tensor):', 'for', 'metric', 'in', 'self.validation_losses.values():', 'metric.reset_states()', 'for', 'metrics', 'in', 'self.validation_metrics.values():', 'for', 'metric', 'in', 'metrics:', 'metric.reset_states()', 'results', '=', '{}', 'eval_iters', '=', 'tf.nest.map_struct...
972,378
salesforce/CodeRL
trainer_callback.py
TrainerState.save_to_json
save_to_json
Save the content of this instance in JSON format inside `json_path`.
[ "Save", "the", "content", "of", "this", "instance", "in", "JSON", "format", "inside", "`json_path`." ]
def save_to_json(self, json_path: str): json_string = json.dumps(dataclasses.asdict(self), indent=2, sort_keys=True) + '\n' with open(json_path, 'w', encoding='utf-8') as f: f.write(json_string)
['def', 'save_to_json(self,', 'json_path:', 'str):', 'json_string', '=', 'json.dumps(dataclasses.asdict(self),', 'indent=2,', 'sort_keys=True)', '+', "'\\n'", 'with', 'open(json_path,', "'w',", "encoding='utf-8')", 'as', 'f:', 'f.write(json_string)']
494,152
deepmind/meltingpot
scenario_factory.py
ScenarioFactory.action_spec
action_spec
Returns spec of action expected from a single focal player.
[ "Returns", "spec", "of", "action", "expected", "from", "a", "single", "focal", "player." ]
def action_spec(self) -> dm_env.specs.DiscreteArray: return self._substrate.action_spec()
['def', 'action_spec(self)', '->', 'dm_env.specs.DiscreteArray:', 'return', 'self._substrate.action_spec()']
285,936
AlibabaResearch/efficientteacher
autoaugment_utils.py
flip_only_bboxes
flip_only_bboxes
Apply flip_lr to each bbox in the image with probability prob.
[ "Apply", "flip_lr", "to", "each", "bbox", "in", "the", "image", "with", "probability", "prob." ]
def flip_only_bboxes(image, bboxes, prob): func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper(image, bboxes, prob, np.fliplr, func_changes_bbox)
['def', 'flip_only_bboxes(image,', 'bboxes,', 'prob):', 'func_changes_bbox', '=', 'False', 'prob', '=', '_scale_bbox_only_op_probability(prob)', 'return', '_apply_multi_bbox_augmentation_wrapper(image,', 'bboxes,', 'prob,', 'np.fliplr,', 'func_changes_bbox)']
561,017
yinyunie/ScenePriors
common_testing.py
TestCaseMixin.assertAllSeparate
assertAllSeparate
Verify that all tensors in tensor_list have their data in distinct locations.
[ "Verify", "that", "all", "tensors", "in", "tensor_list", "have", "their", "data", "in", "distinct", "locations." ]
def assertAllSeparate(self, tensor_list) -> None: ptrs = [i.storage().data_ptr() for i in tensor_list] self.assertCountEqual(ptrs, set(ptrs))
['def', 'assertAllSeparate(self,', 'tensor_list)', '->', 'None:', 'ptrs', '=', '[i.storage().data_ptr()', 'for', 'i', 'in', 'tensor_list]', 'self.assertCountEqual(ptrs,', 'set(ptrs))']
329,965
rlworkgroup/garage
add_ornstein_uhlenbeck_noise.py
AddOrnsteinUhlenbeckNoise.get_action
get_action
Return an action with noise.
[ "Return", "an", "action", "with", "noise." ]
def get_action(self, observation): (action, agent_infos) = self.policy.get_action(observation) ou_state = self._simulate() return (np.clip(action + ou_state, self._action_space.low, self._action_space.high), agent_infos)
['def', 'get_action(self,', 'observation):', '(action,', 'agent_infos)', '=', 'self.policy.get_action(observation)', 'ou_state', '=', 'self._simulate()', 'return', '(np.clip(action', '+', 'ou_state,', 'self._action_space.low,', 'self._action_space.high),', 'agent_infos)']
200,400
Alexander-Parker/youtube_nlp
service_account.py
IDTokenCredentials.service_account_email
service_account_email
The service account email.
[ "The", "service", "account", "email." ]
def service_account_email(self): return self._service_account_email
['def', 'service_account_email(self):', 'return', 'self._service_account_email']
970,087