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
sek788432/Waymo-2D-Object-Detection
squad_utils.py
find_all_best_thresh
find_all_best_thresh
Finds all best threshold.
[ "Finds", "all", "best", "threshold." ]
def find_all_best_thresh(main_eval, preds, exact_raw, f1_raw, na_probs, qid_to_has_ans): (best_exact, exact_thresh, has_ans_exact) = find_best_thresh(preds, exact_raw, na_probs, qid_to_has_ans) (best_f1, f1_thresh, has_ans_f1) = find_best_thresh(preds, f1_raw, na_probs, qid_to_has_ans) main_eval['best_exact...
['def', 'find_all_best_thresh(main_eval,', 'preds,', 'exact_raw,', 'f1_raw,', 'na_probs,', 'qid_to_has_ans):', '(best_exact,', 'exact_thresh,', 'has_ans_exact)', '=', 'find_best_thresh(preds,', 'exact_raw,', 'na_probs,', 'qid_to_has_ans)', '(best_f1,', 'f1_thresh,', 'has_ans_f1)', '=', 'find_best_thresh(preds,', 'f1_ra...
972,914
Kvatsx/Artificial-Intelligence-Assignments
test_constrainedlayout.py
test_constrained_layout13
test_constrained_layout13
Test that padding works.
[ "Test", "that", "padding", "works." ]
def test_constrained_layout13(): (fig, axs) = plt.subplots(2, 2, constrained_layout=True) for ax in axs.flatten(): pcm = example_pcolor(ax, fontsize=12) fig.colorbar(pcm, ax=ax, shrink=0.6, aspect=20.0, pad=0.02) fig.set_constrained_layout_pads(w_pad=24.0 / 72.0, h_pad=24.0 / 72.0)
['def', 'test_constrained_layout13():', '(fig,', 'axs)', '=', 'plt.subplots(2,', '2,', 'constrained_layout=True)', 'for', 'ax', 'in', 'axs.flatten():', 'pcm', '=', 'example_pcolor(ax,', 'fontsize=12)', 'fig.colorbar(pcm,', 'ax=ax,', 'shrink=0.6,', 'aspect=20.0,', 'pad=0.02)', 'fig.set_constrained_layout_pads(w_pad=24.0...
1,484
weimin17/Object-Detection_HelmetDetection
target_assigner.py
batch_assign_targets
batch_assign_targets
Batched assignment of classification and regression targets.
[ "Batched", "assignment", "of", "classification", "and", "regression", "targets." ]
def batch_assign_targets(target_assigner, anchors_batch, gt_box_batch, gt_class_targets_batch, gt_weights_batch=None): if not isinstance(anchors_batch, list): anchors_batch = len(gt_box_batch) * [anchors_batch] if not all((isinstance(anchors, box_list.BoxList) for anchors in anchors_batch)): rai...
['def', 'batch_assign_targets(target_assigner,', 'anchors_batch,', 'gt_box_batch,', 'gt_class_targets_batch,', 'gt_weights_batch=None):', 'if', 'not', 'isinstance(anchors_batch,', 'list):', 'anchors_batch', '=', 'len(gt_box_batch)', '*', '[anchors_batch]', 'if', 'not', 'all((isinstance(anchors,', 'box_list.BoxList)', '...
758,818
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
_DictWrapper.Incr
Incr
Increments the freq/prob associated with the value x.
[ "Increments", "the", "freq/prob", "associated", "with", "the", "value", "x." ]
def Incr(self, x, term=1): self.d[x] = self.d.get(x, 0) + term
['def', 'Incr(self,', 'x,', 'term=1):', 'self.d[x]', '=', 'self.d.get(x,', '0)', '+', 'term']
12,901
liuhuiwisdom/object_detection
base_model.py
BaseModel.setup
setup
Setup useful parameters for class balancing.
[ "Setup", "useful", "parameters", "for", "class", "balancing." ]
def setup(self, show_data=True): p = self.class_balancing_factor stats = np.load(self.anchor_stat_file) self.anchor_iou_freq = stats['anchor_iou_freq'] self.class_iou_freq = stats['class_iou_freq'] if show_data: print('Class frequencies:') for j in range(self.num_anchor_type): ...
['def', 'setup(self,', 'show_data=True):', 'p', '=', 'self.class_balancing_factor', 'stats', '=', 'np.load(self.anchor_stat_file)', 'self.anchor_iou_freq', '=', "stats['anchor_iou_freq']", 'self.class_iou_freq', '=', "stats['class_iou_freq']", 'if', 'show_data:', "print('Class", "frequencies:')", 'for', 'j', 'in', 'ran...
744,843
devashish-patel/webcam-motion-detector
parse.py
splittype
splittype
splittype('type:opaquestring') --> 'type', 'opaquestring'.
[ "splittype('type:opaquestring')", "-->", "'type',", "'opaquestring'." ]
def splittype(url): global _typeprog if _typeprog is None: import re _typeprog = re.compile('^([^/:]+):') match = _typeprog.match(url) if match: scheme = match.group(1) return (scheme.lower(), url[len(scheme) + 1:]) return (None, url)
['def', 'splittype(url):', 'global', '_typeprog', 'if', '_typeprog', 'is', 'None:', 'import', 're', '_typeprog', '=', "re.compile('^([^/:]+):')", 'match', '=', '_typeprog.match(url)', 'if', 'match:', 'scheme', '=', 'match.group(1)', 'return', '(scheme.lower(),', 'url[len(scheme)', '+', '1:])', 'return', '(None,', 'url)...
978,114
ykamikawa/tf-keras-yolov2-tracking
sort.py
KalmanBoxTracker.update
update
Updates the state vector with observed bbox.
[ "Updates", "the", "state", "vector", "with", "observed", "bbox." ]
def update(self, bbox): self.time_since_update = 0 self.history = [] self.hits += 1 self.hit_streak += 1 self.kf.update(convert_bbox_to_z(bbox))
['def', 'update(self,', 'bbox):', 'self.time_since_update', '=', '0', 'self.history', '=', '[]', 'self.hits', '+=', '1', 'self.hit_streak', '+=', '1', 'self.kf.update(convert_bbox_to_z(bbox))']
914,227
zehuichen123/AutoAlignV2
anchor_3d_generator.py
Anchor3DRangeGenerator.grid_anchors
grid_anchors
Generate grid anchors in multiple feature levels.
[ "Generate", "grid", "anchors", "in", "multiple", "feature", "levels." ]
def grid_anchors(self, featmap_sizes, device='cuda'): assert self.num_levels == len(featmap_sizes) multi_level_anchors = [] for i in range(self.num_levels): anchors = self.single_level_grid_anchors(featmap_sizes[i], self.scales[i], device=device) if self.reshape_out: anchors = an...
['def', 'grid_anchors(self,', 'featmap_sizes,', "device='cuda'):", 'assert', 'self.num_levels', '==', 'len(featmap_sizes)', 'multi_level_anchors', '=', '[]', 'for', 'i', 'in', 'range(self.num_levels):', 'anchors', '=', 'self.single_level_grid_anchors(featmap_sizes[i],', 'self.scales[i],', 'device=device)', 'if', 'self....
416,475
implus/GFocalV2
utils.py
weight_reduce_loss
weight_reduce_loss
Apply element-wise weight and reduce loss.
[ "Apply", "element-wise", "weight", "and", "reduce", "loss." ]
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None): if weight is not None: loss = loss * weight if avg_factor is None: loss = reduce_loss(loss, reduction) elif reduction == 'mean': loss = loss.sum() / avg_factor elif reduction != 'none': raise Va...
['def', 'weight_reduce_loss(loss,', 'weight=None,', "reduction='mean',", 'avg_factor=None):', 'if', 'weight', 'is', 'not', 'None:', 'loss', '=', 'loss', '*', 'weight', 'if', 'avg_factor', 'is', 'None:', 'loss', '=', 'reduce_loss(loss,', 'reduction)', 'elif', 'reduction', '==', "'mean':", 'loss', '=', 'loss.sum()', '/',...
557,710
weimin17/Object-Detection_HelmetDetection
mel_features.py
hertz_to_mel
hertz_to_mel
Convert frequencies to mel scale using HTK formula.
[ "Convert", "frequencies", "to", "mel", "scale", "using", "HTK", "formula." ]
def hertz_to_mel(frequencies_hertz): return _MEL_HIGH_FREQUENCY_Q * np.log(1.0 + frequencies_hertz / _MEL_BREAK_FREQUENCY_HERTZ)
['def', 'hertz_to_mel(frequencies_hertz):', 'return', '_MEL_HIGH_FREQUENCY_Q', '*', 'np.log(1.0', '+', 'frequencies_hertz', '/', '_MEL_BREAK_FREQUENCY_HERTZ)']
749,227
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
neural_gpu_trainer.py
initialize
initialize
Initialize data and model.
[ "Initialize", "data", "and", "model." ]
def initialize(sess=None): global MAXLEN_F if not tf.gfile.IsDirectory(FLAGS.train_dir): data.print_out('Creating training directory %s.' % FLAGS.train_dir) tf.gfile.MkDir(FLAGS.train_dir) decode_suffix = 'beam%dln%d' % (FLAGS.beam_size, int(100 * FLAGS.length_norm)) if FLAGS.mode == 0: ...
['def', 'initialize(sess=None):', 'global', 'MAXLEN_F', 'if', 'not', 'tf.gfile.IsDirectory(FLAGS.train_dir):', "data.print_out('Creating", 'training', 'directory', "%s.'", '%', 'FLAGS.train_dir)', 'tf.gfile.MkDir(FLAGS.train_dir)', 'decode_suffix', '=', "'beam%dln%d'", '%', '(FLAGS.beam_size,', 'int(100', '*', 'FLAGS.l...
50,195
alteryx/compose
test_label_maker.py
test_search_offset_mix_0
test_search_offset_mix_0
Test offset mix with window_size (absolute), minimum_data (absolute), and gap (absolute).
[ "Test", "offset", "mix", "with", "window_size", "(absolute),", "minimum_data", "(absolute),", "and", "gap", "(absolute)." ]
def test_search_offset_mix_0(transactions, total_spent_fn): lm = LabelMaker(target_dataframe_index='customer_id', time_index='time', labeling_function=total_spent_fn, window_size='2h') given_labels = lm.search(transactions, num_examples_per_instance=2, minimum_data='30min', gap='2h', drop_empty=True) given_...
['def', 'test_search_offset_mix_0(transactions,', 'total_spent_fn):', 'lm', '=', "LabelMaker(target_dataframe_index='customer_id',", "time_index='time',", 'labeling_function=total_spent_fn,', "window_size='2h')", 'given_labels', '=', 'lm.search(transactions,', 'num_examples_per_instance=2,', "minimum_data='30min',", "g...
136,061
TheCurryMan/MedicAI
debug.py
ProcessedTraceback.exc_info
exc_info
Exception info tuple with a proxy around the frame objects.
[ "Exception", "info", "tuple", "with", "a", "proxy", "around", "the", "frame", "objects." ]
def exc_info(self): return (self.exc_type, self.exc_value, self.frames[0])
['def', 'exc_info(self):', 'return', '(self.exc_type,', 'self.exc_value,', 'self.frames[0])']
648,323
011235813/hierarchical-marl
alg_qmix.py
Alg.run_actor
run_actor
Get actions for all agents as a batch.
[ "Get", "actions", "for", "all", "agents", "as", "a", "batch." ]
def run_actor(self, list_obs, epsilon, sess): obs = np.array(list_obs) feed = {self.obs: obs} actions_argmax = sess.run(self.argmax_Q, feed_dict=feed) actions = np.zeros(self.n_agents, dtype=int) for idx in range(self.n_agents): if np.random.rand() < epsilon: actions[idx] = np.ra...
['def', 'run_actor(self,', 'list_obs,', 'epsilon,', 'sess):', 'obs', '=', 'np.array(list_obs)', 'feed', '=', '{self.obs:', 'obs}', 'actions_argmax', '=', 'sess.run(self.argmax_Q,', 'feed_dict=feed)', 'actions', '=', 'np.zeros(self.n_agents,', 'dtype=int)', 'for', 'idx', 'in', 'range(self.n_agents):', 'if', 'np.random.r...
592,885
Alexander-Parker/youtube_nlp
topology.py
Topology.reset_server_and_request_check
reset_server_and_request_check
Clear our pool for a server, mark it Unknown, and check it soon.
[ "Clear", "our", "pool", "for", "a", "server,", "mark", "it", "Unknown,", "and", "check", "it", "soon." ]
def reset_server_and_request_check(self, address): with self._lock: self._reset_server(address) self._request_check(address)
['def', 'reset_server_and_request_check(self,', 'address):', 'with', 'self._lock:', 'self._reset_server(address)', 'self._request_check(address)']
970,678
devashish-patel/webcam-motion-detector
document.py
Document.apply_json_patch_string
apply_json_patch_string
Apply a JSON patch provided as a string.
[ "Apply", "a", "JSON", "patch", "provided", "as", "a", "string." ]
def apply_json_patch_string(self, patch): json_parsed = loads(patch) self.apply_json_patch(json_parsed)
['def', 'apply_json_patch_string(self,', 'patch):', 'json_parsed', '=', 'loads(patch)', 'self.apply_json_patch(json_parsed)']
977,295
xiaoaleiBLUE/computer_vision
data.py
FaceSegIter.next
next
Returns the next batch of data.
[ "Returns", "the", "next", "batch", "of", "data." ]
def next(self): batch_size = self.batch_size batch_data = nd.empty((batch_size,) + self.data_shape) batch_label = nd.empty((batch_size,) + self.label_shape) i = 0 try: while i < batch_size: (data, label, annot) = self.next_sample() R = self.get_data(data, label, annot...
['def', 'next(self):', 'batch_size', '=', 'self.batch_size', 'batch_data', '=', 'nd.empty((batch_size,)', '+', 'self.data_shape)', 'batch_label', '=', 'nd.empty((batch_size,)', '+', 'self.label_shape)', 'i', '=', '0', 'try:', 'while', 'i', '<', 'batch_size:', '(data,', 'label,', 'annot)', '=', 'self.next_sample()', 'R'...
474,044
apeterswu/RL4NMT
generator_utils.py
maybe_download
maybe_download
Download filename from url unless it's already in directory.
[ "Download", "filename", "from", "url", "unless", "it's", "already", "in", "directory." ]
def maybe_download(directory, filename, url): if not tf.gfile.Exists(directory): tf.logging.info('Creating directory %s' % directory) os.mkdir(directory) filepath = os.path.join(directory, filename) if not tf.gfile.Exists(filepath): tf.logging.info('Downloading %s to %s' % (url, file...
['def', 'maybe_download(directory,', 'filename,', 'url):', 'if', 'not', 'tf.gfile.Exists(directory):', "tf.logging.info('Creating", 'directory', "%s'", '%', 'directory)', 'os.mkdir(directory)', 'filepath', '=', 'os.path.join(directory,', 'filename)', 'if', 'not', 'tf.gfile.Exists(filepath):', "tf.logging.info('Download...
331,380
caiiiac/Machine-Learning-with-Python
mathtext.py
MathtextBackend.render_rect_filled
render_rect_filled
Draw a filled black rectangle from (*x1*, *y1*) to (*x2*, *y2*).
[ "Draw", "a", "filled", "black", "rectangle", "from", "(*x1*,", "*y1*)", "to", "(*x2*,", "*y2*)." ]
def render_rect_filled(self, x1, y1, x2, y2): raise NotImplementedError()
['def', 'render_rect_filled(self,', 'x1,', 'y1,', 'x2,', 'y2):', 'raise', 'NotImplementedError()']
715,593
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
errorcounter.py
AddErrors
AddErrors
Adds the counts and returns a new sum tuple.
[ "Adds", "the", "counts", "and", "returns", "a", "new", "sum", "tuple." ]
def AddErrors(counts1, counts2): return ErrorCounts(counts1.fn + counts2.fn, counts1.fp + counts2.fp, counts1.truth_count + counts2.truth_count, counts1.test_count + counts2.test_count)
['def', 'AddErrors(counts1,', 'counts2):', 'return', 'ErrorCounts(counts1.fn', '+', 'counts2.fn,', 'counts1.fp', '+', 'counts2.fp,', 'counts1.truth_count', '+', 'counts2.truth_count,', 'counts1.test_count', '+', 'counts2.test_count)']
110,433
caiiiac/Machine-Learning-with-Python
expr.py
add_ops
add_ops
Decorator to add default implementation of ops.
[ "Decorator", "to", "add", "default", "implementation", "of", "ops." ]
def add_ops(op_classes): def f(cls): for (op_attr_name, op_class) in compat.iteritems(op_classes): ops = getattr(cls, '{0}_ops'.format(op_attr_name)) ops_map = getattr(cls, '{0}_op_nodes_map'.format(op_attr_name)) for op in ops: op_node = ops_map[op] ...
['def', 'add_ops(op_classes):', 'def', 'f(cls):', 'for', '(op_attr_name,', 'op_class)', 'in', 'compat.iteritems(op_classes):', 'ops', '=', 'getattr(cls,', "'{0}_ops'.format(op_attr_name))", 'ops_map', '=', 'getattr(cls,', "'{0}_op_nodes_map'.format(op_attr_name))", 'for', 'op', 'in', 'ops:', 'op_node', '=', 'ops_map[op...
717,918
Mdominik/artificial_intelligence
baseparser.py
PrettyHelpFormatter.format_usage
format_usage
Ensure there is only one newline between usage and the first heading if there is no description.
[ "Ensure", "there", "is", "only", "one", "newline", "between", "usage", "and", "the", "first", "heading", "if", "there", "is", "no", "description." ]
def format_usage(self, usage): msg = '\nUsage: %s\n' % self.indent_lines(textwrap.dedent(usage), ' ') return msg
['def', 'format_usage(self,', 'usage):', 'msg', '=', "'\\nUsage:", "%s\\n'", '%', 'self.indent_lines(textwrap.dedent(usage),', "'", "')", 'return', 'msg']
71,663
bachiraoun/fullrmc
Translations.py
TranslationTowardsSymmetryAxisGenerator.angle
angle
Tolerance maximum angle in rad.
[ "Tolerance", "maximum", "angle", "in", "rad." ]
def angle(self): return self.__angle
['def', 'angle(self):', 'return', 'self.__angle']
213,975
megvii-research/MSCL
webcam_demo_spatiotemporal_det.py
TaskInfo.add_bboxes
add_bboxes
Add correspondding bounding boxes.
[ "Add", "correspondding", "bounding", "boxes." ]
def add_bboxes(self, display_bboxes): self.display_bboxes = display_bboxes self.stdet_bboxes = display_bboxes.clone() self.stdet_bboxes[:, ::2] = self.stdet_bboxes[:, ::2] * self.ratio[0] self.stdet_bboxes[:, 1::2] = self.stdet_bboxes[:, 1::2] * self.ratio[1]
['def', 'add_bboxes(self,', 'display_bboxes):', 'self.display_bboxes', '=', 'display_bboxes', 'self.stdet_bboxes', '=', 'display_bboxes.clone()', 'self.stdet_bboxes[:,', '::2]', '=', 'self.stdet_bboxes[:,', '::2]', '*', 'self.ratio[0]', 'self.stdet_bboxes[:,', '1::2]', '=', 'self.stdet_bboxes[:,', '1::2]', '*', 'self.r...
264,654
benedekrozemberczki/DANMF
danmf.py
DANMF.pre_training
pre_training
Pre-training each NMF layer.
[ "Pre-training", "each", "NMF", "layer." ]
def pre_training(self): print('\nLayer pre-training started. \n') self.U_s = [] self.V_s = [] for i in tqdm(range(self.p), desc='Layers trained: ', leave=True): self.setup_z(i) (U, V) = self.sklearn_pretrain(i) self.U_s.append(U) self.V_s.append(V)
['def', 'pre_training(self):', "print('\\nLayer", 'pre-training', 'started.', "\\n')", 'self.U_s', '=', '[]', 'self.V_s', '=', '[]', 'for', 'i', 'in', 'tqdm(range(self.p),', "desc='Layers", 'trained:', "',", 'leave=True):', 'self.setup_z(i)', '(U,', 'V)', '=', 'self.sklearn_pretrain(i)', 'self.U_s.append(U)', 'self.V_s...
497,120
Gorilla-Lab-SCUT/frustum-convnet
provider_sample.py
ProviderDataset.get_box3d_center
get_box3d_center
Get the center (XYZ) of 3D bounding box.
[ "Get", "the", "center", "(XYZ)", "of", "3D", "bounding", "box." ]
def get_box3d_center(self, index): box3d_center = (self.box3d_list[index][0, :] + self.box3d_list[index][6, :]) / 2.0 return box3d_center
['def', 'get_box3d_center(self,', 'index):', 'box3d_center', '=', '(self.box3d_list[index][0,', ':]', '+', 'self.box3d_list[index][6,', ':])', '/', '2.0', 'return', 'box3d_center']
564,795
Xianpeng919/MonoCon
inference.py
show_seg_result_meshlab
show_seg_result_meshlab
Show 3D segmentation result by meshlab.
[ "Show", "3D", "segmentation", "result", "by", "meshlab." ]
def show_seg_result_meshlab(data, result, out_dir, palette, show=False, snapshot=False): points = data['points'][0][0].cpu().numpy() pts_filename = data['img_metas'][0][0]['pts_filename'] file_name = osp.split(pts_filename)[-1].split('.')[0] pred_seg = result[0]['semantic_mask'].numpy() if palette i...
['def', 'show_seg_result_meshlab(data,', 'result,', 'out_dir,', 'palette,', 'show=False,', 'snapshot=False):', 'points', '=', "data['points'][0][0].cpu().numpy()", 'pts_filename', '=', "data['img_metas'][0][0]['pts_filename']", 'file_name', '=', "osp.split(pts_filename)[-1].split('.')[0]", 'pred_seg', '=', "result[0]['...
654,210
Jamie725/Multimodal-Object-Detection-via-Probabilistic-Ensembling
gaussian_blur.py
get_gaussian_kernel
get_gaussian_kernel
Function that returns Gaussian filter coefficients.
[ "Function", "that", "returns", "Gaussian", "filter", "coefficients." ]
def get_gaussian_kernel(ksize, sigma): if not isinstance(ksize, int) or ksize % 2 == 0 or ksize <= 0: raise TypeError('ksize must be an odd positive integer. Got {}'.format(ksize)) window_1d: torch.Tensor = gaussian(ksize, sigma) return window_1d
['def', 'get_gaussian_kernel(ksize,', 'sigma):', 'if', 'not', 'isinstance(ksize,', 'int)', 'or', 'ksize', '%', '2', '==', '0', 'or', 'ksize', '<=', '0:', 'raise', "TypeError('ksize", 'must', 'be', 'an', 'odd', 'positive', 'integer.', 'Got', "{}'.format(ksize))", 'window_1d:', 'torch.Tensor', '=', 'gaussian(ksize,', 'si...
643,873
weimin17/Object-Detection_HelmetDetection
accountant.py
AmortizedAccountant.get_privacy_spent
get_privacy_spent
Report the spending so far.
[ "Report", "the", "spending", "so", "far." ]
def get_privacy_spent(self, sess, target_eps=None): unused_target_eps = target_eps (eps_squared_sum, delta_sum) = sess.run([self._eps_squared_sum, self._delta_sum]) return [EpsDelta(math.sqrt(eps_squared_sum), float(delta_sum))]
['def', 'get_privacy_spent(self,', 'sess,', 'target_eps=None):', 'unused_target_eps', '=', 'target_eps', '(eps_squared_sum,', 'delta_sum)', '=', 'sess.run([self._eps_squared_sum,', 'self._delta_sum])', 'return', '[EpsDelta(math.sqrt(eps_squared_sum),', 'float(delta_sum))]']
762,620
fafa92/CSCI-544-Applied-Natural-Language-
starter3.py
SequenceModel.save_model
save_model
Saves model to a file.
[ "Saves", "model", "to", "a", "file." ]
def save_model(self, filename): var_dict = {v.name: v for v in tf.global_variables()} pickle.dump(self.sess.run(var_dict), open(filename, 'w')) pass
['def', 'save_model(self,', 'filename):', 'var_dict', '=', '{v.name:', 'v', 'for', 'v', 'in', 'tf.global_variables()}', 'pickle.dump(self.sess.run(var_dict),', 'open(filename,', "'w'))", 'pass']
508,482
aimclub/FEDOT
base_preprocessing.py
BasePreprocessor.obligatory_prepare_for_fit
obligatory_prepare_for_fit
Performs obligatory preprocessing for pipeline's fit method.
[ "Performs", "obligatory", "preprocessing", "for", "pipeline's", "fit", "method." ]
def obligatory_prepare_for_fit(self, data: Union[InputData, MultiModalData]) -> Union[InputData, MultiModalData]: raise AbstractMethodNotImplementError
['def', 'obligatory_prepare_for_fit(self,', 'data:', 'Union[InputData,', 'MultiModalData])', '->', 'Union[InputData,', 'MultiModalData]:', 'raise', 'AbstractMethodNotImplementError']
545,955
sklearn-theano/sklearn-theano
wire_format.py
IsTypePackable
IsTypePackable
Return true iff packable = true is valid for fields of this type.
[ "Return", "true", "iff", "packable", "=", "true", "is", "valid", "for", "fields", "of", "this", "type." ]
def IsTypePackable(field_type): return field_type not in NON_PACKABLE_TYPES
['def', 'IsTypePackable(field_type):', 'return', 'field_type', 'not', 'in', 'NON_PACKABLE_TYPES']
351,219
zackmcnulty/CSE_446-Machine_Learning
tarfile.py
TarInfo.create_pax_global_header
create_pax_global_header
Return the object as a pax global header block sequence.
[ "Return", "the", "object", "as", "a", "pax", "global", "header", "block", "sequence." ]
def create_pax_global_header(cls, pax_headers): return cls._create_pax_generic_header(pax_headers, XGLTYPE, 'utf8')
['def', 'create_pax_global_header(cls,', 'pax_headers):', 'return', 'cls._create_pax_generic_header(pax_headers,', 'XGLTYPE,', "'utf8')"]
196,673
neokarn/computer_vision
cpp_lint.py
_CppLintState.IncrementErrorCount
IncrementErrorCount
Bumps the module's error statistic.
[ "Bumps", "the", "module's", "error", "statistic." ]
def IncrementErrorCount(self, category): self.error_count += 1 if self.counting in ('toplevel', 'detailed'): if self.counting != 'detailed': category = category.split('/')[0] if category not in self.errors_by_category: self.errors_by_category[category] = 0 self.er...
['def', 'IncrementErrorCount(self,', 'category):', 'self.error_count', '+=', '1', 'if', 'self.counting', 'in', "('toplevel',", "'detailed'):", 'if', 'self.counting', '!=', "'detailed':", 'category', '=', "category.split('/')[0]", 'if', 'category', 'not', 'in', 'self.errors_by_category:', 'self.errors_by_category[catego...
472,909
bislara/Object-detection-GUI
inputs.py
create_predict_input_fn
create_predict_input_fn
Creates a predict `input` function for `Estimator`.
[ "Creates", "a", "predict", "`input`", "function", "for", "`Estimator`." ]
def create_predict_input_fn(model_config, predict_input_config): def _predict_input_fn(params=None): del params example = tf.placeholder(dtype=tf.string, shape=[], name='tf_example') num_classes = config_util.get_number_of_classes(model_config) model_preprocess_fn = INPUT_BUILDER_UT...
['def', 'create_predict_input_fn(model_config,', 'predict_input_config):', 'def', '_predict_input_fn(params=None):', 'del', 'params', 'example', '=', 'tf.placeholder(dtype=tf.string,', 'shape=[],', "name='tf_example')", 'num_classes', '=', 'config_util.get_number_of_classes(model_config)', 'model_preprocess_fn', '=', "...
726,306
open-mmlab/mmrotate
test_rtransforms.py
test_rresize
test_rresize
Test resize for rbboxes.
[ "Test", "resize", "for", "rbboxes." ]
def test_rresize(): results = construct_toy_data() transform = dict(type='RResize', img_scale=(8, 8)) rresize_module = build_from_cfg(transform, PIPELINES) results_rresize = rresize_module(copy.deepcopy(results)) assert results_rresize['img_shape'] == (4, 8, 3)
['def', 'test_rresize():', 'results', '=', 'construct_toy_data()', 'transform', '=', "dict(type='RResize',", 'img_scale=(8,', '8))', 'rresize_module', '=', 'build_from_cfg(transform,', 'PIPELINES)', 'results_rresize', '=', 'rresize_module(copy.deepcopy(results))', 'assert', "results_rresize['img_shape']", '==', '(4,', ...
625,251
openvinotoolkit/training_extensions
imgclsmob.py
multioutput_forward
multioutput_forward
Multioutput forward function for new model (copy from mmdet older).
[ "Multioutput", "forward", "function", "for", "new", "model", "(copy", "from", "mmdet", "older)." ]
def multioutput_forward(self, x): outputs = [] y = x last_stage = max(self.out_indices) for (i, stage) in enumerate(self.features): y = stage(y) s_verbose = str(i) + ' ' + str(y.shape) if i in self.out_indices: outputs.append(y) s_verbose += '*' if...
['def', 'multioutput_forward(self,', 'x):', 'outputs', '=', '[]', 'y', '=', 'x', 'last_stage', '=', 'max(self.out_indices)', 'for', '(i,', 'stage)', 'in', 'enumerate(self.features):', 'y', '=', 'stage(y)', 's_verbose', '=', 'str(i)', '+', "'", "'", '+', 'str(y.shape)', 'if', 'i', 'in', 'self.out_indices:', 'outputs.app...
918,091
ldkong1205/LaserMix
box_np_ops.py
corner_to_surfaces_3d_jit
corner_to_surfaces_3d_jit
Convert 3d box corners from corner function above to surfaces that normal vectors all direct to internal.
[ "Convert", "3d", "box", "corners", "from", "corner", "function", "above", "to", "surfaces", "that", "normal", "vectors", "all", "direct", "to", "internal." ]
def corner_to_surfaces_3d_jit(corners): num_boxes = corners.shape[0] surfaces = np.zeros((num_boxes, 6, 4, 3), dtype=corners.dtype) corner_idxes = np.array([0, 1, 2, 3, 7, 6, 5, 4, 0, 3, 7, 4, 1, 5, 6, 2, 0, 4, 5, 1, 3, 2, 6, 7]).reshape(6, 4) for i in range(num_boxes): for j in range(6): ...
['def', 'corner_to_surfaces_3d_jit(corners):', 'num_boxes', '=', 'corners.shape[0]', 'surfaces', '=', 'np.zeros((num_boxes,', '6,', '4,', '3),', 'dtype=corners.dtype)', 'corner_idxes', '=', 'np.array([0,', '1,', '2,', '3,', '7,', '6,', '5,', '4,', '0,', '3,', '7,', '4,', '1,', '5,', '6,', '2,', '0,', '4,', '5,', '1,', ...
624,403
facebookresearch/salina
halfcheetah.py
Halfcheetah.reset
reset
Resets the environment to an initial state.
[ "Resets", "the", "environment", "to", "an", "initial", "state." ]
def reset(self, rng: jp.ndarray) -> _env.State: (rng, rng1, rng2) = jp.random_split(rng, 3) qpos = self.sys.default_angle() + self._noise(rng1) qvel = self._noise(rng2) qp = self.sys.default_qp(joint_angle=qpos, joint_velocity=qvel) self._qps = [qp] obs = self._get_obs(qp, self.sys.info(qp)) ...
['def', 'reset(self,', 'rng:', 'jp.ndarray)', '->', '_env.State:', '(rng,', 'rng1,', 'rng2)', '=', 'jp.random_split(rng,', '3)', 'qpos', '=', 'self.sys.default_angle()', '+', 'self._noise(rng1)', 'qvel', '=', 'self._noise(rng2)', 'qp', '=', 'self.sys.default_qp(joint_angle=qpos,', 'joint_velocity=qvel)', 'self._qps', '...
328,525
microsoft/InnerEye-DeepLearning
test_segmentation_configs.py
test_prostate_base_with_optional_params
test_prostate_base_with_optional_params
Check that optional parameters can be passed in to ProstateBase class.
[ "Check", "that", "optional", "parameters", "can", "be", "passed", "in", "to", "ProstateBase", "class." ]
def test_prostate_base_with_optional_params() -> None: ground_truth_ids = DEFAULT_PROSTATE_GROUND_TRUTH_IDS ground_truth_count = len(ground_truth_ids) ground_truth_ids_display_names = generate_random_display_ids(ground_truth_count) colours = generate_random_colours_list(RANDOM_COLOUR_GENERATOR, ground_t...
['def', 'test_prostate_base_with_optional_params()', '->', 'None:', 'ground_truth_ids', '=', 'DEFAULT_PROSTATE_GROUND_TRUTH_IDS', 'ground_truth_count', '=', 'len(ground_truth_ids)', 'ground_truth_ids_display_names', '=', 'generate_random_display_ids(ground_truth_count)', 'colours', '=', 'generate_random_colours_list(RA...
613,559
BerkeleyLearnVerify/VerifAI
kitti_vgg16_config.py
kitti_vgg16_config
kitti_vgg16_config
Specify the parameters to tune below.
[ "Specify", "the", "parameters", "to", "tune", "below." ]
def kitti_vgg16_config(): mc = base_model_config('KITTI') mc.IMAGE_WIDTH = 1242 mc.IMAGE_HEIGHT = 375 mc.BATCH_SIZE = 5 mc.WEIGHT_DECAY = 0.0001 mc.LEARNING_RATE = 0.01 mc.DECAY_STEPS = 10000 mc.MAX_GRAD_NORM = 1.0 mc.MOMENTUM = 0.9 mc.LR_DECAY_FACTOR = 0.5 mc.LOSS_COEF_BBOX ...
['def', 'kitti_vgg16_config():', 'mc', '=', "base_model_config('KITTI')", 'mc.IMAGE_WIDTH', '=', '1242', 'mc.IMAGE_HEIGHT', '=', '375', 'mc.BATCH_SIZE', '=', '5', 'mc.WEIGHT_DECAY', '=', '0.0001', 'mc.LEARNING_RATE', '=', '0.01', 'mc.DECAY_STEPS', '=', '10000', 'mc.MAX_GRAD_NORM', '=', '1.0', 'mc.MOMENTUM', '=', '0.9',...
379,352
TengXiaoDai/DistributedCrawling
archive.py
archive_wheelfile
archive_wheelfile
Archive all files under `base_dir` in a whl file and name it like `base_name`.
[ "Archive", "all", "files", "under", "`base_dir`", "in", "a", "whl", "file", "and", "name", "it", "like", "`base_name`." ]
def archive_wheelfile(base_name, base_dir): olddir = os.path.abspath(os.curdir) base_name = os.path.abspath(base_name) try: os.chdir(base_dir) return make_wheelfile_inner(base_name) finally: os.chdir(olddir)
['def', 'archive_wheelfile(base_name,', 'base_dir):', 'olddir', '=', 'os.path.abspath(os.curdir)', 'base_name', '=', 'os.path.abspath(base_name)', 'try:', 'os.chdir(base_dir)', 'return', 'make_wheelfile_inner(base_name)', 'finally:', 'os.chdir(olddir)']
189,372
YannDubs/Invariant-Self-Supervised-Learning
helpers.py
assert_sns_vary_only_param
assert_sns_vary_only_param
Make sure that the only multi indices that have not been conditioned over for plotting and has non unique values are in `param_vary_only`.
[ "Make", "sure", "that", "the", "only", "multi", "indices", "that", "have", "not", "been", "conditioned", "over", "for", "plotting", "and", "has", "non", "unique", "values", "are", "in", "`param_vary_only`." ]
def assert_sns_vary_only_param(data: pd.DataFrame, sns_kwargs: dict, param_vary_only: Optional[list]) -> None: if param_vary_only is not None: multi_idcs = data.index issues = [] for idx in multi_idcs.levels: is_varying = len(idx.values) != 1 is_conditioned = idx.name...
['def', 'assert_sns_vary_only_param(data:', 'pd.DataFrame,', 'sns_kwargs:', 'dict,', 'param_vary_only:', 'Optional[list])', '->', 'None:', 'if', 'param_vary_only', 'is', 'not', 'None:', 'multi_idcs', '=', 'data.index', 'issues', '=', '[]', 'for', 'idx', 'in', 'multi_idcs.levels:', 'is_varying', '=', 'len(idx.values)', ...
246,011
Katja-M/Python_NaturalLanguageProcessing
versioncontrol.py
VersionControl.get_url_rev_options
get_url_rev_options
Return the URL and RevOptions object to use in obtain() and in some cases export(), as a tuple (url, rev_options).
[ "Return", "the", "URL", "and", "RevOptions", "object", "to", "use", "in", "obtain()", "and", "in", "some", "cases", "export(),", "as", "a", "tuple", "(url,", "rev_options)." ]
def get_url_rev_options(self, url): (secret_url, rev, user_pass) = self.get_url_rev_and_auth(url.secret) (username, secret_password) = user_pass password = None if secret_password is not None: password = hide_value(secret_password) extra_args = self.make_rev_args(username, password) rev_...
['def', 'get_url_rev_options(self,', 'url):', '(secret_url,', 'rev,', 'user_pass)', '=', 'self.get_url_rev_and_auth(url.secret)', '(username,', 'secret_password)', '=', 'user_pass', 'password', '=', 'None', 'if', 'secret_password', 'is', 'not', 'None:', 'password', '=', 'hide_value(secret_password)', 'extra_args', '=',...
868,327
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
operator.py
ge
ge
Same as a >= b.
[ "Same", "as", "a", ">=", "b." ]
def ge(a, b): return a >= b
['def', 'ge(a,', 'b):', 'return', 'a', '>=', 'b']
428,975
muhanzhang/D-VAE
test_rng_curand.py
test_normal_basic
test_normal_basic
Run the tests for `normal` with different settings for the shape tuple passed in.
[ "Run", "the", "tests", "for", "`normal`", "with", "different", "settings", "for", "the", "shape", "tuple", "passed", "in." ]
def test_normal_basic(): yield (check_normal_basic, False) yield (check_normal_basic, False, True) yield (check_normal_basic, True)
['def', 'test_normal_basic():', 'yield', '(check_normal_basic,', 'False)', 'yield', '(check_normal_basic,', 'False,', 'True)', 'yield', '(check_normal_basic,', 'True)']
525,196
dengliangshi/pynnlms
vocab.py
Vocab.assign
assign
Assign each word with feature vector and class.
[ "Assign", "each", "word", "with", "feature", "vector", "and", "class." ]
def assign(self): index = 0 cindex = 0 ac_freq = 0 start_index = 0 sorted_words = sorted(self.freq.iteritems(), key=lambda d: d[1], reverse=True) base = sum([x[1] for x in sorted_words]) sqrt_base = sum([np.sqrt(x[1] / float(base)) for x in sorted_words]) for (word, freq) in sorted_words...
['def', 'assign(self):', 'index', '=', '0', 'cindex', '=', '0', 'ac_freq', '=', '0', 'start_index', '=', '0', 'sorted_words', '=', 'sorted(self.freq.iteritems(),', 'key=lambda', 'd:', 'd[1],', 'reverse=True)', 'base', '=', 'sum([x[1]', 'for', 'x', 'in', 'sorted_words])', 'sqrt_base', '=', 'sum([np.sqrt(x[1]', '/', 'flo...
296,761
Trusted-AI/adversarial-robustness-toolbox
pytorch.py
PyTorchRegressor.reset
reset
Resets the weights of the regressor so that it can be refit from scratch.
[ "Resets", "the", "weights", "of", "the", "regressor", "so", "that", "it", "can", "be", "refit", "from", "scratch." ]
def reset(self) -> None: def weight_reset(module): reset_parameters = getattr(module, 'reset_parameters', None) if reset_parameters and callable(reset_parameters): module.reset_parameters() self.model.apply(weight_reset)
['def', 'reset(self)', '->', 'None:', 'def', 'weight_reset(module):', 'reset_parameters', '=', 'getattr(module,', "'reset_parameters',", 'None)', 'if', 'reset_parameters', 'and', 'callable(reset_parameters):', 'module.reset_parameters()', 'self.model.apply(weight_reset)']
398,289
suarez12138/AI-Reversi_IMP_TextDichotomy
test_slsqp.py
TestSLSQP.jac
jac
This is the derivative of fun, returning a NumPy array representing df/dx and df/dy.
[ "This", "is", "the", "derivative", "of", "fun,", "returning", "a", "NumPy", "array", "representing", "df/dx", "and", "df/dy." ]
def jac(self, d, sign=1.0): x = d[0] y = d[1] dfdx = sign * (-2 * x + 2 * y + 2) dfdy = sign * (2 * x - 4 * y) return np.array([dfdx, dfdy], float)
['def', 'jac(self,', 'd,', 'sign=1.0):', 'x', '=', 'd[0]', 'y', '=', 'd[1]', 'dfdx', '=', 'sign', '*', '(-2', '*', 'x', '+', '2', '*', 'y', '+', '2)', 'dfdy', '=', 'sign', '*', '(2', '*', 'x', '-', '4', '*', 'y)', 'return', 'np.array([dfdx,', 'dfdy],', 'float)']
99,826
Abhishekmamidi123/Computer-Vision
flappybird.py
PipePair.top_height_px
top_height_px
Get the top pipe's height, in pixels.
[ "Get", "the", "top", "pipe's", "height,", "in", "pixels." ]
def top_height_px(self): return self.top_pieces * PipePair.PIECE_HEIGHT
['def', 'top_height_px(self):', 'return', 'self.top_pieces', '*', 'PipePair.PIECE_HEIGHT']
468,907
flavioschneider/rl-transfer-
test_npo.py
TestNPO.test_npo_with_max_entropy_and_no_stop_entropy_gradient
test_npo_with_max_entropy_and_no_stop_entropy_gradient
Test NPO with max entropy and false stop_entropy_gradient.
[ "Test", "NPO", "with", "max", "entropy", "and", "false", "stop_entropy_gradient." ]
def test_npo_with_max_entropy_and_no_stop_entropy_gradient(self): with pytest.raises(ValueError): NPO(env_spec=self.env.spec, policy=self.policy, baseline=self.baseline, sampler=self.sampler, entropy_method='max', stop_entropy_gradient=False)
['def', 'test_npo_with_max_entropy_and_no_stop_entropy_gradient(self):', 'with', 'pytest.raises(ValueError):', 'NPO(env_spec=self.env.spec,', 'policy=self.policy,', 'baseline=self.baseline,', 'sampler=self.sampler,', "entropy_method='max',", 'stop_entropy_gradient=False)']
861,748
iffiX/machin
ddpg.py
DDPG.update
update
Update network weights by sampling from replay buffer.
[ "Update", "network", "weights", "by", "sampling", "from", "replay", "buffer." ]
def update(self, update_value=True, update_policy=True, update_target=True, concatenate_samples=True, **__): self.actor.train() self.critic.train() (batch_size, (state, action, reward, next_state, terminal, others)) = self.replay_buffer.sample_batch(self.batch_size, concatenate_samples, sample_method='rando...
['def', 'update(self,', 'update_value=True,', 'update_policy=True,', 'update_target=True,', 'concatenate_samples=True,', '**__):', 'self.actor.train()', 'self.critic.train()', '(batch_size,', '(state,', 'action,', 'reward,', 'next_state,', 'terminal,', 'others))', '=', 'self.replay_buffer.sample_batch(self.batch_size,'...
620,258
Trusted-AI/adversarial-robustness-toolbox
conftest.py
tabular_batch
tabular_batch
Create tabular data fixture of shape (batch_size, features).
[ "Create", "tabular", "data", "fixture", "of", "shape", "(batch_size,", "features)." ]
def tabular_batch(): return (np.zeros((2, 4)), [])
['def', 'tabular_batch():', 'return', '(np.zeros((2,', '4)),', '[])']
398,533
weimin17/Object-Detection_HelmetDetection
models.py
get_model_class
get_model_class
Looks up a model class by name.
[ "Looks", "up", "a", "model", "class", "by", "name." ]
def get_model_class(model_name): if model_name not in _MODELS: raise ValueError('Unrecognized model name: %s' % model_name) return _MODELS[model_name][0]
['def', 'get_model_class(model_name):', 'if', 'model_name', 'not', 'in', '_MODELS:', 'raise', "ValueError('Unrecognized", 'model', 'name:', "%s'", '%', 'model_name)', 'return', '_MODELS[model_name][0]']
761,543
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
visitor.py
Method.acceptFormalParamStdDecl
acceptFormalParamStdDecl
Accept and process a single parameter declaration.
[ "Accept", "and", "process", "a", "single", "parameter", "declaration." ]
def acceptFormalParamStdDecl(self, node, memo): ident = node.firstChildOfType(tokens.IDENT) ptype = self.nodeTypeToString(node) self.parameters.append(self.makeParam(ident.text, ptype)) return self
['def', 'acceptFormalParamStdDecl(self,', 'node,', 'memo):', 'ident', '=', 'node.firstChildOfType(tokens.IDENT)', 'ptype', '=', 'self.nodeTypeToString(node)', 'self.parameters.append(self.makeParam(ident.text,', 'ptype))', 'return', 'self']
11,274
ChenhongyiYang/PGD
detectron2pytorch.py
convert
convert
Convert keys in detectron pretrained ResNet models to pytorch style.
[ "Convert", "keys", "in", "detectron", "pretrained", "ResNet", "models", "to", "pytorch", "style." ]
def convert(src, dst, depth): if depth not in arch_settings: raise ValueError('Only support ResNet-50 and ResNet-101 currently') block_nums = arch_settings[depth] caffe_model = mmcv.load(src, encoding='latin1') blobs = caffe_model['blobs'] if 'blobs' in caffe_model else caffe_model state_dic...
['def', 'convert(src,', 'dst,', 'depth):', 'if', 'depth', 'not', 'in', 'arch_settings:', 'raise', "ValueError('Only", 'support', 'ResNet-50', 'and', 'ResNet-101', "currently')", 'block_nums', '=', 'arch_settings[depth]', 'caffe_model', '=', 'mmcv.load(src,', "encoding='latin1')", 'blobs', '=', "caffe_model['blobs']", '...
768,354
nod-ai/SHARK
utils.py
get_all_devices
get_all_devices
Inputs: driver_name Returns a list of all the available devices for a given driver sorted by the iree path names of the device as in --list_devices option in iree.
[ "Inputs:", "driver_name", "Returns", "a", "list", "of", "all", "the", "available", "devices", "for", "a", "given", "driver", "sorted", "by", "the", "iree", "path", "names", "of", "the", "device", "as", "in", "--list_devices", "option", "in", "iree." ]
def get_all_devices(driver_name): from iree.runtime import get_driver driver = get_driver(driver_name) device_list_src = driver.query_available_devices() device_list_src.sort(key=lambda d: d['path']) return device_list_src
['def', 'get_all_devices(driver_name):', 'from', 'iree.runtime', 'import', 'get_driver', 'driver', '=', 'get_driver(driver_name)', 'device_list_src', '=', 'driver.query_available_devices()', 'device_list_src.sort(key=lambda', 'd:', "d['path'])", 'return', 'device_list_src']
898,978
enuguru/artificial_intelligence_and_machine_
visuals.py
PredictTrials
PredictTrials
Performs trials of fitting and predicting data.
[ "Performs", "trials", "of", "fitting", "and", "predicting", "data." ]
def PredictTrials(X, y, fitter, data): prices = [] for k in range(10): (X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size=0.2, random_state=k) reg = fitter(X_train, y_train) pred = reg.predict([data[0]])[0] prices.append(pred) print('Trial {}: ${:,.2f}'...
['def', 'PredictTrials(X,', 'y,', 'fitter,', 'data):', 'prices', '=', '[]', 'for', 'k', 'in', 'range(10):', '(X_train,', 'X_test,', 'y_train,', 'y_test)', '=', 'train_test_split(X,', 'y,', 'test_size=0.2,', 'random_state=k)', 'reg', '=', 'fitter(X_train,', 'y_train)', 'pred', '=', 'reg.predict([data[0]])[0]', 'prices.a...
164,594
kubeflow/pipelines
_pipeline.py
Pipeline.push_ops_group
push_ops_group
Push an OpsGroup into the stack.
[ "Push", "an", "OpsGroup", "into", "the", "stack." ]
def push_ops_group(self, group: _ops_group.OpsGroup): self.groups[-1].groups.append(group) self.groups.append(group)
['def', 'push_ops_group(self,', 'group:', '_ops_group.OpsGroup):', 'self.groups[-1].groups.append(group)', 'self.groups.append(group)']
780,173
rudranil723/mini-main
data.py
ZipFilePathPointer.entry
entry
The name of the file within zipfile that this path pointer points to.
[ "The", "name", "of", "the", "file", "within", "zipfile", "that", "this", "path", "pointer", "points", "to." ]
def entry(self): return self._entry
['def', 'entry(self):', 'return', 'self._entry']
320,503
weimin17/Object-Detection_HelmetDetection
mst_ops_test.py
MstOpsTest.testLogPartitionFunctionOneTreeScaled
testLogPartitionFunctionOneTreeScaled
Tests the log partition function with one feasible tree.
[ "Tests", "the", "log", "partition", "function", "with", "one", "feasible", "tree." ]
def testLogPartitionFunctionOneTreeScaled(self): with self.test_session(): for forest in [False, True]: pad = 12345.6 scores = tf.constant([[[2, pad, pad], [pad, pad, pad], [pad, pad, pad]], [[3, 0, pad], [5, 0, pad], [pad, pad, pad]], [[7, 0, 0], [11, 0, 0], [0, 13, 0]]], tf.float64...
['def', 'testLogPartitionFunctionOneTreeScaled(self):', 'with', 'self.test_session():', 'for', 'forest', 'in', '[False,', 'True]:', 'pad', '=', '12345.6', 'scores', '=', 'tf.constant([[[2,', 'pad,', 'pad],', '[pad,', 'pad,', 'pad],', '[pad,', 'pad,', 'pad]],', '[[3,', '0,', 'pad],', '[5,', '0,', 'pad],', '[pad,', 'pad,...
753,346
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
dsn.py
add_autoencoders
add_autoencoders
Adds the encoders/decoders for our domain separation model w/ incoherence.
[ "Adds", "the", "encoders/decoders", "for", "our", "domain", "separation", "model", "w/", "incoherence." ]
def add_autoencoders(source_data, source_shared, target_data, target_shared, params): def normalize_images(images): images -= tf.reduce_min(images) return images / tf.reduce_max(images) def concat_operation(shared_repr, private_repr): return shared_repr + private_repr mu = dsn_loss...
['def', 'add_autoencoders(source_data,', 'source_shared,', 'target_data,', 'target_shared,', 'params):', 'def', 'normalize_images(images):', 'images', '-=', 'tf.reduce_min(images)', 'return', 'images', '/', 'tf.reduce_max(images)', 'def', 'concat_operation(shared_repr,', 'private_repr):', 'return', 'shared_repr', '+', ...
47,937
HuiGuanLab/HiCo
builder.py
get_sampler
get_sampler
Returns the sampler object for the dataset.
[ "Returns", "the", "sampler", "object", "for", "the", "dataset." ]
def get_sampler(cfg, dataset, split, shuffle): if misc.get_num_gpus(cfg) > 1: if split == 'train' and cfg.TRAIN.NUM_FOLDS > 1: return MultiFoldDistributedSampler(dataset, cfg.TRAIN.NUM_FOLDS) elif cfg.USE_MULTISEG_VAL_DIST and cfg.TRAIN.ENABLE is False: return MultiSegValDist...
['def', 'get_sampler(cfg,', 'dataset,', 'split,', 'shuffle):', 'if', 'misc.get_num_gpus(cfg)', '>', '1:', 'if', 'split', '==', "'train'", 'and', 'cfg.TRAIN.NUM_FOLDS', '>', '1:', 'return', 'MultiFoldDistributedSampler(dataset,', 'cfg.TRAIN.NUM_FOLDS)', 'elif', 'cfg.USE_MULTISEG_VAL_DIST', 'and', 'cfg.TRAIN.ENABLE', 'is...
206,038
openvinotoolkit/training_extensions
storage_cache.py
arrow_cache_helper
arrow_cache_helper
A helper for dumping Datumaro arrow format.
[ "A", "helper", "for", "dumping", "Datumaro", "arrow", "format." ]
def arrow_cache_helper(dataset: DatumDataset, scheme: str, num_workers: int=0, cache_dir: str=DATASET_CACHE, force: bool=False) -> List[str]: def get_hash(dataset, scheme): source_path = dataset.data_path _hash = hashlib.sha256() _hash.update(f'{source_path}'.encode('utf-8')) _hash....
['def', 'arrow_cache_helper(dataset:', 'DatumDataset,', 'scheme:', 'str,', 'num_workers:', 'int=0,', 'cache_dir:', 'str=DATASET_CACHE,', 'force:', 'bool=False)', '->', 'List[str]:', 'def', 'get_hash(dataset,', 'scheme):', 'source_path', '=', 'dataset.data_path', '_hash', '=', 'hashlib.sha256()', "_hash.update(f'{source...
919,054
aisingapore/PeekingDuck
preprocess.py
mirror
mirror
Mirrors a video frame.
[ "Mirrors", "a", "video", "frame." ]
def mirror(frame: np.ndarray) -> np.ndarray: return cv2.flip(frame, 1)
['def', 'mirror(frame:', 'np.ndarray)', '->', 'np.ndarray:', 'return', 'cv2.flip(frame,', '1)']
766,870
greydanus/mr_london
OleFileIO.py
OleFileIO.loadfat_sect
loadfat_sect
Adds the indexes of the given sector to the FAT :param sect: string containing the first FAT sector, or array of long integers :returns: index of last FAT sector.
[ "Adds", "the", "indexes", "of", "the", "given", "sector", "to", "the", "FAT", ":param", "sect:", "string", "containing", "the", "first", "FAT", "sector,", "or", "array", "of", "long", "integers", ":returns:", "index", "of", "last", "FAT", "sector." ]
def loadfat_sect(self, sect): if isinstance(sect, array.array): fat1 = sect else: fat1 = self.sect2array(sect) self.dumpsect(sect) for isect in fat1: isect = isect & 4294967295 debug('isect = %X' % isect) if isect == ENDOFCHAIN or isect == FREESECT: ...
['def', 'loadfat_sect(self,', 'sect):', 'if', 'isinstance(sect,', 'array.array):', 'fat1', '=', 'sect', 'else:', 'fat1', '=', 'self.sect2array(sect)', 'self.dumpsect(sect)', 'for', 'isect', 'in', 'fat1:', 'isect', '=', 'isect', '&', '4294967295', "debug('isect", '=', "%X'", '%', 'isect)', 'if', 'isect', '==', 'ENDOFCHA...
263,270
weimin17/Object-Detection_HelmetDetection
misc.py
bf_int2char
bf_int2char
Convert BF int token to code char.
[ "Convert", "BF", "int", "token", "to", "code", "char." ]
def bf_int2char(bf_int): return BF_INT_TO_CHAR[bf_int]
['def', 'bf_int2char(bf_int):', 'return', 'BF_INT_TO_CHAR[bf_int]']
761,942
saibash/region_base_semantic_segmentation
tf_util.py
knn
knn
Get KNN based on the pairwise distance.
[ "Get", "KNN", "based", "on", "the", "pairwise", "distance." ]
def knn(adj_matrix, k=20): neg_adj = -adj_matrix (_, nn_idx) = tf.nn.top_k(neg_adj, k=k) return nn_idx
['def', 'knn(adj_matrix,', 'k=20):', 'neg_adj', '=', '-adj_matrix', '(_,', 'nn_idx)', '=', 'tf.nn.top_k(neg_adj,', 'k=k)', 'return', 'nn_idx']
832,890
chribsen/simple-machine-learning-examples
update_checker.py
pretty_date
pretty_date
Attempt to return a human-readable time delta string.
[ "Attempt", "to", "return", "a", "human-readable", "time", "delta", "string." ]
def pretty_date(the_datetime): diff = datetime.utcnow() - the_datetime if diff.days > 7 or diff.days < 0: return the_datetime.strftime('%A %B %d, %Y') elif diff.days == 1: return '1 day ago' elif diff.days > 1: return '{0} days ago'.format(diff.days) elif diff.seconds <= 1: ...
['def', 'pretty_date(the_datetime):', 'diff', '=', 'datetime.utcnow()', '-', 'the_datetime', 'if', 'diff.days', '>', '7', 'or', 'diff.days', '<', '0:', 'return', "the_datetime.strftime('%A", '%B', '%d,', "%Y')", 'elif', 'diff.days', '==', '1:', 'return', "'1", 'day', "ago'", 'elif', 'diff.days', '>', '1:', 'return', "'...
934,921
usmancheema89/computer_vision
multitracker.py
STrack.tlwh_to_xyah
tlwh_to_xyah
Convert bounding box to format `(center x, center y, aspect ratio, height)`, where the aspect ratio is `width / height`.
[ "Convert", "bounding", "box", "to", "format", "`(center", "x,", "center", "y,", "aspect", "ratio,", "height)`,", "where", "the", "aspect", "ratio", "is", "`width", "/", "height`." ]
def tlwh_to_xyah(tlwh): ret = np.asarray(tlwh).copy() ret[:2] += ret[2:] / 2 ret[2] /= ret[3] return ret
['def', 'tlwh_to_xyah(tlwh):', 'ret', '=', 'np.asarray(tlwh).copy()', 'ret[:2]', '+=', 'ret[2:]', '/', '2', 'ret[2]', '/=', 'ret[3]', 'return', 'ret']
476,362
ArdaGunay99/Key_Detection_Unsupervised_Learning
autodist.py
check_gcc_function_attribute
check_gcc_function_attribute
Return True if the given function attribute is supported.
[ "Return", "True", "if", "the", "given", "function", "attribute", "is", "supported." ]
def check_gcc_function_attribute(cmd, attribute, name): cmd._check_compiler() body = textwrap.dedent('\n #pragma GCC diagnostic error "-Wattributes"\n #pragma clang diagnostic error "-Wattributes"\n\n int %s %s(void*);\n\n int\n main()\n {\n return 0;\n ...
['def', 'check_gcc_function_attribute(cmd,', 'attribute,', 'name):', 'cmd._check_compiler()', 'body', '=', "textwrap.dedent('\\n", '#pragma', 'GCC', 'diagnostic', 'error', '"-Wattributes"\\n', '#pragma', 'clang', 'diagnostic', 'error', '"-Wattributes"\\n\\n', 'int', '%s', '%s(void*);\\n\\n', 'int\\n', 'main()\\n', '{\\...
258,456
chncyhn/flappybird-qlearning-bot
learn.py
checkCrash
checkCrash
returns True if player collders with base or pipes.
[ "returns", "True", "if", "player", "collders", "with", "base", "or", "pipes." ]
def checkCrash(player, upperPipes, lowerPipes): pi = player['index'] player['w'] = PLAYER[IM_WIDTH] player['h'] = PLAYER[IM_HEIGTH] if player['y'] + player['h'] >= BASEY - 1 or player['y'] + player['h'] <= 0: return [True, True] else: playerRect = pygame.Rect(player['x'], player['y']...
['def', 'checkCrash(player,', 'upperPipes,', 'lowerPipes):', 'pi', '=', "player['index']", "player['w']", '=', 'PLAYER[IM_WIDTH]', "player['h']", '=', 'PLAYER[IM_HEIGTH]', 'if', "player['y']", '+', "player['h']", '>=', 'BASEY', '-', '1', 'or', "player['y']", '+', "player['h']", '<=', '0:', 'return', '[True,', 'True]', ...
211,150
bobwan1995/PMFNet
mask_rcnn_heads.py
mask_rcnn_fcn_head_v1up
mask_rcnn_fcn_head_v1up
v1up design: 2 * (conv 3x3), convT 2x2.
[ "v1up", "design:", "2", "*", "(conv", "3x3),", "convT", "2x2." ]
def mask_rcnn_fcn_head_v1up(dim_in, roi_xform_func, spatial_scale): return mask_rcnn_fcn_head_v1upXconvs(dim_in, roi_xform_func, spatial_scale, 2)
['def', 'mask_rcnn_fcn_head_v1up(dim_in,', 'roi_xform_func,', 'spatial_scale):', 'return', 'mask_rcnn_fcn_head_v1upXconvs(dim_in,', 'roi_xform_func,', 'spatial_scale,', '2)']
780,663
dvlab-research/FocalsConv
fastai_optim.py
master2model
master2model
Copy `master_params` to `model_params`.
[ "Copy", "`master_params`", "to", "`model_params`." ]
def master2model(model_params, master_params, flat_master: bool=False) -> None: if flat_master: for (model_group, master_group) in zip(model_params, master_params): if len(model_group) != 0: for (model, master) in zip(model_group, _unflatten_dense_tensors(master_group[0].data, mo...
['def', 'master2model(model_params,', 'master_params,', 'flat_master:', 'bool=False)', '->', 'None:', 'if', 'flat_master:', 'for', '(model_group,', 'master_group)', 'in', 'zip(model_params,', 'master_params):', 'if', 'len(model_group)', '!=', '0:', 'for', '(model,', 'master)', 'in', 'zip(model_group,', '_unflatten_dens...
608,315
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
seq2seq_attention_model.py
Seq2SeqAttentionModel.encode_top_state
encode_top_state
Return the top states from encoder for decoder.
[ "Return", "the", "top", "states", "from", "encoder", "for", "decoder." ]
def encode_top_state(self, sess, enc_inputs, enc_len): results = sess.run([self._enc_top_states, self._dec_in_state], feed_dict={self._articles: enc_inputs, self._article_lens: enc_len}) return (results[0], results[1][0])
['def', 'encode_top_state(self,', 'sess,', 'enc_inputs,', 'enc_len):', 'results', '=', 'sess.run([self._enc_top_states,', 'self._dec_in_state],', 'feed_dict={self._articles:', 'enc_inputs,', 'self._article_lens:', 'enc_len})', 'return', '(results[0],', 'results[1][0])']
112,751
drprojects/superpoint_transformer
utils.py
save_file
save_file
Save file in rank zero mode (only on one process in multi-GPU setup).
[ "Save", "file", "in", "rank", "zero", "mode", "(only", "on", "one", "process", "in", "multi-GPU", "setup)." ]
def save_file(path: str, content: str) -> None: with open(path, 'w+') as file: file.write(content)
['def', 'save_file(path:', 'str,', 'content:', 'str)', '->', 'None:', 'with', 'open(path,', "'w+')", 'as', 'file:', 'file.write(content)']
880,961
intel/neural-compressor
tuning_space.py
initial_tuning_cfg_with_quant_mode
initial_tuning_cfg_with_quant_mode
Initialize the tuning cfg.
[ "Initialize", "the", "tuning", "cfg." ]
def initial_tuning_cfg_with_quant_mode(op_name_type, quant_mode, tuning_space: TuningSpace) -> OpTuningConfig: internal_pattern = pattern_to_internal(quant_mode) full_path = {'activation': None, 'weight': None} (full_path['activation'], full_path['weight']) = pattern_to_path(internal_pattern) has_weight...
['def', 'initial_tuning_cfg_with_quant_mode(op_name_type,', 'quant_mode,', 'tuning_space:', 'TuningSpace)', '->', 'OpTuningConfig:', 'internal_pattern', '=', 'pattern_to_internal(quant_mode)', 'full_path', '=', "{'activation':", 'None,', "'weight':", 'None}', "(full_path['activation'],", "full_path['weight'])", '=', 'p...
721,433
microsoft/maro
proxy.py
Proxy.receive
receive
Enter an infinite loop of receiving messages from the communication driver.
[ "Enter", "an", "infinite", "loop", "of", "receiving", "messages", "from", "the", "communication", "driver." ]
def receive(self, timeout: int=None): return self._driver.receive(timeout=timeout)
['def', 'receive(self,', 'timeout:', 'int=None):', 'return', 'self._driver.receive(timeout=timeout)']
628,353
IBM/vsrl-framework
env.py
Env.current_raw_state
current_raw_state
Returns uint8 array with dimensions HWC.
[ "Returns", "uint8", "array", "with", "dimensions", "HWC." ]
def current_raw_state(self) -> np.ndarray: img = np.array(self.render()) return img.reshape(self._height, self._width, -1)
['def', 'current_raw_state(self)', '->', 'np.ndarray:', 'img', '=', 'np.array(self.render())', 'return', 'img.reshape(self._height,', 'self._width,', '-1)']
940,101
nilearn/nilearn
test_displays.py
test_demo_mosaic_slicer
test_demo_mosaic_slicer
Tests for MosaicSlicer with different cut_coords in constructor.
[ "Tests", "for", "MosaicSlicer", "with", "different", "cut_coords", "in", "constructor." ]
def test_demo_mosaic_slicer(cut_coords, img, expected_cuts): slicer = MosaicSlicer(cut_coords=cut_coords) slicer.add_overlay(img, cmap=plt.cm.gray) assert slicer.cut_coords == expected_cuts slicer.close()
['def', 'test_demo_mosaic_slicer(cut_coords,', 'img,', 'expected_cuts):', 'slicer', '=', 'MosaicSlicer(cut_coords=cut_coords)', 'slicer.add_overlay(img,', 'cmap=plt.cm.gray)', 'assert', 'slicer.cut_coords', '==', 'expected_cuts', 'slicer.close()']
724,109
Trusted-AI/AIF360
test_metrics.py
test_smoothed_edf
test_smoothed_edf
Tests that the old and new smoothed_edf matches exactly.
[ "Tests", "that", "the", "old", "and", "new", "smoothed_edf", "matches", "exactly." ]
def test_smoothed_edf(): edf = smoothed_edf(y, sample_weight=sample_weight) assert edf == cm.smoothed_empirical_differential_fairness() edf = smoothed_edf(y, concentration=1000000000.0, sample_weight=sample_weight) assert edf == cm.smoothed_empirical_differential_fairness(1000000000.0)
['def', 'test_smoothed_edf():', 'edf', '=', 'smoothed_edf(y,', 'sample_weight=sample_weight)', 'assert', 'edf', '==', 'cm.smoothed_empirical_differential_fairness()', 'edf', '=', 'smoothed_edf(y,', 'concentration=1000000000.0,', 'sample_weight=sample_weight)', 'assert', 'edf', '==', 'cm.smoothed_empirical_differential_...
412,548
researchmm/WSOD2
mean_ap.py
get_cls_results
get_cls_results
Get det results and gt information of a certain class.
[ "Get", "det", "results", "and", "gt", "information", "of", "a", "certain", "class." ]
def get_cls_results(det_results, annotations, class_id): cls_dets = [img_res[class_id] for img_res in det_results] cls_gts = [] cls_gts_ignore = [] for ann in annotations: gt_inds = ann['labels'] == class_id cls_gts.append(ann['bboxes'][gt_inds, :]) if ann.get('labels_ignore', No...
['def', 'get_cls_results(det_results,', 'annotations,', 'class_id):', 'cls_dets', '=', '[img_res[class_id]', 'for', 'img_res', 'in', 'det_results]', 'cls_gts', '=', '[]', 'cls_gts_ignore', '=', '[]', 'for', 'ann', 'in', 'annotations:', 'gt_inds', '=', "ann['labels']", '==', 'class_id', "cls_gts.append(ann['bboxes'][gt_...
374,045
huawei-noah/xingtian
mindspore_fn.py
concat
concat
Call concat according to backends.
[ "Call", "concat", "according", "to", "backends." ]
def concat(inputs, dim=1): return P.Concat(dim)(inputs)
['def', 'concat(inputs,', 'dim=1):', 'return', 'P.Concat(dim)(inputs)']
962,740
ifwe/digsby
infobox.py
InfoBox.maybe_notify_twitter
maybe_notify_twitter
use a timer to only notify the twitter infobox stat AFTER it has been open for more than the double click time, so that we don't count double clicks opening the main feed window.
[ "use", "a", "timer", "to", "only", "notify", "the", "twitter", "infobox", "stat", "AFTER", "it", "has", "been", "open", "for", "more", "than", "the", "double", "click", "time,", "so", "that", "we", "don't", "count", "double", "clicks", "opening", "the", ...
def maybe_notify_twitter(self): if getattr(self.account, 'protocol', None) != 'twitter': return def later(): if self.IsShown(): hooks.notify('digsby.statistics.twitter.infobox.shown') try: timer = self._dclick_timer except AttributeError: timer = self._dclick...
['def', 'maybe_notify_twitter(self):', 'if', 'getattr(self.account,', "'protocol',", 'None)', '!=', "'twitter':", 'return', 'def', 'later():', 'if', 'self.IsShown():', "hooks.notify('digsby.statistics.twitter.infobox.shown')", 'try:', 'timer', '=', 'self._dclick_timer', 'except', 'AttributeError:', 'timer', '=', 'self....
185,484
open-mmlab/mmrotate
oriented_reppoints_head.py
OrientedRepPointsHead.get_adaptive_points_feature
get_adaptive_points_feature
Get the points features from the locations of predicted points.
[ "Get", "the", "points", "features", "from", "the", "locations", "of", "predicted", "points." ]
def get_adaptive_points_feature(self, features, pt_locations, stride): h = features.shape[2] * stride w = features.shape[3] * stride pt_locations = pt_locations.view(pt_locations.shape[0], pt_locations.shape[1], -1, 2).clone() pt_locations[..., 0] = pt_locations[..., 0] / (w / 2.0) - 1 pt_locations[...
['def', 'get_adaptive_points_feature(self,', 'features,', 'pt_locations,', 'stride):', 'h', '=', 'features.shape[2]', '*', 'stride', 'w', '=', 'features.shape[3]', '*', 'stride', 'pt_locations', '=', 'pt_locations.view(pt_locations.shape[0],', 'pt_locations.shape[1],', '-1,', '2).clone()', 'pt_locations[...,', '0]', '=...
625,118
andrewekhalel/edafa
nasnet.py
nasnet_large_arg_scope
nasnet_large_arg_scope
Defines the default arg scope for the NASNet-A Large ImageNet model.
[ "Defines", "the", "default", "arg", "scope", "for", "the", "NASNet-A", "Large", "ImageNet", "model." ]
def nasnet_large_arg_scope(weight_decay=5e-05, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): batch_norm_params = {'decay': batch_norm_decay, 'epsilon': batch_norm_epsilon, 'scale': True, 'fused': True} weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay) weights_initializer = tf.contri...
['def', 'nasnet_large_arg_scope(weight_decay=5e-05,', 'batch_norm_decay=0.9997,', 'batch_norm_epsilon=0.001):', 'batch_norm_params', '=', "{'decay':", 'batch_norm_decay,', "'epsilon':", 'batch_norm_epsilon,', "'scale':", 'True,', "'fused':", 'True}', 'weights_regularizer', '=', 'tf.contrib.layers.l2_regularizer(weight_...
548,072
lixingjian/DELTA
solver_utils.py
save_infer_res
save_infer_res
Save the result of inference.
[ "Save", "the", "result", "of", "inference." ]
def save_infer_res(config, logits, preds): res_file = config['data']['infer']['res'] res_dir = os.path.dirname(res_file) if not os.path.exists(res_dir): os.makedirs(res_dir) logging.info('Save inference result to: {}'.format(res_file)) with open(res_file, 'w') as in_f: for (logit, pr...
['def', 'save_infer_res(config,', 'logits,', 'preds):', 'res_file', '=', "config['data']['infer']['res']", 'res_dir', '=', 'os.path.dirname(res_file)', 'if', 'not', 'os.path.exists(res_dir):', 'os.makedirs(res_dir)', "logging.info('Save", 'inference', 'result', 'to:', "{}'.format(res_file))", 'with', 'open(res_file,', ...
537,725
TrellixVulnTeam/Unsupervised_Learning_HFI7
handlers.py
ContentsHandler.patch
patch
PATCH renames a file or directory without re-uploading content.
[ "PATCH", "renames", "a", "file", "or", "directory", "without", "re-uploading", "content." ]
def patch(self, path=''): cm = self.contents_manager model = self.get_json_body() if model is None: raise web.HTTPError(400, u'JSON body missing') model = (yield maybe_future(cm.update(model, path))) validate_model(model, expect_content=False) self._finish_model(model)
['def', 'patch(self,', "path=''):", 'cm', '=', 'self.contents_manager', 'model', '=', 'self.get_json_body()', 'if', 'model', 'is', 'None:', 'raise', 'web.HTTPError(400,', "u'JSON", 'body', "missing')", 'model', '=', '(yield', 'maybe_future(cm.update(model,', 'path)))', 'validate_model(model,', 'expect_content=False)', ...
452,253
AlibabaResearch/efficientteacher
torch_utils.py
torch_distributed_zero_first
torch_distributed_zero_first
Decorator to make all processes in distributed training wait for each local_master to do something.
[ "Decorator", "to", "make", "all", "processes", "in", "distributed", "training", "wait", "for", "each", "local_master", "to", "do", "something." ]
def torch_distributed_zero_first(local_rank: int): if local_rank not in [-1, 0]: dist.barrier(device_ids=[local_rank]) yield if local_rank == 0: dist.barrier(device_ids=[0])
['def', 'torch_distributed_zero_first(local_rank:', 'int):', 'if', 'local_rank', 'not', 'in', '[-1,', '0]:', 'dist.barrier(device_ids=[local_rank])', 'yield', 'if', 'local_rank', '==', '0:', 'dist.barrier(device_ids=[0])']
561,058
rudranil723/mini-main
grammar.py
sdg_demo
sdg_demo
A demonstration of how to read a string representation of a CoNLL format dependency tree.
[ "A", "demonstration", "of", "how", "to", "read", "a", "string", "representation", "of", "a", "CoNLL", "format", "dependency", "tree." ]
def sdg_demo(): from nltk.parse import DependencyGraph dg = DependencyGraph('\n 1 Ze ze Pron Pron per|3|evofmv|nom 2 su _ _\n 2 had heb V V trans|ovt|1of2of3|ev 0 ROOT _ _\n 3 met ...
['def', 'sdg_demo():', 'from', 'nltk.parse', 'import', 'DependencyGraph', 'dg', '=', "DependencyGraph('\\n", '1', 'Ze', 'ze', 'Pron', 'Pron', 'per|3|evofmv|nom', '2', 'su', '_', '_\\n', '2', 'had', 'heb', 'V', 'V', 'trans|ovt|1of2of3|ev', '0', 'ROOT', '_', '_\\n', '3', 'met', 'met', 'Prep', 'Prep', 'voor', '8', 'mod', ...
320,562
flyteorg/flytelab
extractor.py
WikiExtractor.extract_content
extract_content
Retrieve formatted (clean) text from Wikipedia.
[ "Retrieve", "formatted", "(clean)", "text", "from", "Wikipedia." ]
def extract_content(self, page: str, summary: bool, sections: List[str]=None, sections_tags: Dict[str, List[str]]=None, section_types: Dict[str, str]=None) -> Dict[str, str]: sections = sections or [] results = self.extract_content_raw(page, summary, sections) sections_tags = {section: sections_tags.get(sec...
['def', 'extract_content(self,', 'page:', 'str,', 'summary:', 'bool,', 'sections:', 'List[str]=None,', 'sections_tags:', 'Dict[str,', 'List[str]]=None,', 'section_types:', 'Dict[str,', 'str]=None)', '->', 'Dict[str,', 'str]:', 'sections', '=', 'sections', 'or', '[]', 'results', '=', 'self.extract_content_raw(page,', 's...
606,982
zhang614/MicroGrid
loader.py
have_avbin
have_avbin
Returns ``True`` iff AVBin is installed and accessible on the user's system.
[ "Returns", "``True``", "iff", "AVBin", "is", "installed", "and", "accessible", "on", "the", "user's", "system." ]
def have_avbin(): global _have_avbin if _have_avbin is None: try: from .avbin import AVbinSource _have_avbin = True except ImportError: _have_avbin = False return _have_avbin
['def', 'have_avbin():', 'global', '_have_avbin', 'if', '_have_avbin', 'is', 'None:', 'try:', 'from', '.avbin', 'import', 'AVbinSource', '_have_avbin', '=', 'True', 'except', 'ImportError:', '_have_avbin', '=', 'False', 'return', '_have_avbin']
668,862
QData/deepWordBug
math2html.py
Container.escapeall
escapeall
Escape all lines in an array according to the output options.
[ "Escape", "all", "lines", "in", "an", "array", "according", "to", "the", "output", "options." ]
def escapeall(self, lines): result = [] for line in lines: if Options.html: line = self.escape(line, EscapeConfig.html) if Options.iso885915: line = self.escape(line, EscapeConfig.iso885915) line = self.escapeentities(line) elif not Options.str: ...
['def', 'escapeall(self,', 'lines):', 'result', '=', '[]', 'for', 'line', 'in', 'lines:', 'if', 'Options.html:', 'line', '=', 'self.escape(line,', 'EscapeConfig.html)', 'if', 'Options.iso885915:', 'line', '=', 'self.escape(line,', 'EscapeConfig.iso885915)', 'line', '=', 'self.escapeentities(line)', 'elif', 'not', 'Opti...
542,421
ballaneypranav/cs50ai
degrees.py
person_id_for_name
person_id_for_name
Returns the IMDB id for a person's name, resolving ambiguities as needed.
[ "Returns", "the", "IMDB", "id", "for", "a", "person's", "name,", "resolving", "ambiguities", "as", "needed." ]
def person_id_for_name(name): person_ids = list(names.get(name.lower(), set())) if len(person_ids) == 0: return None elif len(person_ids) > 1: print(f"Which '{name}'?") for person_id in person_ids: person = people[person_id] name = person['name'] b...
['def', 'person_id_for_name(name):', 'person_ids', '=', 'list(names.get(name.lower(),', 'set()))', 'if', 'len(person_ids)', '==', '0:', 'return', 'None', 'elif', 'len(person_ids)', '>', '1:', 'print(f"Which', '\'{name}\'?")', 'for', 'person_id', 'in', 'person_ids:', 'person', '=', 'people[person_id]', 'name', '=', "per...
192,119
sulc/tfrecord-viewer
classification_overlay.py
ClassificationOverlay.apply_overlay
apply_overlay
Apply annotation overlay over input image.
[ "Apply", "annotation", "overlay", "over", "input", "image." ]
def apply_overlay(self, image_bytes, example): img = Image.open(io.BytesIO(image_bytes)) draw = ImageDraw.Draw(img) class_label = self.get_label(example.features.feature) (w, h) = self.font.getsize(class_label) draw.rectangle((10, 10, 14 + w, 10 + h), fill='white') draw.text((10, 10), class_labe...
['def', 'apply_overlay(self,', 'image_bytes,', 'example):', 'img', '=', 'Image.open(io.BytesIO(image_bytes))', 'draw', '=', 'ImageDraw.Draw(img)', 'class_label', '=', 'self.get_label(example.features.feature)', '(w,', 'h)', '=', 'self.font.getsize(class_label)', 'draw.rectangle((10,', '10,', '14', '+', 'w,', '10', '+',...
915,779
LucasAlegre/morl-baselines
diverse_buffer.py
DiverseMemory.remove_trace
remove_trace
Removes the trace from the main memory.
[ "Removes", "the", "trace", "from", "the", "main", "memory." ]
def remove_trace(self, trace): (_, trace_idx) = trace for i in trace_idx: self.tree.data[i] = (None, None, None) idx = i + self.tree.capacity - 1 for tree in self.tree.trees: self.tree.update(idx, 0, tree)
['def', 'remove_trace(self,', 'trace):', '(_,', 'trace_idx)', '=', 'trace', 'for', 'i', 'in', 'trace_idx:', 'self.tree.data[i]', '=', '(None,', 'None,', 'None)', 'idx', '=', 'i', '+', 'self.tree.capacity', '-', '1', 'for', 'tree', 'in', 'self.tree.trees:', 'self.tree.update(idx,', '0,', 'tree)']
655,786
jimtin/Stock_Comparison
shimmodule.py
ShimImporter.find_module
find_module
Return self if we should be used to import the module.
[ "Return", "self", "if", "we", "should", "be", "used", "to", "import", "the", "module." ]
def find_module(self, fullname, path=None): if fullname.startswith(self.src + '.'): mirror_name = self._mirror_name(fullname) try: mod = import_item(mirror_name) except ImportError: return else: if not isinstance(mod, types.ModuleType): ...
['def', 'find_module(self,', 'fullname,', 'path=None):', 'if', 'fullname.startswith(self.src', '+', "'.'):", 'mirror_name', '=', 'self._mirror_name(fullname)', 'try:', 'mod', '=', 'import_item(mirror_name)', 'except', 'ImportError:', 'return', 'else:', 'if', 'not', 'isinstance(mod,', 'types.ModuleType):', 'return', 'No...
385,500
TJU-DRL-LAB/AI-Optimizer
self_play.py
Node.add_exploration_noise
add_exploration_noise
At the start of each search, we add dirichlet noise to the prior of the root to encourage the search to explore new actions.
[ "At", "the", "start", "of", "each", "search,", "we", "add", "dirichlet", "noise", "to", "the", "prior", "of", "the", "root", "to", "encourage", "the", "search", "to", "explore", "new", "actions." ]
def add_exploration_noise(self, dirichlet_alpha, exploration_fraction): actions = list(self.children.keys()) noise = numpy.random.dirichlet([dirichlet_alpha] * len(actions)) frac = exploration_fraction for (a, n) in zip(actions, noise): self.children[a].prior = self.children[a].prior * (1 - frac...
['def', 'add_exploration_noise(self,', 'dirichlet_alpha,', 'exploration_fraction):', 'actions', '=', 'list(self.children.keys())', 'noise', '=', 'numpy.random.dirichlet([dirichlet_alpha]', '*', 'len(actions))', 'frac', '=', 'exploration_fraction', 'for', '(a,', 'n)', 'in', 'zip(actions,', 'noise):', 'self.children[a].p...
70,381
RLE-Foundation/rllte
performance.py
Performance.create_performance_profile
create_performance_profile
Method for calculating performance profilies.
[ "Method", "for", "calculating", "performance", "profilies." ]
def create_performance_profile(self, tau_list: Union[List[float], np.ndarray], use_score_distribution: bool=True) -> Tuple[np.ndarray, np.ndarray]: if use_score_distribution: def _thunk(scores, tau): return np.mean(scores > tau) else: def _thunk(scores, tau): return np....
['def', 'create_performance_profile(self,', 'tau_list:', 'Union[List[float],', 'np.ndarray],', 'use_score_distribution:', 'bool=True)', '->', 'Tuple[np.ndarray,', 'np.ndarray]:', 'if', 'use_score_distribution:', 'def', '_thunk(scores,', 'tau):', 'return', 'np.mean(scores', '>', 'tau)', 'else:', 'def', '_thunk(scores,',...
333,559
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
server.py
BaseHTTPRequestHandler.address_string
address_string
Return the client address.
[ "Return", "the", "client", "address." ]
def address_string(self): return self.client_address[0]
['def', 'address_string(self):', 'return', 'self.client_address[0]']
430,740