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
paschalidoud/hierarchical_primitives
evaluate.py
distance_p2p
distance_p2p
Computes minimal distances of each point in points_src to points_tgt.
[ "Computes", "minimal", "distances", "of", "each", "point", "in", "points_src", "to", "points_tgt." ]
def distance_p2p(points_src, normals_src, points_tgt, normals_tgt): kdtree = KDTree(points_tgt) (dist, idx) = kdtree.query(points_src) if normals_src is not None and normals_tgt is not None: normals_src = normals_src / np.linalg.norm(normals_src, axis=-1, keepdims=True) normals_tgt = normals...
['def', 'distance_p2p(points_src,', 'normals_src,', 'points_tgt,', 'normals_tgt):', 'kdtree', '=', 'KDTree(points_tgt)', '(dist,', 'idx)', '=', 'kdtree.query(points_src)', 'if', 'normals_src', 'is', 'not', 'None', 'and', 'normals_tgt', 'is', 'not', 'None:', 'normals_src', '=', 'normals_src', '/', 'np.linalg.norm(normal...
206,492
napratin/lumos
input.py
InputRunner.update
update
Perform a single update iteration, return True/False to indicate continuation/exit.
[ "Perform", "a", "single", "update", "iteration,", "return", "True/False", "to", "indicate", "continuation/exit." ]
def update(self): try: self.context.update() if self.showFPS: timeDiff = self.context.timeNow - self.timeLast fps = 1.0 / timeDiff if timeDiff > 0.0 else 0.0 self.logger.info('{0:5.2f} fps'.format(fps)) if not self.isFrozen: if not self.inputDe...
['def', 'update(self):', 'try:', 'self.context.update()', 'if', 'self.showFPS:', 'timeDiff', '=', 'self.context.timeNow', '-', 'self.timeLast', 'fps', '=', '1.0', '/', 'timeDiff', 'if', 'timeDiff', '>', '0.0', 'else', '0.0', "self.logger.info('{0:5.2f}", "fps'.format(fps))", 'if', 'not', 'self.isFrozen:', 'if', 'not', ...
617,589
huawei-noah/xingtian
algorithm.py
Algorithm.get_weights
get_weights
Get the actor model weights as default.
[ "Get", "the", "actor", "model", "weights", "as", "default." ]
def get_weights(self): return self.actor.get_weights()
['def', 'get_weights(self):', 'return', 'self.actor.get_weights()']
962,081
Erfanafshar/Principles-and-Applications-of---graph-coloring
geo.py
GeoAxes.set_latitude_grid
set_latitude_grid
Set the number of degrees between each latitude grid.
[ "Set", "the", "number", "of", "degrees", "between", "each", "latitude", "grid." ]
def set_latitude_grid(self, degrees): grid = np.arange(-90 + degrees, 90, degrees) self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid))) self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))
['def', 'set_latitude_grid(self,', 'degrees):', 'grid', '=', 'np.arange(-90', '+', 'degrees,', '90,', 'degrees)', 'self.yaxis.set_major_locator(FixedLocator(np.deg2rad(grid)))', 'self.yaxis.set_major_formatter(self.ThetaFormatter(degrees))']
307,485
YanZiQinKevin/object_detection
dataset.py
prepare_test_data
prepare_test_data
Prepare relevant data for testing the model.
[ "Prepare", "relevant", "data", "for", "testing", "the", "model." ]
def prepare_test_data(args): image_dir = args.test_image_dir files = os.listdir(image_dir) files = [f for f in files if f.lower().endswith('.jpg')] img_ids = list(range(len(files))) img_files = [] img_heights = [] img_widths = [] for f in files: img_path = os.path.join(image_dir,...
['def', 'prepare_test_data(args):', 'image_dir', '=', 'args.test_image_dir', 'files', '=', 'os.listdir(image_dir)', 'files', '=', '[f', 'for', 'f', 'in', 'files', 'if', "f.lower().endswith('.jpg')]", 'img_ids', '=', 'list(range(len(files)))', 'img_files', '=', '[]', 'img_heights', '=', '[]', 'img_widths', '=', '[]', 'f...
744,979
ifwe/digsby
simplemenu.py
SimpleMenu.InsertItem
InsertItem
Insert an item to an index.
[ "Insert", "an", "item", "to", "an", "index." ]
def InsertItem(self, index, item): self.spine.items.insert(index, item) self.spine.ItemCount = len(self.spine.items)
['def', 'InsertItem(self,', 'index,', 'item):', 'self.spine.items.insert(index,', 'item)', 'self.spine.ItemCount', '=', 'len(self.spine.items)']
185,598
openvinotoolkit/training_extensions
task.py
ClassificationOpenVINOTask.optimize
optimize
Optimize function of ClassificationOpenVINOTask.
[ "Optimize", "function", "of", "ClassificationOpenVINOTask." ]
def optimize(self, optimization_type: OptimizationType, dataset: DatasetEntity, output_model: ModelEntity, optimization_parameters: Optional[OptimizationParameters]=None): if optimization_type is not OptimizationType.POT: raise ValueError('PTQ is the only supported optimization type for OpenVino models') ...
['def', 'optimize(self,', 'optimization_type:', 'OptimizationType,', 'dataset:', 'DatasetEntity,', 'output_model:', 'ModelEntity,', 'optimization_parameters:', 'Optional[OptimizationParameters]=None):', 'if', 'optimization_type', 'is', 'not', 'OptimizationType.POT:', 'raise', "ValueError('PTQ", 'is', 'the', 'only', 'su...
904,104
rudranil723/mini-main
autopep8.py
FixPEP8.fix_e301
fix_e301
Add missing blank line.
[ "Add", "missing", "blank", "line." ]
def fix_e301(self, result): cr = '\n' self.source[result['line'] - 1] = cr + self.source[result['line'] - 1]
['def', 'fix_e301(self,', 'result):', 'cr', '=', "'\\n'", "self.source[result['line']", '-', '1]', '=', 'cr', '+', "self.source[result['line']", '-', '1]']
313,911
kubeflow/pipelines
pipeline_with_metrics_outputs.py
output_metrics
output_metrics
Dummy component that outputs metrics with a random accuracy.
[ "Dummy", "component", "that", "outputs", "metrics", "with", "a", "random", "accuracy." ]
def output_metrics(metrics: Output[Metrics]): import random result = random.randint(0, 100) metrics.log_metric('accuracy', result)
['def', 'output_metrics(metrics:', 'Output[Metrics]):', 'import', 'random', 'result', '=', 'random.randint(0,', '100)', "metrics.log_metric('accuracy',", 'result)']
780,334
nilearn/nilearn
test_img_plotting.py
test_plot_with_nans
test_plot_with_nans
Smoke test for plotting functions with nans in data image.
[ "Smoke", "test", "for", "plotting", "functions", "with", "nans", "in", "data", "image." ]
def test_plot_with_nans(plot_func, img_3d_mni): plot_func(_add_nans_to_img(img_3d_mni))
['def', 'test_plot_with_nans(plot_func,', 'img_3d_mni):', 'plot_func(_add_nans_to_img(img_3d_mni))']
724,144
QData/deepWordBug
math2html.py
FormulaCommand.parsecommandtype
parsecommandtype
Parse a given command type.
[ "Parse", "a", "given", "command", "type." ]
def parsecommandtype(self, command, type, pos): bit = self.factory.create(type) bit.setcommand(command) returned = bit.parsebit(pos) if returned: return returned return bit
['def', 'parsecommandtype(self,', 'command,', 'type,', 'pos):', 'bit', '=', 'self.factory.create(type)', 'bit.setcommand(command)', 'returned', '=', 'bit.parsebit(pos)', 'if', 'returned:', 'return', 'returned', 'return', 'bit']
542,569
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
sessions.py
SessionRedirectMixin.rebuild_method
rebuild_method
When being redirected we may want to change the method of the request based on certain specs or browser behavior.
[ "When", "being", "redirected", "we", "may", "want", "to", "change", "the", "method", "of", "the", "request", "based", "on", "certain", "specs", "or", "browser", "behavior." ]
def rebuild_method(self, prepared_request, response): method = prepared_request.method if response.status_code == codes.see_other and method != 'HEAD': method = 'GET' if response.status_code == codes.found and method != 'HEAD': method = 'GET' if response.status_code == codes.moved and me...
['def', 'rebuild_method(self,', 'prepared_request,', 'response):', 'method', '=', 'prepared_request.method', 'if', 'response.status_code', '==', 'codes.see_other', 'and', 'method', '!=', "'HEAD':", 'method', '=', "'GET'", 'if', 'response.status_code', '==', 'codes.found', 'and', 'method', '!=', "'HEAD':", 'method', '='...
950,636
AboudyKreidieh/h-baselines
av_multi.py
AVOpenMultiAgentEnv.additional_command
additional_command
See definition in AVOpenEnv.
[ "See", "definition", "in", "AVOpenEnv." ]
def additional_command(self): super(AVOpenMultiAgentEnv, self).additional_command() (self.rl_queue, self.rl_veh, self.removed_veh) = update_rl_veh(self, rl_queue=self.rl_queue, rl_veh=self.rl_veh, removed_veh=self.removed_veh, control_range=self._control_range, num_rl=self.num_rl, rl_ids=reversed(sorted(self.k....
['def', 'additional_command(self):', 'super(AVOpenMultiAgentEnv,', 'self).additional_command()', '(self.rl_queue,', 'self.rl_veh,', 'self.removed_veh)', '=', 'update_rl_veh(self,', 'rl_queue=self.rl_queue,', 'rl_veh=self.rl_veh,', 'removed_veh=self.removed_veh,', 'control_range=self._control_range,', 'num_rl=self.num_r...
573,899
ifzhang/ByteTrack
setup_env.py
configure_nccl
configure_nccl
Configure multi-machine environment variables of NCCL.
[ "Configure", "multi-machine", "environment", "variables", "of", "NCCL." ]
def configure_nccl(): os.environ['NCCL_LAUNCH_MODE'] = 'PARALLEL' os.environ['NCCL_IB_HCA'] = subprocess.getoutput('pushd /sys/class/infiniband/ > /dev/null; for i in mlx5_*; do cat $i/ports/1/gid_attrs/types/* 2>/dev/null | grep v >/dev/null && echo $i ; done; popd > /dev/null') os.environ['NCCL_IB_GID_IND...
['def', 'configure_nccl():', "os.environ['NCCL_LAUNCH_MODE']", '=', "'PARALLEL'", "os.environ['NCCL_IB_HCA']", '=', "subprocess.getoutput('pushd", '/sys/class/infiniband/', '>', '/dev/null;', 'for', 'i', 'in', 'mlx5_*;', 'do', 'cat', '$i/ports/1/gid_attrs/types/*', '2>/dev/null', '|', 'grep', 'v', '>/dev/null', '&&', '...
410,723
caiostringari/deepwaves
minimum_bounding_geometry.py
call_main_with_surfaces_file
call_main_with_surfaces_file
Call the main program.
[ "Call", "the", "main", "program." ]
def call_main_with_surfaces_file(): ds = xr.open_dataset(args.input[0]) if args.debug: frame = plt.imread(args.frame[0]) outpath = 'debug_mbg' os.makedirs(outpath, exist_ok=True) scale = float(args.scale[0]) top_left_i = [] top_left_j = [] length = [] width = [] f...
['def', 'call_main_with_surfaces_file():', 'ds', '=', 'xr.open_dataset(args.input[0])', 'if', 'args.debug:', 'frame', '=', 'plt.imread(args.frame[0])', 'outpath', '=', "'debug_mbg'", 'os.makedirs(outpath,', 'exist_ok=True)', 'scale', '=', 'float(args.scale[0])', 'top_left_i', '=', '[]', 'top_left_j', '=', '[]', 'length...
540,980
Wuziyi616/Artificial_Intelligence_Project1
search_algorithm.py
Mask.try_element
try_element
Try placing an element on the grid.
[ "Try", "placing", "an", "element", "on", "the", "grid." ]
def try_element(self, element_id, start_x, start_y, start_angle): assert element_id in self.unused_element_ids assert start_x in range(self.grid.shape[0]) assert start_y in range(self.grid.shape[1]) element = Element(element_id) for x in range(start_x, self.grid.shape[0]): for y in range(sta...
['def', 'try_element(self,', 'element_id,', 'start_x,', 'start_y,', 'start_angle):', 'assert', 'element_id', 'in', 'self.unused_element_ids', 'assert', 'start_x', 'in', 'range(self.grid.shape[0])', 'assert', 'start_y', 'in', 'range(self.grid.shape[1])', 'element', '=', 'Element(element_id)', 'for', 'x', 'in', 'range(st...
92,198
hans/pyccg
test_lexicon.py
test_attempt_candidate_parse
test_attempt_candidate_parse
Find parse candidates even when the parse requires composition.
[ "Find", "parse", "candidates", "even", "when", "the", "parse", "requires", "composition." ]
def test_attempt_candidate_parse(): lex = Lexicon.fromstring('\n :- S, N\n\n gives => S\\N/N/N {\\o x y.give(x, y, o)}\n John => N {\\x.John(x)}\n Mark => N {\\x.Mark(x)}\n it => N {\\x.T}\n ', include_semantics=True) cand_category = lex.parse_category('S\\N/N/N') cand_expressions = [l.Expression.from...
['def', 'test_attempt_candidate_parse():', 'lex', '=', "Lexicon.fromstring('\\n", ':-', 'S,', 'N\\n\\n', 'gives', '=>', 'S\\\\N/N/N', '{\\\\o', 'x', 'y.give(x,', 'y,', 'o)}\\n', 'John', '=>', 'N', '{\\\\x.John(x)}\\n', 'Mark', '=>', 'N', '{\\\\x.Mark(x)}\\n', 'it', '=>', 'N', '{\\\\x.T}\\n', "',", 'include_semantics=Tr...
296,036
wandb/wandb
artifact.py
Artifact.project
project
The name of the project of the secondary (portfolio) artifact collection.
[ "The", "name", "of", "the", "project", "of", "the", "secondary", "(portfolio)", "artifact", "collection." ]
def project(self) -> str: self._ensure_logged('project') assert self._project is not None return self._project
['def', 'project(self)', '->', 'str:', "self._ensure_logged('project')", 'assert', 'self._project', 'is', 'not', 'None', 'return', 'self._project']
941,610
dmpelt/msdnet
gpuoperations.py
GPUImageData.relu
relu
Apply ReLU to single image.
[ "Apply", "ReLU", "to", "single", "image." ]
def relu(self, i): relu2d_cuda[self.bpg2d, self.tpb2d](self.arr, i)
['def', 'relu(self,', 'i):', 'relu2d_cuda[self.bpg2d,', 'self.tpb2d](self.arr,', 'i)']
265,129
bislara/Object-detection-GUI
inputs_test.py
InputsTest.test_force_no_resize
test_force_no_resize
Tests the functionality of force_no_reisze option.
[ "Tests", "the", "functionality", "of", "force_no_reisze", "option." ]
def test_force_no_resize(self): configs = _get_configs_for_model('ssd_inception_v2_pets') configs['eval_config'].force_no_resize = True eval_input_fn = inputs.create_eval_input_fn(eval_config=configs['eval_config'], eval_input_config=configs['eval_input_configs'][0], model_config=configs['model']) train...
['def', 'test_force_no_resize(self):', 'configs', '=', "_get_configs_for_model('ssd_inception_v2_pets')", "configs['eval_config'].force_no_resize", '=', 'True', 'eval_input_fn', '=', "inputs.create_eval_input_fn(eval_config=configs['eval_config'],", "eval_input_config=configs['eval_input_configs'][0],", "model_config=c...
726,321
yinyunie/ScenePriors
base.py
FeatureMap.forward_keys
forward_keys
Encode the keys `x` using this feature map.
[ "Encode", "the", "keys", "`x`", "using", "this", "feature", "map." ]
def forward_keys(self, x): return self(x)
['def', 'forward_keys(self,', 'x):', 'return', 'self(x)']
329,553
jbwang1997/CrossKD
test_yolof_head.py
TestYOLOFHead.test_yolof_head_loss
test_yolof_head_loss
Tests yolof head loss when truth is empty and non-empty.
[ "Tests", "yolof", "head", "loss", "when", "truth", "is", "empty", "and", "non-empty." ]
def test_yolof_head_loss(self): s = 256 img_metas = [{'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_shape': (s, s, 3)}] train_cfg = Config(dict(assigner=dict(type='UniformAssigner', pos_ignore_thr=0.15, neg_ignore_thr=0.7), allowed_border=-1, pos_weight=-1, debug=False)) yolof_head = YOLOFHead(num_cla...
['def', 'test_yolof_head_loss(self):', 's', '=', '256', 'img_metas', '=', "[{'img_shape':", '(s,', 's,', '3),', "'scale_factor':", '1,', "'pad_shape':", '(s,', 's,', '3)}]', 'train_cfg', '=', "Config(dict(assigner=dict(type='UniformAssigner',", 'pos_ignore_thr=0.15,', 'neg_ignore_thr=0.7),', 'allowed_border=-1,', 'pos_...
491,922
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
bulk_component.py
BulkAnnotatorComponentBuilder.build_greedy_inference
build_greedy_inference
Annotates a batch of documents using network scores.
[ "Annotates", "a", "batch", "of", "documents", "using", "network", "scores." ]
def build_greedy_inference(self, state, network_states, during_training=False): logging.info('Building component: %s', self.spec.name) if self.spec.fixed_feature: raise RuntimeError('Fixed features are not compatible with bulk annotation. Use the "bulk-features" component instead.') linked_embedding...
['def', 'build_greedy_inference(self,', 'state,', 'network_states,', 'during_training=False):', "logging.info('Building", 'component:', "%s',", 'self.spec.name)', 'if', 'self.spec.fixed_feature:', 'raise', "RuntimeError('Fixed", 'features', 'are', 'not', 'compatible', 'with', 'bulk', 'annotation.', 'Use', 'the', '"bulk...
28,025
open-mmlab/mmtracking
eval_mot.py
bbox_distances
bbox_distances
Calculate the IoU distances of two sets of boxes.
[ "Calculate", "the", "IoU", "distances", "of", "two", "sets", "of", "boxes." ]
def bbox_distances(bboxes1, bboxes2, iou_thr=0.5): ious = bbox_overlaps(bboxes1, bboxes2, mode='iou') distances = 1 - ious distances = np.where(distances > iou_thr, np.nan, distances) return distances
['def', 'bbox_distances(bboxes1,', 'bboxes2,', 'iou_thr=0.5):', 'ious', '=', 'bbox_overlaps(bboxes1,', 'bboxes2,', "mode='iou')", 'distances', '=', '1', '-', 'ious', 'distances', '=', 'np.where(distances', '>', 'iou_thr,', 'np.nan,', 'distances)', 'return', 'distances']
625,664
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform
test.py
Client.delete_cookie
delete_cookie
Deletes a cookie in the test client.
[ "Deletes", "a", "cookie", "in", "the", "test", "client." ]
def delete_cookie(self, server_name, key, path='/', domain=None): self.set_cookie(server_name, key, expires=0, max_age=0, path=path, domain=domain)
['def', 'delete_cookie(self,', 'server_name,', 'key,', "path='/',", 'domain=None):', 'self.set_cookie(server_name,', 'key,', 'expires=0,', 'max_age=0,', 'path=path,', 'domain=domain)']
84,953
tencent-ailab/TriNet
quantization_utils.py
Quantizer.begin_epoch
begin_epoch
Called at the beginning of each epoch (epochs start at 1).
[ "Called", "at", "the", "beginning", "of", "each", "epoch", "(epochs", "start", "at", "1)." ]
def begin_epoch(self, epoch): if self.epoch_schedule is not None and epoch > 0 and ((epoch - 1) % self.epoch_schedule == 0) or self.quantization_step == 0: self.step()
['def', 'begin_epoch(self,', 'epoch):', 'if', 'self.epoch_schedule', 'is', 'not', 'None', 'and', 'epoch', '>', '0', 'and', '((epoch', '-', '1)', '%', 'self.epoch_schedule', '==', '0)', 'or', 'self.quantization_step', '==', '0:', 'self.step()']
425,006
ADLab3Ds/TiG-BEV
sparse_unet.py
SparseUNet.reduce_channel
reduce_channel
reduce channel for element-wise addition.
[ "reduce", "channel", "for", "element-wise", "addition." ]
def reduce_channel(x, out_channels): features = x.features (n, in_channels) = features.shape assert in_channels % out_channels == 0 and in_channels >= out_channels x.features = features.view(n, out_channels, -1).sum(dim=2) return x
['def', 'reduce_channel(x,', 'out_channels):', 'features', '=', 'x.features', '(n,', 'in_channels)', '=', 'features.shape', 'assert', 'in_channels', '%', 'out_channels', '==', '0', 'and', 'in_channels', '>=', 'out_channels', 'x.features', '=', 'features.view(n,', 'out_channels,', '-1).sum(dim=2)', 'return', 'x']
917,085
marlbenchmark/off-policy
base_runner.py
RecRunner.save
save
Save all policies to the path specified by the config.
[ "Save", "all", "policies", "to", "the", "path", "specified", "by", "the", "config." ]
def save(self): for pid in self.policy_ids: policy_critic = self.policies[pid].critic critic_save_path = self.save_dir + '/' + str(pid) if not os.path.exists(critic_save_path): os.makedirs(critic_save_path) torch.save(policy_critic.state_dict(), critic_save_path + '/criti...
['def', 'save(self):', 'for', 'pid', 'in', 'self.policy_ids:', 'policy_critic', '=', 'self.policies[pid].critic', 'critic_save_path', '=', 'self.save_dir', '+', "'/'", '+', 'str(pid)', 'if', 'not', 'os.path.exists(critic_save_path):', 'os.makedirs(critic_save_path)', 'torch.save(policy_critic.state_dict(),', 'critic_sa...
755,520
Visual-Attention-Network/SegNeXt
dataset_wrappers.py
ConcatDataset.pre_eval
pre_eval
do pre eval for every sample of ConcatDataset.
[ "do", "pre", "eval", "for", "every", "sample", "of", "ConcatDataset." ]
def pre_eval(self, preds, indices): if not isinstance(indices, list): indices = [indices] if not isinstance(preds, list): preds = [preds] ret_res = [] for (i, indice) in enumerate(indices): (dataset_idx, sample_idx) = self.get_dataset_idx_and_sample_idx(indice) res = self...
['def', 'pre_eval(self,', 'preds,', 'indices):', 'if', 'not', 'isinstance(indices,', 'list):', 'indices', '=', '[indices]', 'if', 'not', 'isinstance(preds,', 'list):', 'preds', '=', '[preds]', 'ret_res', '=', '[]', 'for', '(i,', 'indice)', 'in', 'enumerate(indices):', '(dataset_idx,', 'sample_idx)', '=', 'self.get_data...
842,992
Ruturaj123/Flowchart-Detection
timeline.py
Timeline.generate_chrome_trace_format
generate_chrome_trace_format
Produces a trace in Chrome Trace Format.
[ "Produces", "a", "trace", "in", "Chrome", "Trace", "Format." ]
def generate_chrome_trace_format(self, show_dataflow=True, show_memory=False): step_stats_analysis = self.analyze_step_stats(show_dataflow=show_dataflow, show_memory=show_memory) return step_stats_analysis.chrome_trace.format_to_string(pretty=True)
['def', 'generate_chrome_trace_format(self,', 'show_dataflow=True,', 'show_memory=False):', 'step_stats_analysis', '=', 'self.analyze_step_stats(show_dataflow=show_dataflow,', 'show_memory=show_memory)', 'return', 'step_stats_analysis.chrome_trace.format_to_string(pretty=True)']
604,980
iffiX/machin
helper_classes.py
Counter.get
get
Get the internal number of counter.
[ "Get", "the", "internal", "number", "of", "counter." ]
def get(self): return self._count
['def', 'get(self):', 'return', 'self._count']
620,451
Xianpeng919/MonoCon
anchor_free_bbox_coder.py
AnchorFreeBBoxCoder.split_pred
split_pred
Split predicted features to specific parts.
[ "Split", "predicted", "features", "to", "specific", "parts." ]
def split_pred(self, cls_preds, reg_preds, base_xyz): results = {} results['obj_scores'] = cls_preds (start, end) = (0, 0) reg_preds_trans = reg_preds.transpose(2, 1) end += 3 results['center_offset'] = reg_preds_trans[..., start:end] results['center'] = base_xyz.detach() + reg_preds_trans[....
['def', 'split_pred(self,', 'cls_preds,', 'reg_preds,', 'base_xyz):', 'results', '=', '{}', "results['obj_scores']", '=', 'cls_preds', '(start,', 'end)', '=', '(0,', '0)', 'reg_preds_trans', '=', 'reg_preds.transpose(2,', '1)', 'end', '+=', '3', "results['center_offset']", '=', 'reg_preds_trans[...,', 'start:end]', "re...
654,256
nlp-uoregon/trankit
conll.py
CoNLL.dict2conllstring
dict2conllstring
Convert the dictionary format input data to the CoNLL-U format output data and write to a file.
[ "Convert", "the", "dictionary", "format", "input", "data", "to", "the", "CoNLL-U", "format", "output", "data", "and", "write", "to", "a", "file." ]
def dict2conllstring(doc_dict): doc_conll = CoNLL.convert_dict(doc_dict) conll_string = CoNLL.conll_as_string(doc_conll) return conll_string
['def', 'dict2conllstring(doc_dict):', 'doc_conll', '=', 'CoNLL.convert_dict(doc_dict)', 'conll_string', '=', 'CoNLL.conll_as_string(doc_conll)', 'return', 'conll_string']
920,469
jogisuda/QuantumSentenceTransformer
QuantumSentenceTransformer.py
RY_layer
RY_layer
Layer of parametrized qubit rotations around the y axis.
[ "Layer", "of", "parametrized", "qubit", "rotations", "around", "the", "y", "axis." ]
def RY_layer(w): for (idx, element) in enumerate(w): qml.RY(element, wires=idx)
['def', 'RY_layer(w):', 'for', '(idx,', 'element)', 'in', 'enumerate(w):', 'qml.RY(element,', 'wires=idx)']
835,527
liuzuxin/safe-mbrl
mpi_tf.py
MpiAdamOptimizer.compute_gradients
compute_gradients
Same as normal compute_gradients, except average grads over processes.
[ "Same", "as", "normal", "compute_gradients,", "except", "average", "grads", "over", "processes." ]
def compute_gradients(self, loss, var_list, **kwargs): grads_and_vars = super().compute_gradients(loss, var_list, **kwargs) grads_and_vars = [(g, v) for (g, v) in grads_and_vars if g is not None] flat_grad = flat_concat([g for (g, v) in grads_and_vars]) shapes = [v.shape.as_list() for (g, v) in grads_an...
['def', 'compute_gradients(self,', 'loss,', 'var_list,', '**kwargs):', 'grads_and_vars', '=', 'super().compute_gradients(loss,', 'var_list,', '**kwargs)', 'grads_and_vars', '=', '[(g,', 'v)', 'for', '(g,', 'v)', 'in', 'grads_and_vars', 'if', 'g', 'is', 'not', 'None]', 'flat_grad', '=', 'flat_concat([g', 'for', '(g,', '...
828,861
IBM/mi-prometheus
task_generator.py
Task.topological_sort
topological_sort
Perform a topological sort.
[ "Perform", "a", "topological", "sort." ]
def topological_sort(self): nodes = self._all_nodes visited = defaultdict(lambda : False) stack = [] for node in nodes: if not visited[node]: self.topological_sort_visit(node, visited, stack) return stack
['def', 'topological_sort(self):', 'nodes', '=', 'self._all_nodes', 'visited', '=', 'defaultdict(lambda', ':', 'False)', 'stack', '=', '[]', 'for', 'node', 'in', 'nodes:', 'if', 'not', 'visited[node]:', 'self.topological_sort_visit(node,', 'visited,', 'stack)', 'return', 'stack']
635,750
Farama-Foundation/Gymnasium
vector_env.py
VectorWrapper.observation_space
observation_space
Gets the observation space of the vector environment.
[ "Gets", "the", "observation", "space", "of", "the", "vector", "environment." ]
def observation_space(self) -> gym.Space: if self._observation_space is None: return self.env.observation_space return self._observation_space
['def', 'observation_space(self)', '->', 'gym.Space:', 'if', 'self._observation_space', 'is', 'None:', 'return', 'self.env.observation_space', 'return', 'self._observation_space']
573,121
calico/basenji
basenji_sat_h5.py
parse_input
parse_input
Parse an input file that might be FASTA or HDF5.
[ "Parse", "an", "input", "file", "that", "might", "be", "FASTA", "or", "HDF5." ]
def parse_input(input_file, sample): try: seqs = [] seq_headers = [] for line in open(input_file): if line[0] == '>': seq_headers.append(line[1:].rstrip()) seqs.append('') else: seqs[-1] += line.rstrip() seqs = n...
['def', 'parse_input(input_file,', 'sample):', 'try:', 'seqs', '=', '[]', 'seq_headers', '=', '[]', 'for', 'line', 'in', 'open(input_file):', 'if', 'line[0]', '==', "'>':", 'seq_headers.append(line[1:].rstrip())', "seqs.append('')", 'else:', 'seqs[-1]', '+=', 'line.rstrip()', 'seqs', '=', 'np.array(seqs)', 'seq_headers...
94,878
deepmind/dm_control
containers.py
TaggedTasks.add
add
Decorator that adds a factory function to the container with tags.
[ "Decorator", "that", "adds", "a", "factory", "function", "to", "the", "container", "with", "tags." ]
def add(self, *tags): def wrap(factory_func): name = factory_func.__name__ if name in self and (not self.allow_overriding_keys): raise ValueError(_NAME_ALREADY_EXISTS.format(name=name)) self._tasks[name] = factory_func for tag in tags: self._tags[tag][name] =...
['def', 'add(self,', '*tags):', 'def', 'wrap(factory_func):', 'name', '=', 'factory_func.__name__', 'if', 'name', 'in', 'self', 'and', '(not', 'self.allow_overriding_keys):', 'raise', 'ValueError(_NAME_ALREADY_EXISTS.format(name=name))', 'self._tasks[name]', '=', 'factory_func', 'for', 'tag', 'in', 'tags:', 'self._tags...
166,507
agrija9/Deep-Unsupervised-Domain-Adaptation
main.py
step_decay
step_decay
Schedule step decay of learning rate with epochs.
[ "Schedule", "step", "decay", "of", "learning", "rate", "with", "epochs." ]
def step_decay(epoch, learning_rate): initial_learning_rate = learning_rate drop = 0.8 epochs_drop = 10.0 learning_rate = initial_learning_rate * math.pow(drop, math.floor((1 + epoch) / epochs_drop)) return learning_rate
['def', 'step_decay(epoch,', 'learning_rate):', 'initial_learning_rate', '=', 'learning_rate', 'drop', '=', '0.8', 'epochs_drop', '=', '10.0', 'learning_rate', '=', 'initial_learning_rate', '*', 'math.pow(drop,', 'math.floor((1', '+', 'epoch)', '/', 'epochs_drop))', 'return', 'learning_rate']
519,911
Kvatsx/Artificial-Intelligence-Assignments
test_algorithmic.py
imprint
imprint
Monkey-patch the given environment so that when reset() is called, the input tape/grid will be set to the given data, rather than being randomly generated.
[ "Monkey-patch", "the", "given", "environment", "so", "that", "when", "reset()", "is", "called,", "the", "input", "tape/grid", "will", "be", "set", "to", "the", "given", "data,", "rather", "than", "being", "randomly", "generated." ]
def imprint(env, input_arr): env.generate_input_data = lambda _: input_arr
['def', 'imprint(env,', 'input_arr):', 'env.generate_input_data', '=', 'lambda', '_:', 'input_arr']
37,334
sunishsheth2009/ChatterBot
align.py
IBMModel1.aligned
aligned
Return a list of AlignedSents with Alignments calculated using IBM-Model 1.
[ "Return", "a", "list", "of", "AlignedSents", "with", "Alignments", "calculated", "using", "IBM-Model", "1." ]
def aligned(self): if self.probabilities is None: raise ValueError('No probabilities calculated') aligned = [] for aligned_sent in self.aligned_sents: alignment = [] for (j, e_w) in enumerate(aligned_sent.words): f_max = (self.probabilities[e_w, None], None) f...
['def', 'aligned(self):', 'if', 'self.probabilities', 'is', 'None:', 'raise', "ValueError('No", 'probabilities', "calculated')", 'aligned', '=', '[]', 'for', 'aligned_sent', 'in', 'self.aligned_sents:', 'alignment', '=', '[]', 'for', '(j,', 'e_w)', 'in', 'enumerate(aligned_sent.words):', 'f_max', '=', '(self.probabilit...
527,311
aisingapore/PeekingDuck
bbox.py
draw_pts
draw_pts
Draw pts of selected object onto frame.
[ "Draw", "pts", "of", "selected", "object", "onto", "frame." ]
def draw_pts(frame: np.ndarray, pts: List[Tuple[float]]) -> None: for point in pts: cv2.circle(frame, point, POINT_RADIUS, CHAMPAGNE, -1)
['def', 'draw_pts(frame:', 'np.ndarray,', 'pts:', 'List[Tuple[float]])', '->', 'None:', 'for', 'point', 'in', 'pts:', 'cv2.circle(frame,', 'point,', 'POINT_RADIUS,', 'CHAMPAGNE,', '-1)']
766,858
VoraHarsh/iit-cs480-Introduction-to--
search.py
Node.solution
solution
Return the sequence of actions to go from the root to this node.
[ "Return", "the", "sequence", "of", "actions", "to", "go", "from", "the", "root", "to", "this", "node." ]
def solution(self): return [node.action for node in self.path()[1:]]
['def', 'solution(self):', 'return', '[node.action', 'for', 'node', 'in', 'self.path()[1:]]']
229,079
gugarosa/nalp
relational_memory_cell.py
RelationalMemoryCell.get_initial_state
get_initial_state
Gets the cell initial state by creating an identity matrix.
[ "Gets", "the", "cell", "initial", "state", "by", "creating", "an", "identity", "matrix." ]
def get_initial_state(self, inputs: Optional[tf.Tensor]=None, batch_size: Optional[int]=None, dtype: Optional[tf.DType]=None) -> Tuple[tf.Tensor, tf.Tensor]: states = tf.eye(self.n_slots, batch_shape=[batch_size]) if self.slot_size > self.n_slots: diff = self.slot_size - self.n_slots padding = t...
['def', 'get_initial_state(self,', 'inputs:', 'Optional[tf.Tensor]=None,', 'batch_size:', 'Optional[int]=None,', 'dtype:', 'Optional[tf.DType]=None)', '->', 'Tuple[tf.Tensor,', 'tf.Tensor]:', 'states', '=', 'tf.eye(self.n_slots,', 'batch_shape=[batch_size])', 'if', 'self.slot_size', '>', 'self.n_slots:', 'diff', '=', '...
651,783
HuiGuanLab/HiCo
lr_policy.py
get_lr_func
get_lr_func
Given the configs, retrieve the specified lr policy function.
[ "Given", "the", "configs,", "retrieve", "the", "specified", "lr", "policy", "function." ]
def get_lr_func(lr_policy): policy = 'lr_func_' + lr_policy if policy not in globals(): raise NotImplementedError('Unknown LR policy: {}'.format(lr_policy)) else: return globals()[policy]
['def', 'get_lr_func(lr_policy):', 'policy', '=', "'lr_func_'", '+', 'lr_policy', 'if', 'policy', 'not', 'in', 'globals():', 'raise', "NotImplementedError('Unknown", 'LR', 'policy:', "{}'.format(lr_policy))", 'else:', 'return', 'globals()[policy]']
206,105
voxel51/fiftyone
cli.py
Command.execute
execute
Executes the command on the given args.
[ "Executes", "the", "command", "on", "the", "given", "args." ]
def execute(parser, args): raise NotImplementedError('subclass must implement execute()')
['def', 'execute(parser,', 'args):', 'raise', "NotImplementedError('subclass", 'must', 'implement', "execute()')"]
582,706
eddylau328/fyp-artificial-intelligence-ac-control-device
_messaging_encoder.py
MessageEncoder.encode_android
encode_android
Encodes an ``AndroidConfig`` instance into JSON.
[ "Encodes", "an", "``AndroidConfig``", "instance", "into", "JSON." ]
def encode_android(cls, android): if android is None: return None if not isinstance(android, _messaging_utils.AndroidConfig): raise ValueError('Message.android must be an instance of AndroidConfig class.') result = {'collapse_key': _Validators.check_string('AndroidConfig.collapse_key', andro...
['def', 'encode_android(cls,', 'android):', 'if', 'android', 'is', 'None:', 'return', 'None', 'if', 'not', 'isinstance(android,', '_messaging_utils.AndroidConfig):', 'raise', "ValueError('Message.android", 'must', 'be', 'an', 'instance', 'of', 'AndroidConfig', "class.')", 'result', '=', "{'collapse_key':", "_Validators...
214,344
intel/neural-compressor
test_runner.py
TestMain.test_main
test_main
Test blocking flag in abort_job method.
[ "Test", "blocking", "flag", "in", "abort_job", "method." ]
def test_main(self): path = 'test.txt' with open(path, 'w') as f: f.write('hostname1 2 20\nhostname2 2 20') adding_abort = threading.Thread(target=main, kwargs={'args': ['-H', 'test.txt', '-TMP', '2222', '-RMP', '3333', '-CEN', 'inc_conda_env']}, daemon=True) adding_abort.start() adding_abor...
['def', 'test_main(self):', 'path', '=', "'test.txt'", 'with', 'open(path,', "'w')", 'as', 'f:', "f.write('hostname1", '2', '20\\nhostname2', '2', "20')", 'adding_abort', '=', 'threading.Thread(target=main,', "kwargs={'args':", "['-H',", "'test.txt',", "'-TMP',", "'2222',", "'-RMP',", "'3333',", "'-CEN',", "'inc_conda_...
721,851
intel/neural-compressor
callbacks.py
BaseCallbacks.on_step_begin
on_step_begin
Be called on the beginning of batches.
[ "Be", "called", "on", "the", "beginning", "of", "batches." ]
def on_step_begin(self, batch_id): if len(self.hooks_dict['on_step_begin']) > 0: res_list = [] for on_step_begin_hook in self.hooks_dict['on_step_begin']: res_list.append(on_step_begin_hook(batch_id)) return res_list else: return None
['def', 'on_step_begin(self,', 'batch_id):', 'if', "len(self.hooks_dict['on_step_begin'])", '>', '0:', 'res_list', '=', '[]', 'for', 'on_step_begin_hook', 'in', "self.hooks_dict['on_step_begin']:", 'res_list.append(on_step_begin_hook(batch_id))', 'return', 'res_list', 'else:', 'return', 'None']
737,965
alugupta/ares
wideresnet.py
create_wres28_10
create_wres28_10
The function to create wide-resnet28-10 for cifar10 models.
[ "The", "function", "to", "create", "wide-resnet28-10", "for", "cifar10", "models." ]
def create_wres28_10(): model = WideResNet(depth=28, num_classes=10, widen_factor=10, dropRate=0.0) return model
['def', 'create_wres28_10():', 'model', '=', 'WideResNet(depth=28,', 'num_classes=10,', 'widen_factor=10,', 'dropRate=0.0)', 'return', 'model']
402,170
unixpickle/anyrl-py
util.py
reduce_states
reduce_states
Reduce a batch of states to a batch of one state.
[ "Reduce", "a", "batch", "of", "states", "to", "a", "batch", "of", "one", "state." ]
def reduce_states(state_batch, env_idx): if state_batch is None: return None elif isinstance(state_batch, tuple): return tuple((reduce_states(s, env_idx) for s in state_batch)) return state_batch[env_idx:env_idx + 1].copy()
['def', 'reduce_states(state_batch,', 'env_idx):', 'if', 'state_batch', 'is', 'None:', 'return', 'None', 'elif', 'isinstance(state_batch,', 'tuple):', 'return', 'tuple((reduce_states(s,', 'env_idx)', 'for', 's', 'in', 'state_batch))', 'return', 'state_batch[env_idx:env_idx', '+', '1].copy()']
33,880
google-research/scenic
base_model.py
MaskedFeatureRegressionModel.loss_function
loss_function
Returns the (weighted) mean squared error.
[ "Returns", "the", "(weighted)", "mean", "squared", "error." ]
def loss_function(self, predictions: jnp.ndarray, prediction_masks: jnp.ndarray, batch: base_model.Batch, model_params: Optional[jnp.ndarray]=None) -> float: batch_mask = batch.get('batch_mask') if batch_mask is None: batch_mask = jnp.ones(prediction_masks.shape) if batch_mask.ndim == 1: bat...
['def', 'loss_function(self,', 'predictions:', 'jnp.ndarray,', 'prediction_masks:', 'jnp.ndarray,', 'batch:', 'base_model.Batch,', 'model_params:', 'Optional[jnp.ndarray]=None)', '->', 'float:', 'batch_mask', '=', "batch.get('batch_mask')", 'if', 'batch_mask', 'is', 'None:', 'batch_mask', '=', 'jnp.ones(prediction_mask...
846,396
clips/pattern
__init__.py
tokenize
tokenize
Returns a list of sentences, where punctuation marks have been split from words.
[ "Returns", "a", "list", "of", "sentences,", "where", "punctuation", "marks", "have", "been", "split", "from", "words." ]
def tokenize(s, *args, **kwargs): return parser.find_tokens(s, *args, **kwargs)
['def', 'tokenize(s,', '*args,', '**kwargs):', 'return', 'parser.find_tokens(s,', '*args,', '**kwargs)']
764,984
facebookresearch/CompilerGym
compiler_env.py
CompilerEnv.action_spaces
action_spaces
A list of supported action space names.
[ "A", "list", "of", "supported", "action", "space", "names." ]
def action_spaces(self) -> List[ActionSpace]: raise NotImplementedError('abstract method')
['def', 'action_spaces(self)', '->', 'List[ActionSpace]:', 'raise', "NotImplementedError('abstract", "method')"]
126,144
fudan-zvg/GSS
dataset_wrappers.py
ConcatDataset.get_dataset_idx_and_sample_idx
get_dataset_idx_and_sample_idx
Return dataset and sample index when given an indice of ConcatDataset.
[ "Return", "dataset", "and", "sample", "index", "when", "given", "an", "indice", "of", "ConcatDataset." ]
def get_dataset_idx_and_sample_idx(self, indice): if indice < 0: if -indice > len(self): raise ValueError('absolute value of index should not exceed dataset length') indice = len(self) + indice dataset_idx = bisect.bisect_right(self.cumulative_sizes, indice) if dataset_idx == 0: ...
['def', 'get_dataset_idx_and_sample_idx(self,', 'indice):', 'if', 'indice', '<', '0:', 'if', '-indice', '>', 'len(self):', 'raise', "ValueError('absolute", 'value', 'of', 'index', 'should', 'not', 'exceed', 'dataset', "length')", 'indice', '=', 'len(self)', '+', 'indice', 'dataset_idx', '=', 'bisect.bisect_right(self.c...
572,034
RasaHQ/rasa
mitie_featurizer.py
MitieFeaturizer.process_training_data
process_training_data
Processes the training examples in the given training data in-place.
[ "Processes", "the", "training", "examples", "in", "the", "given", "training", "data", "in-place." ]
def process_training_data(self, training_data: TrainingData, model: MitieModel) -> TrainingData: self.process(training_data.training_examples, model) return training_data
['def', 'process_training_data(self,', 'training_data:', 'TrainingData,', 'model:', 'MitieModel)', '->', 'TrainingData:', 'self.process(training_data.training_examples,', 'model)', 'return', 'training_data']
837,262
aws/sagemaker-python-sdk
common.py
RecordDeserializer.deserialize
deserialize
Deserialize RecordIO Protobuf data from an inference endpoint.
[ "Deserialize", "RecordIO", "Protobuf", "data", "from", "an", "inference", "endpoint." ]
def deserialize(self, data, content_type): try: return read_records(data) finally: data.close()
['def', 'deserialize(self,', 'data,', 'content_type):', 'try:', 'return', 'read_records(data)', 'finally:', 'data.close()']
829,765
Ruturaj123/Flowchart-Detection
input_data.py
AudioProcessor.get_unprocessed_data
get_unprocessed_data
Retrieve sample data for the given partition, with no transformations.
[ "Retrieve", "sample", "data", "for", "the", "given", "partition,", "with", "no", "transformations." ]
def get_unprocessed_data(self, how_many, model_settings, mode): candidates = self.data_index[mode] if how_many == -1: sample_count = len(candidates) else: sample_count = how_many desired_samples = model_settings['desired_samples'] words_list = self.words_list data = np.zeros((sam...
['def', 'get_unprocessed_data(self,', 'how_many,', 'model_settings,', 'mode):', 'candidates', '=', 'self.data_index[mode]', 'if', 'how_many', '==', '-1:', 'sample_count', '=', 'len(candidates)', 'else:', 'sample_count', '=', 'how_many', 'desired_samples', '=', "model_settings['desired_samples']", 'words_list', '=', 'se...
604,901
avadhari/Unsupervised-Learning
utils.py
plot_loss
plot_loss
Function to plot loss curve.
[ "Function", "to", "plot", "loss", "curve." ]
def plot_loss(loss_list): plt.figure() markers = ['.', 'o'] colors = ['r', 'b'] x = np.arange(config.NUM_EPOCHS) plt.plot(np.asarray(x), np.asarray(loss_list), label='loss', color=colors[0], marker=markers[0]) plt.ylabel('Loss') plt.xlabel('Epoch') plt.title('Loss Curve') plt.legend(...
['def', 'plot_loss(loss_list):', 'plt.figure()', 'markers', '=', "['.',", "'o']", 'colors', '=', "['r',", "'b']", 'x', '=', 'np.arange(config.NUM_EPOCHS)', 'plt.plot(np.asarray(x),', 'np.asarray(loss_list),', "label='loss',", 'color=colors[0],', 'marker=markers[0])', "plt.ylabel('Loss')", "plt.xlabel('Epoch')", "plt.ti...
353,382
devashish-patel/webcam-motion-detector
pathlib2.py
Path.exists
exists
Whether this path exists.
[ "Whether", "this", "path", "exists." ]
def exists(self): try: self.stat() except OSError as e: if e.errno not in (ENOENT, ENOTDIR): raise return False return True
['def', 'exists(self):', 'try:', 'self.stat()', 'except', 'OSError', 'as', 'e:', 'if', 'e.errno', 'not', 'in', '(ENOENT,', 'ENOTDIR):', 'raise', 'return', 'False', 'return', 'True']
976,721
Gradiant/pyodi
ground_truth.py
ground_truth
ground_truth
Explore the images and bounding boxes of a dataset.
[ "Explore", "the", "images", "and", "bounding", "boxes", "of", "a", "dataset." ]
def ground_truth(ground_truth_file: str, show: bool=True, output: Optional[str]=None, output_size: Tuple[int, int]=(1600, 900)) -> None: if output is not None: output = str(Path(output) / Path(ground_truth_file).stem) Path(output).mkdir(parents=True, exist_ok=True) df_annotations = coco_ground_t...
['def', 'ground_truth(ground_truth_file:', 'str,', 'show:', 'bool=True,', 'output:', 'Optional[str]=None,', 'output_size:', 'Tuple[int,', 'int]=(1600,', '900))', '->', 'None:', 'if', 'output', 'is', 'not', 'None:', 'output', '=', 'str(Path(output)', '/', 'Path(ground_truth_file).stem)', 'Path(output).mkdir(parents=True...
820,831
tudelft3d/SUMS-Semantic-Urban-Mesh--public
main.py
resume
resume
Loads model and optimizer state from a previous checkpoint.
[ "Loads", "model", "and", "optimizer", "state", "from", "a", "previous", "checkpoint." ]
def resume(args, dbinfo): print("=> loading checkpoint '{}'".format(args.resume)) checkpoint = torch.load(args.resume) checkpoint['args'].model_config = args.model_config model = create_model(checkpoint['args'], dbinfo) optimizer = create_optimizer(args, model) model.load_state_dict({k: checkpoi...
['def', 'resume(args,', 'dbinfo):', 'print("=>', 'loading', 'checkpoint', '\'{}\'".format(args.resume))', 'checkpoint', '=', 'torch.load(args.resume)', "checkpoint['args'].model_config", '=', 'args.model_config', 'model', '=', "create_model(checkpoint['args'],", 'dbinfo)', 'optimizer', '=', 'create_optimizer(args,', 'm...
911,647
jimtin/Stock_Comparison
ols.py
OLS.std_err
std_err
Returns the standard err values of the betas.
[ "Returns", "the", "standard", "err", "values", "of", "the", "betas." ]
def std_err(self): return Series(self._std_err_raw, index=self.beta.index)
['def', 'std_err(self):', 'return', 'Series(self._std_err_raw,', 'index=self.beta.index)']
388,100
declare-lab/speech-adapters
modeling_wav2vec2.py
Wav2Vec2ForCTC.freeze_feature_encoder
freeze_feature_encoder
Calling this function will disable the gradient computation for the feature encoder so that its parameter will not be updated during training.
[ "Calling", "this", "function", "will", "disable", "the", "gradient", "computation", "for", "the", "feature", "encoder", "so", "that", "its", "parameter", "will", "not", "be", "updated", "during", "training." ]
def freeze_feature_encoder(self): self.wav2vec2.feature_extractor._freeze_parameters()
['def', 'freeze_feature_encoder(self):', 'self.wav2vec2.feature_extractor._freeze_parameters()']
894,846
aeon-toolkit/aeon
test_base.py
test_predict_single_class
test_predict_single_class
Test return of predict predict_proba in case only single class seen in fit.
[ "Test", "return", "of", "predict", "predict_proba", "in", "case", "only", "single", "class", "seen", "in", "fit." ]
def test_predict_single_class(): trainX = np.ones(shape=(10, 20)) y = np.ones(10) testX = np.ones(shape=(10, 20)) clf = DummyClassifier() clf.fit(trainX, y) y_pred = clf.predict(testX) y_pred_proba = clf.predict_proba(testX) assert y_pred.ndim == 1 assert y_pred.shape == (10,) as...
['def', 'test_predict_single_class():', 'trainX', '=', 'np.ones(shape=(10,', '20))', 'y', '=', 'np.ones(10)', 'testX', '=', 'np.ones(shape=(10,', '20))', 'clf', '=', 'DummyClassifier()', 'clf.fit(trainX,', 'y)', 'y_pred', '=', 'clf.predict(testX)', 'y_pred_proba', '=', 'clf.predict_proba(testX)', 'assert', 'y_pred.ndim...
399,312
huawei-noah/xingtian
utils.py
FakeLoss.construct
construct
Forward of fake loss.
[ "Forward", "of", "fake", "loss." ]
def construct(self, output, label): return 0
['def', 'construct(self,', 'output,', 'label):', 'return', '0']
962,612
AastaNV/ObjectDetection
box_utils.py
diounms
diounms
Apply DIoU-NMS at test time to avoid detecting too many overlapping bounding boxes for a given object.
[ "Apply", "DIoU-NMS", "at", "test", "time", "to", "avoid", "detecting", "too", "many", "overlapping", "bounding", "boxes", "for", "a", "given", "object." ]
def diounms(boxes, scores, overlap=0.5, top_k=200, beta1=1.0): keep = scores.new(scores.size(0)).zero_().long() if boxes.numel() == 0: return keep x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3] area = torch.mul(x2 - x1, y2 - y1) (v, idx) = scores.sort(0) ...
['def', 'diounms(boxes,', 'scores,', 'overlap=0.5,', 'top_k=200,', 'beta1=1.0):', 'keep', '=', 'scores.new(scores.size(0)).zero_().long()', 'if', 'boxes.numel()', '==', '0:', 'return', 'keep', 'x1', '=', 'boxes[:,', '0]', 'y1', '=', 'boxes[:,', '1]', 'x2', '=', 'boxes[:,', '2]', 'y2', '=', 'boxes[:,', '3]', 'area', '='...
754,729
ryu-ed/SpaceInvaders_Ros
math2html.py
LangLine.process
process
Only generate a span with lang info when the language is recognized.
[ "Only", "generate", "a", "span", "with", "lang", "info", "when", "the", "language", "is", "recognized." ]
def process(self): lang = self.header[1] if not lang in TranslationConfig.languages: self.output = ContentsOutput() return isolang = TranslationConfig.languages[lang] self.output = TaggedOutput().settag('span lang="' + isolang + '"', False)
['def', 'process(self):', 'lang', '=', 'self.header[1]', 'if', 'not', 'lang', 'in', 'TranslationConfig.languages:', 'self.output', '=', 'ContentsOutput()', 'return', 'isolang', '=', 'TranslationConfig.languages[lang]', 'self.output', '=', "TaggedOutput().settag('span", 'lang="\'', '+', 'isolang', '+', '\'"\',', 'False)...
395,264
enlite-ai/maze
dict_action_conversion.py
ActionConversion.space
space
Returns Gym dict action space.
[ "Returns", "Gym", "dict", "action", "space." ]
def space(self) -> spaces.Dict: return spaces.Dict({'piece_idx': spaces.Discrete(self.max_pieces_in_inventory), 'cut_rotation': spaces.Discrete(2), 'cut_order': spaces.Discrete(2)})
['def', 'space(self)', '->', 'spaces.Dict:', 'return', "spaces.Dict({'piece_idx':", 'spaces.Discrete(self.max_pieces_in_inventory),', "'cut_rotation':", 'spaces.Discrete(2),', "'cut_order':", 'spaces.Discrete(2)})']
647,685
caiiiac/Machine-Learning-with-Python
grid_helper_curvelinear.py
curvelinear_test2
curvelinear_test2
polar projection, but in a rectangular box.
[ "polar", "projection,", "but", "in", "a", "rectangular", "box." ]
def curvelinear_test2(fig): global ax1 import numpy as np from . import angle_helper from matplotlib.projections import PolarAxes from matplotlib.transforms import Affine2D from mpl_toolkits.axes_grid.parasite_axes import SubplotHost, ParasiteAxesAuxTrans import matplotlib.cbook as cbook ...
['def', 'curvelinear_test2(fig):', 'global', 'ax1', 'import', 'numpy', 'as', 'np', 'from', '.', 'import', 'angle_helper', 'from', 'matplotlib.projections', 'import', 'PolarAxes', 'from', 'matplotlib.transforms', 'import', 'Affine2D', 'from', 'mpl_toolkits.axes_grid.parasite_axes', 'import', 'SubplotHost,', 'ParasiteAxe...
716,813
rlgraph/rlgraph
define_by_run_ops.py
execute_define_by_run_graph_fn
execute_define_by_run_graph_fn
Executes a graph_fn in define by run mode.
[ "Executes", "a", "graph_fn", "in", "define", "by", "run", "mode." ]
def execute_define_by_run_graph_fn(component, graph_fn, options, *args, **kwargs): flatten_ops = options.pop('flatten_ops', False) split_ops = options.pop('split_ops', False) add_auto_key_as_first_param = options.pop('add_auto_key_as_first_param', False) if not flatten_ops: return graph_fn(compo...
['def', 'execute_define_by_run_graph_fn(component,', 'graph_fn,', 'options,', '*args,', '**kwargs):', 'flatten_ops', '=', "options.pop('flatten_ops',", 'False)', 'split_ops', '=', "options.pop('split_ops',", 'False)', 'add_auto_key_as_first_param', '=', "options.pop('add_auto_key_as_first_param',", 'False)', 'if', 'not...
862,833
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
operator.py
truth
truth
Return True if a is true, False otherwise.
[ "Return", "True", "if", "a", "is", "true,", "False", "otherwise." ]
def truth(a): return True if a else False
['def', 'truth(a):', 'return', 'True', 'if', 'a', 'else', 'False']
428,978
neurospin/pylearn-parsimony
estimators.py
LinearRegressionL2SmoothedL1TV.score
score
Return the mean squared error of the estimator.
[ "Return", "the", "mean", "squared", "error", "of", "the", "estimator." ]
def score(self, X, y): (n, p) = X.shape y_hat = np.dot(X, self.beta) return np.sum((y_hat - y) ** 2) / float(n)
['def', 'score(self,', 'X,', 'y):', '(n,', 'p)', '=', 'X.shape', 'y_hat', '=', 'np.dot(X,', 'self.beta)', 'return', 'np.sum((y_hat', '-', 'y)', '**', '2)', '/', 'float(n)']
819,906
gunthercox/ChatterBot
test_benchmarks.py
SqlBenchmarkingTests.test_get_response_after_ubuntu_corpus_training
test_get_response_after_ubuntu_corpus_training
Test response time after training with the Ubuntu corpus.
[ "Test", "response", "time", "after", "training", "with", "the", "Ubuntu", "corpus." ]
def test_get_response_after_ubuntu_corpus_training(self): trainer = get_ubuntu_corpus_trainer(self.chatbot) trainer.train() self.assert_response_duration_is_less_than(6)
['def', 'test_get_response_after_ubuntu_corpus_training(self):', 'trainer', '=', 'get_ubuntu_corpus_trainer(self.chatbot)', 'trainer.train()', 'self.assert_response_duration_is_less_than(6)']
485,832
enuguru/artificial_intelligence_and_machine_learning
migrate_repository.py
delete_file
delete_file
Deletes a file and prints a message.
[ "Deletes", "a", "file", "and", "prints", "a", "message." ]
def delete_file(filepath): log.info('Deleting file: %s' % filepath) os.remove(filepath)
['def', 'delete_file(filepath):', "log.info('Deleting", 'file:', "%s'", '%', 'filepath)', 'os.remove(filepath)']
158,969
tobegit3hub/deep_image_model
tfexample_decoder_test.py
TFExampleDecoderTest.DecodeExample
DecodeExample
Decodes the given serialized example with the specified item handler.
[ "Decodes", "the", "given", "serialized", "example", "with", "the", "specified", "item", "handler." ]
def DecodeExample(self, serialized_example, item_handler, image_format): serialized_example = tf.reshape(serialized_example, shape=[]) decoder = slim.tfexample_decoder.TFExampleDecoder(keys_to_features={'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''), 'image/format': tf.FixedLenFeature((), ...
['def', 'DecodeExample(self,', 'serialized_example,', 'item_handler,', 'image_format):', 'serialized_example', '=', 'tf.reshape(serialized_example,', 'shape=[])', 'decoder', '=', "slim.tfexample_decoder.TFExampleDecoder(keys_to_features={'image/encoded':", 'tf.FixedLenFeature((),', 'tf.string,', "default_value=''),", "...
182,032
bfshi/TOAST
distributed.py
get_local_rank
get_local_rank
Returns: The rank of the current process within the local (per-machine) process group.
[ "Returns:", "The", "rank", "of", "the", "current", "process", "within", "the", "local", "(per-machine)", "process", "group." ]
def get_local_rank(): if not dist.is_available(): return 0 if not dist.is_initialized(): return 0 assert _LOCAL_PROCESS_GROUP is not None return dist.get_rank(group=_LOCAL_PROCESS_GROUP)
['def', 'get_local_rank():', 'if', 'not', 'dist.is_available():', 'return', '0', 'if', 'not', 'dist.is_initialized():', 'return', '0', 'assert', '_LOCAL_PROCESS_GROUP', 'is', 'not', 'None', 'return', 'dist.get_rank(group=_LOCAL_PROCESS_GROUP)']
901,682
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
registry_test.py
RegistryTest.testCannotCreateMissingClass
testCannotCreateMissingClass
Tests that Create fails if the class does not exist in the module.
[ "Tests", "that", "Create", "fails", "if", "the", "class", "does", "not", "exist", "in", "the", "module." ]
def testCannotCreateMissingClass(self): with self.assertRaisesRegexp(ValueError, 'Failed to create'): registry_test_base.Base.Create(PATH + 'registry_test_impl.MissingClass', 'hello world')
['def', 'testCannotCreateMissingClass(self):', 'with', 'self.assertRaisesRegexp(ValueError,', "'Failed", 'to', "create'):", 'registry_test_base.Base.Create(PATH', '+', "'registry_test_impl.MissingClass',", "'hello", "world')"]
111,929
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
utils.py
wet_records
wet_records
Generate WETRecords from filepath.
[ "Generate", "WETRecords", "from", "filepath." ]
def wet_records(wet_filepath): if wet_filepath.endswith('.gz'): fopen = gzip.open else: fopen = tf.gfile.FastGFile with fopen(wet_filepath) as f: for record in wet_records_from_file_obj(f): yield record
['def', 'wet_records(wet_filepath):', 'if', "wet_filepath.endswith('.gz'):", 'fopen', '=', 'gzip.open', 'else:', 'fopen', '=', 'tf.gfile.FastGFile', 'with', 'fopen(wet_filepath)', 'as', 'f:', 'for', 'record', 'in', 'wet_records_from_file_obj(f):', 'yield', 'record']
965,103
dawdleryang/object_detection
rpn.py
add_rpn_blobs
add_rpn_blobs
Add blobs needed training RPN-only and end-to-end Faster R-CNN models.
[ "Add", "blobs", "needed", "training", "RPN-only", "and", "end-to-end", "Faster", "R-CNN", "models." ]
def add_rpn_blobs(blobs, im_scales, roidb): if cfg.FPN.FPN_ON and cfg.FPN.MULTILEVEL_RPN: k_max = cfg.FPN.RPN_MAX_LEVEL k_min = cfg.FPN.RPN_MIN_LEVEL foas = [] for lvl in range(k_min, k_max + 1): field_stride = 2.0 ** lvl anchor_sizes = (cfg.FPN.RPN_ANCHOR_STA...
['def', 'add_rpn_blobs(blobs,', 'im_scales,', 'roidb):', 'if', 'cfg.FPN.FPN_ON', 'and', 'cfg.FPN.MULTILEVEL_RPN:', 'k_max', '=', 'cfg.FPN.RPN_MAX_LEVEL', 'k_min', '=', 'cfg.FPN.RPN_MIN_LEVEL', 'foas', '=', '[]', 'for', 'lvl', 'in', 'range(k_min,', 'k_max', '+', '1):', 'field_stride', '=', '2.0', '**', 'lvl', 'anchor_si...
773,035
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data.py
Pad
Pad
Pad or trim list to len length.
[ "Pad", "or", "trim", "list", "to", "len", "length." ]
def Pad(ids, pad_id, length): assert pad_id is not None assert length is not None if len(ids) < length: a = [pad_id] * (length - len(ids)) return ids + a else: return ids[:length]
['def', 'Pad(ids,', 'pad_id,', 'length):', 'assert', 'pad_id', 'is', 'not', 'None', 'assert', 'length', 'is', 'not', 'None', 'if', 'len(ids)', '<', 'length:', 'a', '=', '[pad_id]', '*', '(length', '-', 'len(ids))', 'return', 'ids', '+', 'a', 'else:', 'return', 'ids[:length]']
29,872
JoyHuYY1412/Class_Imbalanced_Semi_Supervised_Learning
layers.py
kl_divergence_from_logits
kl_divergence_from_logits
Gets KL divergence from logits parameterizing categorical distributions.
[ "Gets", "KL", "divergence", "from", "logits", "parameterizing", "categorical", "distributions." ]
def kl_divergence_from_logits(logits_a, logits_b): distribution1 = tf.contrib.distributions.Categorical(logits=logits_a) distribution2 = tf.contrib.distributions.Categorical(logits=logits_b) return tf.contrib.distributions.kl_divergence(distribution1, distribution2)
['def', 'kl_divergence_from_logits(logits_a,', 'logits_b):', 'distribution1', '=', 'tf.contrib.distributions.Categorical(logits=logits_a)', 'distribution2', '=', 'tf.contrib.distributions.Categorical(logits=logits_b)', 'return', 'tf.contrib.distributions.kl_divergence(distribution1,', 'distribution2)']
122,261
gunthercox/ChatterBot
fst.py
BaseCursor.label
label
Returns the label bytes of the current arc.
[ "Returns", "the", "label", "bytes", "of", "the", "current", "arc." ]
def label(self): raise NotImplementedError
['def', 'label(self):', 'raise', 'NotImplementedError']
526,619
rudranil723/mini-main
symbolic.py
Expr.symbols
symbols
Return a set of symbols contained in self.
[ "Return", "a", "set", "of", "symbols", "contained", "in", "self." ]
def symbols(self): found = set() def visit(expr, found=found): if expr.op is Op.SYMBOL: found.add(expr) self.traverse(visit) return found
['def', 'symbols(self):', 'found', '=', 'set()', 'def', 'visit(expr,', 'found=found):', 'if', 'expr.op', 'is', 'Op.SYMBOL:', 'found.add(expr)', 'self.traverse(visit)', 'return', 'found']
322,697
voxel51/fiftyone
types.py
Object.enum
enum
Defines a property on the object that is an enum.
[ "Defines", "a", "property", "on", "the", "object", "that", "is", "an", "enum." ]
def enum(self, name, values, **kwargs): return self.define_property(name, Enum(values), **kwargs)
['def', 'enum(self,', 'name,', 'values,', '**kwargs):', 'return', 'self.define_property(name,', 'Enum(values),', '**kwargs)']
583,797
cuiziteng/ICCV_MAET
inference.py
inference_detector
inference_detector
Inference image(s) with the detector.
[ "Inference", "image(s)", "with", "the", "detector." ]
def inference_detector(model, img): cfg = model.cfg device = next(model.parameters()).device if isinstance(img, np.ndarray): data = dict(img=img) cfg = cfg.copy() cfg.data.test.pipeline[0].type = 'LoadImageFromWebcam' else: data = dict(img_info=dict(filename=img), img_pre...
['def', 'inference_detector(model,', 'img):', 'cfg', '=', 'model.cfg', 'device', '=', 'next(model.parameters()).device', 'if', 'isinstance(img,', 'np.ndarray):', 'data', '=', 'dict(img=img)', 'cfg', '=', 'cfg.copy()', 'cfg.data.test.pipeline[0].type', '=', "'LoadImageFromWebcam'", 'else:', 'data', '=', 'dict(img_info=d...
228,332
ameet-1997/AttentionGuidance
tokenization_marian.py
MarianTokenizer.save_vocabulary
save_vocabulary
save vocab file to json and copy spm files from their original path.
[ "save", "vocab", "file", "to", "json", "and", "copy", "spm", "files", "from", "their", "original", "path." ]
def save_vocabulary(self, save_directory: str) -> Tuple[str]: save_dir = Path(save_directory) assert save_dir.is_dir(), f'{save_directory} should be a directory' save_json(self.encoder, save_dir / self.vocab_files_names['vocab']) for f in self.spm_files: dest_path = save_dir / Path(f).name ...
['def', 'save_vocabulary(self,', 'save_directory:', 'str)', '->', 'Tuple[str]:', 'save_dir', '=', 'Path(save_directory)', 'assert', 'save_dir.is_dir(),', "f'{save_directory}", 'should', 'be', 'a', "directory'", 'save_json(self.encoder,', 'save_dir', '/', "self.vocab_files_names['vocab'])", 'for', 'f', 'in', 'self.spm_f...
93,120
myothida/Supervised-Machine-Learning
test_kernel_pca.py
test_kernel_pca_n_components
test_kernel_pca_n_components
Test that `n_components` is correctly taken into account for projections For all solvers this tests that the output has the correct shape depending on the selected number of components.
[ "Test", "that", "`n_components`", "is", "correctly", "taken", "into", "account", "for", "projections", "For", "all", "solvers", "this", "tests", "that", "the", "output", "has", "the", "correct", "shape", "depending", "on", "the", "selected", "number", "of", "c...
def test_kernel_pca_n_components(): rng = np.random.RandomState(0) X_fit = rng.random_sample((5, 4)) X_pred = rng.random_sample((2, 4)) for eigen_solver in ('dense', 'arpack', 'randomized'): for c in [1, 2, 4]: kpca = KernelPCA(n_components=c, eigen_solver=eigen_solver) s...
['def', 'test_kernel_pca_n_components():', 'rng', '=', 'np.random.RandomState(0)', 'X_fit', '=', 'rng.random_sample((5,', '4))', 'X_pred', '=', 'rng.random_sample((2,', '4))', 'for', 'eigen_solver', 'in', "('dense',", "'arpack',", "'randomized'):", 'for', 'c', 'in', '[1,', '2,', '4]:', 'kpca', '=', 'KernelPCA(n_compone...
363,673
lambert-x/RVC_Segmentation
ema_head.py
reduce_mean
reduce_mean
Reduce mean when distributed training.
[ "Reduce", "mean", "when", "distributed", "training." ]
def reduce_mean(tensor): if not (dist.is_available() and dist.is_initialized()): return tensor tensor = tensor.clone() dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM) return tensor
['def', 'reduce_mean(tensor):', 'if', 'not', '(dist.is_available()', 'and', 'dist.is_initialized()):', 'return', 'tensor', 'tensor', '=', 'tensor.clone()', 'dist.all_reduce(tensor.div_(dist.get_world_size()),', 'op=dist.ReduceOp.SUM)', 'return', 'tensor']
828,403
openvinotoolkit/training_extensions
data_utils.py
get_extended_label_names
get_extended_label_names
Getter function of extended label names.
[ "Getter", "function", "of", "extended", "label", "names." ]
def get_extended_label_names(labels: List[LabelEntity]): target_labels = [v.name for v in sorted(labels, key=lambda x: x.id)] all_labels = ['background'] + target_labels return all_labels
['def', 'get_extended_label_names(labels:', 'List[LabelEntity]):', 'target_labels', '=', '[v.name', 'for', 'v', 'in', 'sorted(labels,', 'key=lambda', 'x:', 'x.id)]', 'all_labels', '=', "['background']", '+', 'target_labels', 'return', 'all_labels']
918,309
wutong8023/CoLL
tokenization_tapas.py
format_text
format_text
Lowercases and strips punctuation.
[ "Lowercases", "and", "strips", "punctuation." ]
def format_text(text): text = text.lower().strip() if text == 'n/a' or text == '?' or text == 'nan': text = EMPTY_TEXT text = re.sub('[^\\w\\d]+', ' ', text).replace('_', ' ') text = ' '.join(text.split()) text = text.strip() if text: return text return EMPTY_TEXT
['def', 'format_text(text):', 'text', '=', 'text.lower().strip()', 'if', 'text', '==', "'n/a'", 'or', 'text', '==', "'?'", 'or', 'text', '==', "'nan':", 'text', '=', 'EMPTY_TEXT', 'text', '=', "re.sub('[^\\\\w\\\\d]+',", "'", "',", "text).replace('_',", "'", "')", 'text', '=', "'", "'.join(text.split())", 'text', '=', ...
466,854
MycroftAI/mycroft-core
mimic_tts.py
MimicValidator.get_tts_class
get_tts_class
Return the TTS class associated with the validator.
[ "Return", "the", "TTS", "class", "associated", "with", "the", "validator." ]
def get_tts_class(self): return Mimic
['def', 'get_tts_class(self):', 'return', 'Mimic']
290,689
thenamangoyal/artificial-intelligence
__init__.py
FCompiler.dump_properties
dump_properties
Print out the attributes of a compiler instance.
[ "Print", "out", "the", "attributes", "of", "a", "compiler", "instance." ]
def dump_properties(self): props = [] for key in list(self.executables.keys()) + ['version', 'libraries', 'library_dirs', 'object_switch', 'compile_switch']: if hasattr(self, key): v = getattr(self, key) props.append((key, None, '= ' + repr(v))) props.sort() pretty_printe...
['def', 'dump_properties(self):', 'props', '=', '[]', 'for', 'key', 'in', 'list(self.executables.keys())', '+', "['version',", "'libraries',", "'library_dirs',", "'object_switch',", "'compile_switch']:", 'if', 'hasattr(self,', 'key):', 'v', '=', 'getattr(self,', 'key)', 'props.append((key,', 'None,', "'=", "'", '+', 'r...
168,931
intel/neural-compressor
default_dataloader.py
DefaultDataLoader.batch
batch
Set batch_size and last_batch.
[ "Set", "batch_size", "and", "last_batch." ]
def batch(self, batch_size, last_batch='rollover'): self._batch_size = batch_size self.last_batch = last_batch
['def', 'batch(self,', 'batch_size,', "last_batch='rollover'):", 'self._batch_size', '=', 'batch_size', 'self.last_batch', '=', 'last_batch']
738,475
open-mmlab/mmdetection3d
test_fcaf3d_head.py
TestFCAF3DHead.test_fcaf3d_head_loss
test_fcaf3d_head_loss
Test fcaf3d head loss when truth is empty and non-empty.
[ "Test", "fcaf3d", "head", "loss", "when", "truth", "is", "empty", "and", "non-empty." ]
def test_fcaf3d_head_loss(self): if not torch.cuda.is_available(): pytest.skip('test requires GPU and torch+cuda') try: import MinkowskiEngine as ME except ImportError: pytest.skip('test requires MinkowskiEngine installation') fcaf3d_head = FCAF3DHead(in_channels=(64, 128, 256, 5...
['def', 'test_fcaf3d_head_loss(self):', 'if', 'not', 'torch.cuda.is_available():', "pytest.skip('test", 'requires', 'GPU', 'and', "torch+cuda')", 'try:', 'import', 'MinkowskiEngine', 'as', 'ME', 'except', 'ImportError:', "pytest.skip('test", 'requires', 'MinkowskiEngine', "installation')", 'fcaf3d_head', '=', 'FCAF3DHe...
632,494
asyml/texar
conv_networks_test.py
Conv1DNetworkTest.test_unknown_seq_length
test_unknown_seq_length
Tests use of pooling layer when the seq_length dimension of inputs is `None`.
[ "Tests", "use", "of", "pooling", "layer", "when", "the", "seq_length", "dimension", "of", "inputs", "is", "`None`." ]
def test_unknown_seq_length(self): network_1 = Conv1DNetwork() inputs_1 = tf.placeholder(tf.float32, [64, None, 300]) outputs_1 = network_1(inputs_1) self.assertEqual(outputs_1.shape, [64, 128]) hparams = {'num_conv_layers': 2, 'filters': 128, 'kernel_size': [[3, 4, 5], 4], 'pooling': 'AveragePoolin...
['def', 'test_unknown_seq_length(self):', 'network_1', '=', 'Conv1DNetwork()', 'inputs_1', '=', 'tf.placeholder(tf.float32,', '[64,', 'None,', '300])', 'outputs_1', '=', 'network_1(inputs_1)', 'self.assertEqual(outputs_1.shape,', '[64,', '128])', 'hparams', '=', "{'num_conv_layers':", '2,', "'filters':", '128,', "'kern...
924,386
zihuitang/medical_AI_platform
handlers.py
SocketHandler.makePickle
makePickle
Pickles the record in binary format with a length prefix, and returns it ready for transmission across the socket.
[ "Pickles", "the", "record", "in", "binary", "format", "with", "a", "length", "prefix,", "and", "returns", "it", "ready", "for", "transmission", "across", "the", "socket." ]
def makePickle(self, record): ei = record.exc_info if ei: dummy = self.format(record) d = dict(record.__dict__) d['msg'] = record.getMessage() d['args'] = None d['exc_info'] = None d.pop('message', None) s = pickle.dumps(d, 1) slen = struct.pack('>L', len(s)) return slen ...
['def', 'makePickle(self,', 'record):', 'ei', '=', 'record.exc_info', 'if', 'ei:', 'dummy', '=', 'self.format(record)', 'd', '=', 'dict(record.__dict__)', "d['msg']", '=', 'record.getMessage()', "d['args']", '=', 'None', "d['exc_info']", '=', 'None', "d.pop('message',", 'None)', 's', '=', 'pickle.dumps(d,', '1)', 'slen...
283,054
AndrewYinLi/lstm-neural-network-spam-filter
kmeans.py
KMeansClusterer.means
means
The means used for clustering.
[ "The", "means", "used", "for", "clustering." ]
def means(self): return self._means
['def', 'means(self):', 'return', 'self._means']
217,601
ldkong1205/LaserMix
batch_roigridpoint_extractor.py
Batch3DRoIGridExtractor.forward
forward
Forward roi extractor to extract grid points feature.
[ "Forward", "roi", "extractor", "to", "extract", "grid", "points", "feature." ]
def forward(self, feats: torch.Tensor, coordinate: torch.Tensor, batch_inds: torch.Tensor, rois: torch.Tensor) -> torch.Tensor: batch_size = int(batch_inds.max()) + 1 xyz = coordinate xyz_batch_cnt = xyz.new_zeros(batch_size).int() for k in range(batch_size): xyz_batch_cnt[k] = (batch_inds == k)...
['def', 'forward(self,', 'feats:', 'torch.Tensor,', 'coordinate:', 'torch.Tensor,', 'batch_inds:', 'torch.Tensor,', 'rois:', 'torch.Tensor)', '->', 'torch.Tensor:', 'batch_size', '=', 'int(batch_inds.max())', '+', '1', 'xyz', '=', 'coordinate', 'xyz_batch_cnt', '=', 'xyz.new_zeros(batch_size).int()', 'for', 'k', 'in', ...
624,225