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
5taku/tensorflow_object_detection_helper_tool
metrics.py
compute_recall_at_k
compute_recall_at_k
Computes Recall@k, MedianRank@k, where k is the top-scoring labels.
[ "Computes", "Recall@k,", "MedianRank@k,", "where", "k", "is", "the", "top-scoring", "labels." ]
def compute_recall_at_k(tp_fp_list, num_gt, k): tp_fp_eval = [] for i in range(len(tp_fp_list)): tp_fp_eval.append(tp_fp_list[i][0:min(k, tp_fp_list[i].shape[0])]) tp_fp_eval = np.concatenate(tp_fp_eval) return np.sum(tp_fp_eval) / num_gt
['def', 'compute_recall_at_k(tp_fp_list,', 'num_gt,', 'k):', 'tp_fp_eval', '=', '[]', 'for', 'i', 'in', 'range(len(tp_fp_list)):', 'tp_fp_eval.append(tp_fp_list[i][0:min(k,', 'tp_fp_list[i].shape[0])])', 'tp_fp_eval', '=', 'np.concatenate(tp_fp_eval)', 'return', 'np.sum(tp_fp_eval)', '/', 'num_gt']
923,220
HuiGuanLab/HiCo
meters.py
ValMeter.update_predictions
update_predictions
Update predictions and labels.
[ "Update", "predictions", "and", "labels." ]
def update_predictions(self, preds, labels): self.all_preds.append(preds) self.all_labels.append(labels)
['def', 'update_predictions(self,', 'preds,', 'labels):', 'self.all_preds.append(preds)', 'self.all_labels.append(labels)']
206,257
weimin17/Object-Detection_HelmetDetection
neural_bandit_model.py
NeuralBanditModel.create_summaries
create_summaries
Defines summaries including mean loss, learning rate, and global step.
[ "Defines", "summaries", "including", "mean", "loss,", "learning", "rate,", "and", "global", "step." ]
def create_summaries(self): with self.graph.as_default(): with tf.name_scope(self.name + '_summaries'): tf.summary.scalar('cost', self.cost) tf.summary.scalar('lr', self.lr) tf.summary.scalar('global_step', self.global_step) self.summary_op = tf.summary.merge_...
['def', 'create_summaries(self):', 'with', 'self.graph.as_default():', 'with', 'tf.name_scope(self.name', '+', "'_summaries'):", "tf.summary.scalar('cost',", 'self.cost)', "tf.summary.scalar('lr',", 'self.lr)', "tf.summary.scalar('global_step',", 'self.global_step)', 'self.summary_op', '=', 'tf.summary.merge_all()']
762,281
Bismarrck/kcon
transformer.py
MultiTransformer.include_all_k
include_all_k
Return True if a standalone two-body term is included.
[ "Return", "True", "if", "a", "standalone", "two-body", "term", "is", "included." ]
def include_all_k(self): return self._include_all_k
['def', 'include_all_k(self):', 'return', 'self._include_all_k']
247,597
NoGameNoLife00/mybolg
filters.py
do_lower
do_lower
Convert a value to lowercase.
[ "Convert", "a", "value", "to", "lowercase." ]
def do_lower(s): return soft_unicode(s).lower()
['def', 'do_lower(s):', 'return', 'soft_unicode(s).lower()']
289,500
deepmind/meltingpot
prisoners_dilemma_in_the_matrix__repeated.py
create_prefabs
create_prefabs
Returns a dictionary mapping names to template game objects.
[ "Returns", "a", "dictionary", "mapping", "names", "to", "template", "game", "objects." ]
def create_prefabs(): prefabs = {'wall': WALL, 'spawn_point': SPAWN_POINT} prefabs['resource_class1'] = create_resource_prefab(1, shapes.BUTTON, {'*': RESOURCE1_COLOR_DATA[0], '#': RESOURCE1_COLOR_DATA[1], 'x': (0, 0, 0, 0)}) prefabs['resource_class2'] = create_resource_prefab(2, shapes.BUTTON, {'*': RESOUR...
['def', 'create_prefabs():', 'prefabs', '=', "{'wall':", 'WALL,', "'spawn_point':", 'SPAWN_POINT}', "prefabs['resource_class1']", '=', 'create_resource_prefab(1,', 'shapes.BUTTON,', "{'*':", 'RESOURCE1_COLOR_DATA[0],', "'#':", 'RESOURCE1_COLOR_DATA[1],', "'x':", '(0,', '0,', '0,', '0)})', "prefabs['resource_class2']", ...
285,795
matsu0228/nlp-jp
styles.py
hex_to_rgb
hex_to_rgb
Convert a hex color to rgb integer tuple.
[ "Convert", "a", "hex", "color", "to", "rgb", "integer", "tuple." ]
def hex_to_rgb(color): if color.startswith('#'): color = color[1:] if len(color) == 3: color = ''.join([c * 2 for c in color]) if len(color) != 6: return False try: r = int(color[:2], 16) g = int(color[2:4], 16) b = int(color[4:], 16) except ValueError...
['def', 'hex_to_rgb(color):', 'if', "color.startswith('#'):", 'color', '=', 'color[1:]', 'if', 'len(color)', '==', '3:', 'color', '=', "''.join([c", '*', '2', 'for', 'c', 'in', 'color])', 'if', 'len(color)', '!=', '6:', 'return', 'False', 'try:', 'r', '=', 'int(color[:2],', '16)', 'g', '=', 'int(color[2:4],', '16)', 'b...
805,262
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
utils.py
BuildNetwork
BuildNetwork
Build a network using the given parameters.
[ "Build", "a", "network", "using", "the", "given", "parameters." ]
def BuildNetwork(inputs, network_parameters): training_parameters = {} num_inputs = network_parameters.input_size outputs = inputs projection = None for conv_param in network_parameters.conv_parameters: outputs = tf.reshape(outputs, [-1, conv_param.in_size, conv_param.in_size, conv_param.in_...
['def', 'BuildNetwork(inputs,', 'network_parameters):', 'training_parameters', '=', '{}', 'num_inputs', '=', 'network_parameters.input_size', 'outputs', '=', 'inputs', 'projection', '=', 'None', 'for', 'conv_param', 'in', 'network_parameters.conv_parameters:', 'outputs', '=', 'tf.reshape(outputs,', '[-1,', 'conv_param....
47,604
kubeflow/pipelines
pipeline.py
get
get
Get information about a pipeline.
[ "Get", "information", "about", "a", "pipeline." ]
def get(ctx: click.Context, pipeline_id: str): client_obj: client.Client = ctx.obj['client'] output_format = ctx.obj['output'] pipeline = client_obj.get_pipeline(pipeline_id) output.print_output(pipeline, output.ModelType.PIPELINE, output_format)
['def', 'get(ctx:', 'click.Context,', 'pipeline_id:', 'str):', 'client_obj:', 'client.Client', '=', "ctx.obj['client']", 'output_format', '=', "ctx.obj['output']", 'pipeline', '=', 'client_obj.get_pipeline(pipeline_id)', 'output.print_output(pipeline,', 'output.ModelType.PIPELINE,', 'output_format)']
779,842
AndrewSpano/BSc-Thesis
run_utils.py
device_from_str
device_from_str
Fixes the torch device string if needed.
[ "Fixes", "the", "torch", "device", "string", "if", "needed." ]
def device_from_str(device_str: str) -> str: if device_str == 'auto': device_str = 'cuda' if torch.cuda.is_available() else 'cpu' return device_str
['def', 'device_from_str(device_str:', 'str)', '->', 'str:', 'if', 'device_str', '==', "'auto':", 'device_str', '=', "'cuda'", 'if', 'torch.cuda.is_available()', 'else', "'cpu'", 'return', 'device_str']
410,092
zwl-max/road_object_detection
bucketing_bbox_coder.py
bucket2bbox
bucket2bbox
Apply bucketing estimation (cls preds) and fine regression (offset preds) to generate det bboxes.
[ "Apply", "bucketing", "estimation", "(cls", "preds)", "and", "fine", "regression", "(offset", "preds)", "to", "generate", "det", "bboxes." ]
def bucket2bbox(proposals, cls_preds, offset_preds, num_buckets, scale_factor=1.0, max_shape=None, clip_border=True): side_num = int(np.ceil(num_buckets / 2.0)) cls_preds = cls_preds.view(-1, side_num) offset_preds = offset_preds.view(-1, side_num) scores = F.softmax(cls_preds, dim=1) (score_topk, s...
['def', 'bucket2bbox(proposals,', 'cls_preds,', 'offset_preds,', 'num_buckets,', 'scale_factor=1.0,', 'max_shape=None,', 'clip_border=True):', 'side_num', '=', 'int(np.ceil(num_buckets', '/', '2.0))', 'cls_preds', '=', 'cls_preds.view(-1,', 'side_num)', 'offset_preds', '=', 'offset_preds.view(-1,', 'side_num)', 'scores...
825,392
AboudyKreidieh/h-baselines
envs.py
AntGatherEnv.horizon
horizon
Return the environment time horizon.
[ "Return", "the", "environment", "time", "horizon." ]
def horizon(self): return self.HORIZON
['def', 'horizon(self):', 'return', 'self.HORIZON']
573,916
danielzgsilva/MOT
evaluate_tracking.py
trackingEvaluation.loadGroundtruth
loadGroundtruth
Helper function to load ground truth.
[ "Helper", "function", "to", "load", "ground", "truth." ]
def loadGroundtruth(self): try: self._loadData(self.gt_path, cls=self.cls, loading_groundtruth=True) except IOError: return False return True
['def', 'loadGroundtruth(self):', 'try:', 'self._loadData(self.gt_path,', 'cls=self.cls,', 'loading_groundtruth=True)', 'except', 'IOError:', 'return', 'False', 'return', 'True']
241,499
Ruturaj123/Flowchart-Detection
data_flow_ops.py
ConditionalAccumulatorBase.dtype
dtype
The datatype of the gradients accumulated by this accumulator.
[ "The", "datatype", "of", "the", "gradients", "accumulated", "by", "this", "accumulator." ]
def dtype(self): return self._dtype
['def', 'dtype(self):', 'return', 'self._dtype']
605,847
PaddlePaddle/Paddle3D
bevdet_nuscene_metrics.py
BevDetNuScenesMetric.compute
compute
Evaluation for a single model in nuScenes protocol.
[ "Evaluation", "for", "a", "single", "model", "in", "nuScenes", "protocol." ]
def compute(self, **kwargs) -> dict: (result_path_dict, tmp_dir) = self.format_results(self.predictions) result_path = result_path_dict['pts_bbox'] output_dir = osp.join(*osp.split(result_path)[:-1]) nusc = NuScenes(version=self.version, dataroot=self.data_root, verbose=False) eval_set_map = {'v1.0-...
['def', 'compute(self,', '**kwargs)', '->', 'dict:', '(result_path_dict,', 'tmp_dir)', '=', 'self.format_results(self.predictions)', 'result_path', '=', "result_path_dict['pts_bbox']", 'output_dir', '=', 'osp.join(*osp.split(result_path)[:-1])', 'nusc', '=', 'NuScenes(version=self.version,', 'dataroot=self.data_root,',...
777,264
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
tree.py
TreeParser.getErrorHeader
getErrorHeader
Prefix error message with the grammar name because message is always intended for the programmer because the parser built the input tree not the user.
[ "Prefix", "error", "message", "with", "the", "grammar", "name", "because", "message", "is", "always", "intended", "for", "the", "programmer", "because", "the", "parser", "built", "the", "input", "tree", "not", "the", "user." ]
def getErrorHeader(self, e): return self.getGrammarFileName() + ': node from %sline %s:%s' % (['', 'after '][e.approximateLineInfo], e.line, e.charPositionInLine)
['def', 'getErrorHeader(self,', 'e):', 'return', 'self.getGrammarFileName()', '+', "':", 'node', 'from', '%sline', "%s:%s'", '%', "(['',", "'after", "'][e.approximateLineInfo],", 'e.line,', 'e.charPositionInLine)']
10,347
deepmind/bsuite
agent.py
ActorCritic.select_action
select_action
Selects actions according to the latest softmax policy.
[ "Selects", "actions", "according", "to", "the", "latest", "softmax", "policy." ]
def select_action(self, timestep: dm_env.TimeStep) -> base.Action: observation = tf.expand_dims(timestep.observation, axis=0) action = self._sample_policy(observation) return action.numpy()
['def', 'select_action(self,', 'timestep:', 'dm_env.TimeStep)', '->', 'base.Action:', 'observation', '=', 'tf.expand_dims(timestep.observation,', 'axis=0)', 'action', '=', 'self._sample_policy(observation)', 'return', 'action.numpy()']
410,124
sunishsheth2009/ChatterBot
senna.py
SennaTagger.tag
tag
Applies the specified operation(s) on a list of tokens.
[ "Applies", "the", "specified", "operation(s)", "on", "a", "list", "of", "tokens." ]
def tag(self, tokens): return self.batch_tag([tokens])[0]
['def', 'tag(self,', 'tokens):', 'return', 'self.batch_tag([tokens])[0]']
530,324
lucko515/ml_tutor
knn.py
KNeighbourClassifier.interview_questions
interview_questions
Generates commonly asked interview questions about the algorithm in the Jupyter Notebook/Google colab.
[ "Generates", "commonly", "asked", "interview", "questions", "about", "the", "algorithm", "in", "the", "Jupyter", "Notebook/Google", "colab." ]
def interview_questions(self): if not super().__is_visual_on__(): print('Supported only in Jupyter Notebook and Google Colab.') return NotImplementedError from IPython.core.getipython import get_ipython content = u'\n<h1> K-Nearest Neighbors Interview Questions </h1>\n\n<h2> 1. What is âÂ\x...
['def', 'interview_questions(self):', 'if', 'not', 'super().__is_visual_on__():', "print('Supported", 'only', 'in', 'Jupyter', 'Notebook', 'and', 'Google', "Colab.')", 'return', 'NotImplementedError', 'from', 'IPython.core.getipython', 'import', 'get_ipython', 'content', '=', "u'\\n<h1>", 'K-Nearest', 'Neighbors', 'Int...
631,392
huawei-noah/xingtian
share_buffer.py
ShareBuf.get
get
Get a object data from plasma server with id.
[ "Get", "a", "object", "data", "from", "plasma", "server", "with", "id." ]
def get(self, object_id_byte): return self._get_buf(object_id_byte)
['def', 'get(self,', 'object_id_byte):', 'return', 'self._get_buf(object_id_byte)']
962,365
myothida/Supervised-Machine-Learning
predictor.py
TreePredictor.get_max_depth
get_max_depth
Return maximum depth among all leaves.
[ "Return", "maximum", "depth", "among", "all", "leaves." ]
def get_max_depth(self): return int(self.nodes['depth'].max())
['def', 'get_max_depth(self):', 'return', "int(self.nodes['depth'].max())"]
363,840
Ruturaj123/Flowchart-Detection
model_fn_test.py
EstimatorSpecEvalTest.testLossNumber
testLossNumber
Tests that error is raised when loss is a number (not Tensor).
[ "Tests", "that", "error", "is", "raised", "when", "loss", "is", "a", "number", "(not", "Tensor)." ]
def testLossNumber(self): with ops.Graph().as_default(), self.test_session(): with self.assertRaisesRegexp(TypeError, 'loss must be Tensor'): model_fn.EstimatorSpec(mode=model_fn.ModeKeys.EVAL, predictions={'loss': constant_op.constant(1.0)}, loss=1.0)
['def', 'testLossNumber(self):', 'with', 'ops.Graph().as_default(),', 'self.test_session():', 'with', 'self.assertRaisesRegexp(TypeError,', "'loss", 'must', 'be', "Tensor'):", 'model_fn.EstimatorSpec(mode=model_fn.ModeKeys.EVAL,', "predictions={'loss':", 'constant_op.constant(1.0)},', 'loss=1.0)']
605,189
rudranil723/mini-main
list.py
MultipleObjectMixin.get_allow_empty
get_allow_empty
Return ``True`` if the view should display empty lists and ``False`` if a 404 should be raised instead.
[ "Return", "``True``", "if", "the", "view", "should", "display", "empty", "lists", "and", "``False``", "if", "a", "404", "should", "be", "raised", "instead." ]
def get_allow_empty(self): return self.allow_empty
['def', 'get_allow_empty(self):', 'return', 'self.allow_empty']
316,933
usmancheema89/computer_vision
cpp_lint.py
GetHeaderGuardCPPVariable
GetHeaderGuardCPPVariable
Returns the CPP variable that should be used as a header guard.
[ "Returns", "the", "CPP", "variable", "that", "should", "be", "used", "as", "a", "header", "guard." ]
def GetHeaderGuardCPPVariable(filename): filename = re.sub('_flymake\\.h$', '.h', filename) filename = re.sub('/\\.flymake/([^/]*)$', '/\\1', filename) fileinfo = FileInfo(filename) file_path_from_root = fileinfo.RepositoryName() if _root: file_path_from_root = re.sub('^' + _root + os.sep, '...
['def', 'GetHeaderGuardCPPVariable(filename):', 'filename', '=', "re.sub('_flymake\\\\.h$',", "'.h',", 'filename)', 'filename', '=', "re.sub('/\\\\.flymake/([^/]*)$',", "'/\\\\1',", 'filename)', 'fileinfo', '=', 'FileInfo(filename)', 'file_path_from_root', '=', 'fileinfo.RepositoryName()', 'if', '_root:', 'file_path_fr...
473,224
intel/neural-compressor
kl_divergence.py
KL_Divergence.get_threshold
get_threshold
The interface of getting threshold per op using KL divergency algorithm.
[ "The", "interface", "of", "getting", "threshold", "per", "op", "using", "KL", "divergency", "algorithm." ]
def get_threshold(self, hist, hist_edges, min_val, max_val, num_bins, quantized_type, num_quantized_bins=255): if min_val >= 0: ending_iter = num_bins - 1 starting_iter = int(ending_iter * 0.7) else: th = max(abs(max_val), abs(min_val)) starting_iter = 0 ending_iter = num...
['def', 'get_threshold(self,', 'hist,', 'hist_edges,', 'min_val,', 'max_val,', 'num_bins,', 'quantized_type,', 'num_quantized_bins=255):', 'if', 'min_val', '>=', '0:', 'ending_iter', '=', 'num_bins', '-', '1', 'starting_iter', '=', 'int(ending_iter', '*', '0.7)', 'else:', 'th', '=', 'max(abs(max_val),', 'abs(min_val))'...
721,468
brain-research/hyperbolictext
post_analysis.py
save_hyperbolic_norms
save_hyperbolic_norms
Compute hyperbolic norms and save in sorted order.
[ "Compute", "hyperbolic", "norms", "and", "save", "in", "sorted", "order." ]
def save_hyperbolic_norms(output_embeddings, vocab): hyp_norms = np.squeeze(_hyperbolic_distance(output_embeddings, np.zeros((1, output_embeddings.shape[1])))) sorted_idx = np.argsort(hyp_norms) f = tf.gfile.Open(os.path.join(FLAGS.output_dir, 'sorted_hyperbolic_norms.txt'), 'w') f.write('\n'.join(['%s\...
['def', 'save_hyperbolic_norms(output_embeddings,', 'vocab):', 'hyp_norms', '=', 'np.squeeze(_hyperbolic_distance(output_embeddings,', 'np.zeros((1,', 'output_embeddings.shape[1]))))', 'sorted_idx', '=', 'np.argsort(hyp_norms)', 'f', '=', 'tf.gfile.Open(os.path.join(FLAGS.output_dir,', "'sorted_hyperbolic_norms.txt'),"...
228,123
dibyaghosh/gcsl
tracker.py
TrackerState.rot_euler
rot_euler
Returns the (rx, ry, rz) Euler rotations.
[ "Returns", "the", "(rx,", "ry,", "rz)", "Euler", "rotations." ]
def rot_euler(self): if self._rot_euler is not None: return self._rot_euler if self._rot_mat is not None: self._rot_euler = mat2euler(self.rot, axes='rxyz') return self._rot_euler
['def', 'rot_euler(self):', 'if', 'self._rot_euler', 'is', 'not', 'None:', 'return', 'self._rot_euler', 'if', 'self._rot_mat', 'is', 'not', 'None:', 'self._rot_euler', '=', 'mat2euler(self.rot,', "axes='rxyz')", 'return', 'self._rot_euler']
201,808
carlos-ferras/Sequence-ToolKit
SystemSolver.py
SystemSolver.saveState
saveState
Return a serializable description of the solver's current state.
[ "Return", "a", "serializable", "description", "of", "the", "solver's", "current", "state." ]
def saveState(self): state = OrderedDict() for (name, var) in self._vars.items(): state[name] = (var[0], var[2]) return state
['def', 'saveState(self):', 'state', '=', 'OrderedDict()', 'for', '(name,', 'var)', 'in', 'self._vars.items():', 'state[name]', '=', '(var[0],', 'var[2])', 'return', 'state']
876,885
thu-ml/tianshou
continuous.py
Actor.forward
forward
Mapping: obs -> logits -> action.
[ "Mapping:", "obs", "->", "logits", "->", "action." ]
def forward(self, obs: Union[np.ndarray, torch.Tensor], state: Any=None, info: Optional[dict[str, Any]]=None) -> tuple[torch.Tensor, Any]: if info is None: info = {} (logits, hidden) = self.preprocess(obs, state) logits = self.max_action * torch.tanh(self.last(logits)) return (logits, hidden)
['def', 'forward(self,', 'obs:', 'Union[np.ndarray,', 'torch.Tensor],', 'state:', 'Any=None,', 'info:', 'Optional[dict[str,', 'Any]]=None)', '->', 'tuple[torch.Tensor,', 'Any]:', 'if', 'info', 'is', 'None:', 'info', '=', '{}', '(logits,', 'hidden)', '=', 'self.preprocess(obs,', 'state)', 'logits', '=', 'self.max_action...
355,320
sunsmarterjie/SDL-Skeleton
create_res2net.py
res2net152_v1b_26w_4s
res2net152_v1b_26w_4s
Constructs a Res2Net-50_v1b_26w_4s model.
[ "Constructs", "a", "Res2Net-50_v1b_26w_4s", "model." ]
def res2net152_v1b_26w_4s(pretrained=False, **kwargs): model = Res2Net(Bottle2neck, [3, 8, 36, 3], baseWidth=26, scale=4, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['res2net152_v1b_26w_4s'])) return model
['def', 'res2net152_v1b_26w_4s(pretrained=False,', '**kwargs):', 'model', '=', 'Res2Net(Bottle2neck,', '[3,', '8,', '36,', '3],', 'baseWidth=26,', 'scale=4,', '**kwargs)', 'if', 'pretrained:', "model.load_state_dict(model_zoo.load_url(model_urls['res2net152_v1b_26w_4s']))", 'return', 'model']
855,216
microsoft/nni
mutable.py
MutableSymbol.float
float
Cast the mutable to a float.
[ "Cast", "the", "mutable", "to", "a", "float." ]
def float(self) -> MutableExpression[float]: return MutableExpression.to_float(self)
['def', 'float(self)', '->', 'MutableExpression[float]:', 'return', 'MutableExpression.to_float(self)']
728,653
YBZh/MaskSurf
checkpoint.py
get_unexpected_parameters_message
get_unexpected_parameters_message
Get a logging-friendly message to report parameter names (keys) that are in the checkpoint but not found in the model.
[ "Get", "a", "logging-friendly", "message", "to", "report", "parameter", "names", "(keys)", "that", "are", "in", "the", "checkpoint", "but", "not", "found", "in", "the", "model." ]
def get_unexpected_parameters_message(keys: List[str]) -> str: groups = _group_checkpoint_keys(keys) msg = 'The checkpoint state_dict contains keys that are not used by the model:\n' msg += '\n'.join((' ' + colored(k + _group_to_str(v), 'magenta') for (k, v) in groups.items())) return msg
['def', 'get_unexpected_parameters_message(keys:', 'List[str])', '->', 'str:', 'groups', '=', '_group_checkpoint_keys(keys)', 'msg', '=', "'The", 'checkpoint', 'state_dict', 'contains', 'keys', 'that', 'are', 'not', 'used', 'by', 'the', "model:\\n'", 'msg', '+=', "'\\n'.join(('", "'", '+', 'colored(k', '+', '_group_to_...
209,734
secretflow/secretflow
node_split.py
compute_gh
compute_gh
compute first and second order gradient of each sample.
[ "compute", "first", "and", "second", "order", "gradient", "of", "each", "sample." ]
def compute_gh(y: np.ndarray, pred: np.ndarray, objective: RegType) -> Tuple[np.ndarray, np.ndarray]: if objective == RegType.Linear: g = pred - y h = jnp.ones(pred.shape) elif objective == RegType.Logistic: yhat = sigmoid(pred) g = yhat - y h = yhat * (1 - yhat) else...
['def', 'compute_gh(y:', 'np.ndarray,', 'pred:', 'np.ndarray,', 'objective:', 'RegType)', '->', 'Tuple[np.ndarray,', 'np.ndarray]:', 'if', 'objective', '==', 'RegType.Linear:', 'g', '=', 'pred', '-', 'y', 'h', '=', 'jnp.ones(pred.shape)', 'elif', 'objective', '==', 'RegType.Logistic:', 'yhat', '=', 'sigmoid(pred)', 'g'...
856,508
marcsto/rl
vc1.py
VC1Transform.make_noload_model
make_noload_model
Creates an naive model at a custom destination.
[ "Creates", "an", "naive", "model", "at", "a", "custom", "destination." ]
def make_noload_model(cls): import vc_models models_filepath = os.path.dirname(os.path.abspath(vc_models.__file__)) cfg_path = os.path.join(models_filepath, 'conf', 'model', 'vc1_vitb_noload.yaml') if os.path.exists(cfg_path): return config = '_target_: vc_models.models.load_model\nmodel:\n ...
['def', 'make_noload_model(cls):', 'import', 'vc_models', 'models_filepath', '=', 'os.path.dirname(os.path.abspath(vc_models.__file__))', 'cfg_path', '=', 'os.path.join(models_filepath,', "'conf',", "'model',", "'vc1_vitb_noload.yaml')", 'if', 'os.path.exists(cfg_path):', 'return', 'config', '=', "'_target_:", 'vc_mode...
859,175
AiIsBetter/computer_vision
filesystem.py
try_import_dali
try_import_dali
Try import NVIDIA DALI at runtime.
[ "Try", "import", "NVIDIA", "DALI", "at", "runtime." ]
def try_import_dali(): try: dali = __import__('nvidia.dali', fromlist=['pipeline', 'ops', 'types']) dali.Pipeline = dali.pipeline.Pipeline except ImportError: class dali: class Pipeline: def __init__(self): raise NotImplementedError('DAL...
['def', 'try_import_dali():', 'try:', 'dali', '=', "__import__('nvidia.dali',", "fromlist=['pipeline',", "'ops',", "'types'])", 'dali.Pipeline', '=', 'dali.pipeline.Pipeline', 'except', 'ImportError:', 'class', 'dali:', 'class', 'Pipeline:', 'def', '__init__(self):', 'raise', "NotImplementedError('DALI", 'not', 'found,...
500,090
calico/basenji
basenji_hdf5_cluster.py
batch_end
batch_end
Determine the batch end that will keep the batch length under the given max.
[ "Determine", "the", "batch", "end", "that", "will", "keep", "the", "batch", "length", "under", "the", "given", "max." ]
def batch_end(segments, bstart, batch_max): bi = bstart blength = 0 while bi < len(segments) and blength < batch_max: (chrom, seg_start, seg_end) = segments[bi] blength += seg_end - seg_start bi += 1 bend = bi if bstart >= bend or bend > len(segments): print("I've mad...
['def', 'batch_end(segments,', 'bstart,', 'batch_max):', 'bi', '=', 'bstart', 'blength', '=', '0', 'while', 'bi', '<', 'len(segments)', 'and', 'blength', '<', 'batch_max:', '(chrom,', 'seg_start,', 'seg_end)', '=', 'segments[bi]', 'blength', '+=', 'seg_end', '-', 'seg_start', 'bi', '+=', '1', 'bend', '=', 'bi', 'if', '...
94,853
jesus255221/semantic_segmentation_benchmark
model.py
MaskRCNN.get_trainable_layers
get_trainable_layers
Returns a list of layers that have weights.
[ "Returns", "a", "list", "of", "layers", "that", "have", "weights." ]
def get_trainable_layers(self): layers = [] for l in self.keras_model.layers: l = self.find_trainable_layer(l) if l.get_weights(): layers.append(l) return layers
['def', 'get_trainable_layers(self):', 'layers', '=', '[]', 'for', 'l', 'in', 'self.keras_model.layers:', 'l', '=', 'self.find_trainable_layer(l)', 'if', 'l.get_weights():', 'layers.append(l)', 'return', 'layers']
873,881
wbsth/cs50ai
tictactoe.py
actions
actions
Returns set of all possible actions (i, j) available on the board.
[ "Returns", "set", "of", "all", "possible", "actions", "(i,", "j)", "available", "on", "the", "board." ]
def actions(board): possible_actions = set() for (i, row) in enumerate(board): if EMPTY in row: for (j, space) in enumerate(row): if space is EMPTY: possible_actions.add((i, j)) return possible_actions
['def', 'actions(board):', 'possible_actions', '=', 'set()', 'for', '(i,', 'row)', 'in', 'enumerate(board):', 'if', 'EMPTY', 'in', 'row:', 'for', '(j,', 'space)', 'in', 'enumerate(row):', 'if', 'space', 'is', 'EMPTY:', 'possible_actions.add((i,', 'j))', 'return', 'possible_actions']
192,091
Katja-M/Python_NaturalLanguageProcessing
backend_pgf.py
make_pdf_to_png_converter
make_pdf_to_png_converter
Returns a function that converts a pdf file to a png file.
[ "Returns", "a", "function", "that", "converts", "a", "pdf", "file", "to", "a", "png", "file." ]
def make_pdf_to_png_converter(): if shutil.which('pdftocairo'): def cairo_convert(pdffile, pngfile, dpi): cmd = ['pdftocairo', '-singlefile', '-png', '-r', '%d' % dpi, pdffile, os.path.splitext(pngfile)[0]] subprocess.check_output(cmd, stderr=subprocess.STDOUT) return cairo_...
['def', 'make_pdf_to_png_converter():', 'if', "shutil.which('pdftocairo'):", 'def', 'cairo_convert(pdffile,', 'pngfile,', 'dpi):', 'cmd', '=', "['pdftocairo',", "'-singlefile',", "'-png',", "'-r',", "'%d'", '%', 'dpi,', 'pdffile,', 'os.path.splitext(pngfile)[0]]', 'subprocess.check_output(cmd,', 'stderr=subprocess.STDO...
865,235
ashwanitanwar/nmt-transfer-learning-xlm-r
fairseq_incremental_decoder.py
FairseqIncrementalDecoder.set_beam_size
set_beam_size
Sets the beam size in the decoder and all children.
[ "Sets", "the", "beam", "size", "in", "the", "decoder", "and", "all", "children." ]
def set_beam_size(self, beam_size): if getattr(self, '_beam_size', -1) != beam_size: seen = set() def apply_set_beam_size(module): if module != self and hasattr(module, 'set_beam_size') and (module not in seen): seen.add(module) module.set_beam_size(beam_...
['def', 'set_beam_size(self,', 'beam_size):', 'if', 'getattr(self,', "'_beam_size',", '-1)', '!=', 'beam_size:', 'seen', '=', 'set()', 'def', 'apply_set_beam_size(module):', 'if', 'module', '!=', 'self', 'and', 'hasattr(module,', "'set_beam_size')", 'and', '(module', 'not', 'in', 'seen):', 'seen.add(module)', 'module.s...
732,942
KalleHallden/InstaAutomator
readers.py
FFMPEG_AudioReader.initialize
initialize
Opens the file, creates the pipe.
[ "Opens", "the", "file,", "creates", "the", "pipe." ]
def initialize(self, starttime=0): self.close_proc() if starttime != 0: offset = min(1, starttime) i_arg = ['-ss', '%.05f' % (starttime - offset), '-i', self.filename, '-vn', '-ss', '%.05f' % offset] else: i_arg = ['-i', self.filename, '-vn'] cmd = [get_setting('FFMPEG_BINARY')] ...
['def', 'initialize(self,', 'starttime=0):', 'self.close_proc()', 'if', 'starttime', '!=', '0:', 'offset', '=', 'min(1,', 'starttime)', 'i_arg', '=', "['-ss',", "'%.05f'", '%', '(starttime', '-', 'offset),', "'-i',", 'self.filename,', "'-vn',", "'-ss',", "'%.05f'", '%', 'offset]', 'else:', 'i_arg', '=', "['-i',", 'self...
242,859
ucdaviscl/soliloquy_variation
tokenizer.py
TreebankWordDetokenizer.detokenize
detokenize
Duck-typing the abstract *tokenize()*.
[ "Duck-typing", "the", "abstract", "*tokenize()*." ]
def detokenize(self, tokens, convert_parentheses=False): return self.tokenize(tokens, convert_parentheses)
['def', 'detokenize(self,', 'tokens,', 'convert_parentheses=False):', 'return', 'self.tokenize(tokens,', 'convert_parentheses)']
879,471
shivendrapratap2/Computer-Vision
flappybird.py
PipePair.visible
visible
Get whether this PipePair on screen, visible to the player.
[ "Get", "whether", "this", "PipePair", "on", "screen,", "visible", "to", "the", "player." ]
def visible(self): return -PipePair.WIDTH < self.x < WIN_WIDTH
['def', 'visible(self):', 'return', '-PipePair.WIDTH', '<', 'self.x', '<', 'WIN_WIDTH']
468,779
TrellixVulnTeam/Unsupervised_Learning_HFI7
tree.py
Function.iter_return_stmts
iter_return_stmts
Returns a generator of `return_stmt`.
[ "Returns", "a", "generator", "of", "`return_stmt`." ]
def iter_return_stmts(self): def scan(children): for element in children: if element.type == 'return_stmt' or (element.type == 'keyword' and element.value == 'return'): yield element if element.type in _RETURN_STMT_CONTAINERS: yield from scan(element....
['def', 'iter_return_stmts(self):', 'def', 'scan(children):', 'for', 'element', 'in', 'children:', 'if', 'element.type', '==', "'return_stmt'", 'or', '(element.type', '==', "'keyword'", 'and', 'element.value', '==', "'return'):", 'yield', 'element', 'if', 'element.type', 'in', '_RETURN_STMT_CONTAINERS:', 'yield', 'from...
454,018
gopinath-balu/computer_vision
cpp_lint.py
FindNextMatchingAngleBracket
FindNextMatchingAngleBracket
Find the corresponding > to close a template.
[ "Find", "the", "corresponding", ">", "to", "close", "a", "template." ]
def FindNextMatchingAngleBracket(clean_lines, linenum, init_suffix): line = init_suffix nesting_stack = ['<'] while True: match = Search('^[^<>(),;\\[\\]]*([<>(),;\\[\\]])(.*)$', line) if match: operator = match.group(1) line = match.group(2) if nesting_st...
['def', 'FindNextMatchingAngleBracket(clean_lines,', 'linenum,', 'init_suffix):', 'line', '=', 'init_suffix', 'nesting_stack', '=', "['<']", 'while', 'True:', 'match', '=', "Search('^[^<>(),;\\\\[\\\\]]*([<>(),;\\\\[\\\\]])(.*)$',", 'line)', 'if', 'match:', 'operator', '=', 'match.group(1)', 'line', '=', 'match.group(2...
473,150
facebookresearch/detectron2
config.py
CfgNode.merge_from_file
merge_from_file
Load content from the given config file and merge it into self.
[ "Load", "content", "from", "the", "given", "config", "file", "and", "merge", "it", "into", "self." ]
def merge_from_file(self, cfg_filename: str, allow_unsafe: bool=True) -> None: assert PathManager.isfile(cfg_filename), f"Config file '{cfg_filename}' does not exist!" loaded_cfg = self.load_yaml_with_base(cfg_filename, allow_unsafe=allow_unsafe) loaded_cfg = type(self)(loaded_cfg) from .defaults import...
['def', 'merge_from_file(self,', 'cfg_filename:', 'str,', 'allow_unsafe:', 'bool=True)', '->', 'None:', 'assert', 'PathManager.isfile(cfg_filename),', 'f"Config', 'file', "'{cfg_filename}'", 'does', 'not', 'exist!"', 'loaded_cfg', '=', 'self.load_yaml_with_base(cfg_filename,', 'allow_unsafe=allow_unsafe)', 'loaded_cfg'...
549,078
tensorflow/agents
stationary_stochastic_per_arm_py_environment_test.py
check_unbatched_time_step_spec
check_unbatched_time_step_spec
Checks if time step conforms array spec, even if batched.
[ "Checks", "if", "time", "step", "conforms", "array", "spec,", "even", "if", "batched." ]
def check_unbatched_time_step_spec(time_step, time_step_spec, batch_size): if batch_size is None: return array_spec.check_arrays_nest(time_step, time_step_spec) return array_spec.check_arrays_nest(time_step, array_spec.add_outer_dims_nest(time_step_spec, (batch_size,)))
['def', 'check_unbatched_time_step_spec(time_step,', 'time_step_spec,', 'batch_size):', 'if', 'batch_size', 'is', 'None:', 'return', 'array_spec.check_arrays_nest(time_step,', 'time_step_spec)', 'return', 'array_spec.check_arrays_nest(time_step,', 'array_spec.add_outer_dims_nest(time_step_spec,', '(batch_size,)))']
22,591
OpenMDAO/OpenMDAO-Framework
vector.py
Vector.promote
promote
Promote from N-dimensional to N+1 dimensional index space.
[ "Promote", "from", "N-dimensional", "to", "N+1", "dimensional", "index", "space." ]
def promote(self): shape = self.real_shape if len(shape) > 2: raise RuntimeError('Vector is 3D') elif len(shape) > 1: (imax, jmax) = shape if self.x is not None: new_arr = numpy.zeros((imax, jmax, 1)) new_arr[:, :, 0] = self.x[:, :] self.x = new_ar...
['def', 'promote(self):', 'shape', '=', 'self.real_shape', 'if', 'len(shape)', '>', '2:', 'raise', "RuntimeError('Vector", 'is', "3D')", 'elif', 'len(shape)', '>', '1:', '(imax,', 'jmax)', '=', 'shape', 'if', 'self.x', 'is', 'not', 'None:', 'new_arr', '=', 'numpy.zeros((imax,', 'jmax,', '1))', 'new_arr[:,', ':,', '0]',...
275,518
011235813/cm3
alg_baseline.py
Alg.run_actor_target
run_actor_target
Gets actions from the slowly-updating policy.
[ "Gets", "actions", "from", "the", "slowly-updating", "policy." ]
def run_actor_target(self, local_others, local_v, goals, epsilon, sess): feed = {self.obs_others: local_others, self.v_obs: local_v, self.v_goal: goals, self.epsilon: epsilon} action_samples_res = sess.run(self.action_samples_target, feed_dict=feed) return np.reshape(action_samples_res, action_samples_res.s...
['def', 'run_actor_target(self,', 'local_others,', 'local_v,', 'goals,', 'epsilon,', 'sess):', 'feed', '=', '{self.obs_others:', 'local_others,', 'self.v_obs:', 'local_v,', 'self.v_goal:', 'goals,', 'self.epsilon:', 'epsilon}', 'action_samples_res', '=', 'sess.run(self.action_samples_target,', 'feed_dict=feed)', 'retur...
488,559
googleapis/python-aiplatform
client.py
IndexServiceClient.index_endpoint_path
index_endpoint_path
Returns a fully-qualified index_endpoint string.
[ "Returns", "a", "fully-qualified", "index_endpoint", "string." ]
def index_endpoint_path(project: str, location: str, index_endpoint: str) -> str: return 'projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}'.format(project=project, location=location, index_endpoint=index_endpoint)
['def', 'index_endpoint_path(project:', 'str,', 'location:', 'str,', 'index_endpoint:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}'.format(project=project,", 'location=location,', 'index_endpoint=index_endpoint)']
812,959
43Carrig/recurrent_neural_networks_practice
message_test.py
MessageTest.testAssignByteStringToUnicodeField
testAssignByteStringToUnicodeField
Assigning a byte string to a string field should result in the value being converted to a Unicode string.
[ "Assigning", "a", "byte", "string", "to", "a", "string", "field", "should", "result", "in", "the", "value", "being", "converted", "to", "a", "Unicode", "string." ]
def testAssignByteStringToUnicodeField(self, message_module): m = message_module.TestAllTypes() m.optional_string = str('') self.assertIsInstance(m.optional_string, six.text_type)
['def', 'testAssignByteStringToUnicodeField(self,', 'message_module):', 'm', '=', 'message_module.TestAllTypes()', 'm.optional_string', '=', "str('')", 'self.assertIsInstance(m.optional_string,', 'six.text_type)']
309,951
jimtin/Stock_Comparison
session.py
extract_header
extract_header
Given a message or header, return the header.
[ "Given", "a", "message", "or", "header,", "return", "the", "header." ]
def extract_header(msg_or_header): if not msg_or_header: return {} try: h = msg_or_header['header'] except KeyError: try: h = msg_or_header['msg_id'] except KeyError: raise else: h = msg_or_header if not isinstance(h, dict): ...
['def', 'extract_header(msg_or_header):', 'if', 'not', 'msg_or_header:', 'return', '{}', 'try:', 'h', '=', "msg_or_header['header']", 'except', 'KeyError:', 'try:', 'h', '=', "msg_or_header['msg_id']", 'except', 'KeyError:', 'raise', 'else:', 'h', '=', 'msg_or_header', 'if', 'not', 'isinstance(h,', 'dict):', 'h', '=', ...
386,074
megvii-research/PETR
browse_dataset.py
build_data_cfg
build_data_cfg
Build data config for loading visualization data.
[ "Build", "data", "config", "for", "loading", "visualization", "data." ]
def build_data_cfg(config_path, skip_type, cfg_options): cfg = Config.fromfile(config_path) if cfg_options is not None: cfg.merge_from_dict(cfg_options) if cfg.get('custom_imports', None): from mmcv.utils import import_modules_from_strings import_modules_from_strings(**cfg['custom_im...
['def', 'build_data_cfg(config_path,', 'skip_type,', 'cfg_options):', 'cfg', '=', 'Config.fromfile(config_path)', 'if', 'cfg_options', 'is', 'not', 'None:', 'cfg.merge_from_dict(cfg_options)', 'if', "cfg.get('custom_imports',", 'None):', 'from', 'mmcv.utils', 'import', 'import_modules_from_strings', "import_modules_fro...
767,624
suarez12138/AI-Reversi_IMP_TextDichotomy
test_fir_filter_design.py
TestFirWinMore.test_bad_cutoff
test_bad_cutoff
Test that invalid cutoff argument raises ValueError.
[ "Test", "that", "invalid", "cutoff", "argument", "raises", "ValueError." ]
def test_bad_cutoff(self): assert_raises(ValueError, firwin, 99, -0.5) assert_raises(ValueError, firwin, 99, 1.5) assert_raises(ValueError, firwin, 99, [0, 0.5]) assert_raises(ValueError, firwin, 99, [0.5, 1]) assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.2]) assert_raises(ValueError, firwi...
['def', 'test_bad_cutoff(self):', 'assert_raises(ValueError,', 'firwin,', '99,', '-0.5)', 'assert_raises(ValueError,', 'firwin,', '99,', '1.5)', 'assert_raises(ValueError,', 'firwin,', '99,', '[0,', '0.5])', 'assert_raises(ValueError,', 'firwin,', '99,', '[0.5,', '1])', 'assert_raises(ValueError,', 'firwin,', '99,', '[...
100,035
secretflow/secretflow
load.py
SFLoadPartyScheduling.tests_finished
tests_finished
Return True if all tests have been executed by the nodes.
[ "Return", "True", "if", "all", "tests", "have", "been", "executed", "by", "the", "nodes." ]
def tests_finished(self): if not self.collection_is_completed: return False if self.pending: return False for pending in self.node2pending.values(): if len(pending) >= 2: return False return True
['def', 'tests_finished(self):', 'if', 'not', 'self.collection_is_completed:', 'return', 'False', 'if', 'self.pending:', 'return', 'False', 'for', 'pending', 'in', 'self.node2pending.values():', 'if', 'len(pending)', '>=', '2:', 'return', 'False', 'return', 'True']
856,721
cleanlab/cleanlab
object_detection_utils.py
softmin1d
softmin1d
Returns softmin of passed in scores.
[ "Returns", "softmin", "of", "passed", "in", "scores." ]
def softmin1d(scores: np.ndarray, temperature: float=0.99, axis: int=0) -> float: scores = np.array(scores) softmax_scores = softmax(x=-1 * scores, temperature=temperature, axis=axis, shift=True) return np.dot(softmax_scores, scores)
['def', 'softmin1d(scores:', 'np.ndarray,', 'temperature:', 'float=0.99,', 'axis:', 'int=0)', '->', 'float:', 'scores', '=', 'np.array(scores)', 'softmax_scores', '=', 'softmax(x=-1', '*', 'scores,', 'temperature=temperature,', 'axis=axis,', 'shift=True)', 'return', 'np.dot(softmax_scores,', 'scores)']
488,015
michaelhush/M-LOOP
visualizations.py
create_learner_visualizer_from_archive
create_learner_visualizer_from_archive
Create an instance of the appropriate visualizer class for a learner archive.
[ "Create", "an", "instance", "of", "the", "appropriate", "visualizer", "class", "for", "a", "learner", "archive." ]
def create_learner_visualizer_from_archive(filename, controller_type=None, **kwargs): if controller_type is not None: warnings.warn('The controller_type argument is now deprecated and has no effect. It will be removed in a future version of M-LOOP. Do not provide a value for controller_type.') controlle...
['def', 'create_learner_visualizer_from_archive(filename,', 'controller_type=None,', '**kwargs):', 'if', 'controller_type', 'is', 'not', 'None:', "warnings.warn('The", 'controller_type', 'argument', 'is', 'now', 'deprecated', 'and', 'has', 'no', 'effect.', 'It', 'will', 'be', 'removed', 'in', 'a', 'future', 'version', ...
619,949
HCIILAB/DeRPN
cpp_lint.py
FindNextMultiLineCommentEnd
FindNextMultiLineCommentEnd
We are inside a comment, find the end marker.
[ "We", "are", "inside", "a", "comment,", "find", "the", "end", "marker." ]
def FindNextMultiLineCommentEnd(lines, lineix): while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines)
['def', 'FindNextMultiLineCommentEnd(lines,', 'lineix):', 'while', 'lineix', '<', 'len(lines):', 'if', "lines[lineix].strip().endswith('*/'):", 'return', 'lineix', 'lineix', '+=', '1', 'return', 'len(lines)']
184,073
Edward-CNRG-NTU/ADLxMLDS2017
utils.py
make_sequences_same_length
make_sequences_same_length
Make sequences same length for avoiding value error: setting an array element with a sequence.
[ "Make", "sequences", "same", "length", "for", "avoiding", "value", "error:", "setting", "an", "array", "element", "with", "a", "sequence." ]
def make_sequences_same_length(sequences, sequences_lengths, default_value=0.0, max_length=41): num_samples = len(sequences) if max_length == 0: max_length = np.max(sequences_lengths) sample_shape = tuple() for s in sequences: if len(s) > 0: sample_shape = np.asarray(s).shape...
['def', 'make_sequences_same_length(sequences,', 'sequences_lengths,', 'default_value=0.0,', 'max_length=41):', 'num_samples', '=', 'len(sequences)', 'if', 'max_length', '==', '0:', 'max_length', '=', 'np.max(sequences_lengths)', 'sample_shape', '=', 'tuple()', 'for', 's', 'in', 'sequences:', 'if', 'len(s)', '>', '0:',...
396,660
openvinotoolkit/training_extensions
omz_wrapper.py
download_model
download_model
Function for downloading model from directory.
[ "Function", "for", "downloading", "model", "from", "directory." ]
def download_model(model, download_dir=OMZ_CACHE, precisions=None, force=False): download_dir = Path('') if download_dir is None else Path(download_dir) precisions = precisions if precisions else {'FP32'} if not force and (download_dir / model.subdirectory).exists(): target_file_names = [] f...
['def', 'download_model(model,', 'download_dir=OMZ_CACHE,', 'precisions=None,', 'force=False):', 'download_dir', '=', "Path('')", 'if', 'download_dir', 'is', 'None', 'else', 'Path(download_dir)', 'precisions', '=', 'precisions', 'if', 'precisions', 'else', "{'FP32'}", 'if', 'not', 'force', 'and', '(download_dir', '/', ...
919,066
onnx/onnx
test_external_data.py
TestNotAllowToLoadExternalDataOutsideModelDirectory.test_check_model_relative
test_check_model_relative
More relative path test.
[ "More", "relative", "path", "test." ]
def test_check_model_relative(self) -> None: self.model_filename = self.create_test_model('../test/../file.bin') with self.assertRaises(onnx.checker.ValidationError): checker.check_model(self.model_filename)
['def', 'test_check_model_relative(self)', '->', 'None:', 'self.model_filename', '=', "self.create_test_model('../test/../file.bin')", 'with', 'self.assertRaises(onnx.checker.ValidationError):', 'checker.check_model(self.model_filename)']
756,586
googleapis/python-aiplatform
client.py
JobServiceClient.persistent_resource_path
persistent_resource_path
Returns a fully-qualified persistent_resource string.
[ "Returns", "a", "fully-qualified", "persistent_resource", "string." ]
def persistent_resource_path(project: str, location: str, persistent_resource: str) -> str: return 'projects/{project}/locations/{location}/persistentResources/{persistent_resource}'.format(project=project, location=location, persistent_resource=persistent_resource)
['def', 'persistent_resource_path(project:', 'str,', 'location:', 'str,', 'persistent_resource:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}/persistentResources/{persistent_resource}'.format(project=project,", 'location=location,', 'persistent_resource=persistent_resource)']
813,065
nesl/Time-in-State-RL
benchmark_dr.py
WalkerBaseBulletEnv.move_robot
move_robot
Used by multiplayer stadium to move sideways, to another running lane.
[ "Used", "by", "multiplayer", "stadium", "to", "move", "sideways,", "to", "another", "running", "lane." ]
def move_robot(self, init_x, init_y, init_z): self.cpp_robot.query_position() pose = self.cpp_robot.root_part.pose() pose.move_xyz(init_x, init_y, init_z) self.cpp_robot.set_pose(pose)
['def', 'move_robot(self,', 'init_x,', 'init_y,', 'init_z):', 'self.cpp_robot.query_position()', 'pose', '=', 'self.cpp_robot.root_part.pose()', 'pose.move_xyz(init_x,', 'init_y,', 'init_z)', 'self.cpp_robot.set_pose(pose)']
917,271
opendilab/DI-star
host_remote_agent.py
VsAgent.host_ports
host_ports
The WebSocket ports that the remote agents should connect to.
[ "The", "WebSocket", "ports", "that", "the", "remote", "agents", "should", "connect", "to." ]
def host_ports(self): return [process.port for process in self._processes]
['def', 'host_ports(self):', 'return', '[process.port', 'for', 'process', 'in', 'self._processes]']
184,620
scikit-learn/scikit-learn
test_iforest.py
test_iforest_error
test_iforest_error
Test that it gives proper exception on deficient input.
[ "Test", "that", "it", "gives", "proper", "exception", "on", "deficient", "input." ]
def test_iforest_error(): X = iris.data warn_msg = 'max_samples will be set to n_samples for estimation' with pytest.warns(UserWarning, match=warn_msg): IsolationForest(max_samples=1000).fit(X) with warnings.catch_warnings(): warnings.simplefilter('error', UserWarning) IsolationF...
['def', 'test_iforest_error():', 'X', '=', 'iris.data', 'warn_msg', '=', "'max_samples", 'will', 'be', 'set', 'to', 'n_samples', 'for', "estimation'", 'with', 'pytest.warns(UserWarning,', 'match=warn_msg):', 'IsolationForest(max_samples=1000).fit(X)', 'with', 'warnings.catch_warnings():', "warnings.simplefilter('error'...
853,187
tobegit3hub/deep_image_model
test.py
is_built_with_cuda
is_built_with_cuda
Returns whether TensorFlow was built with CUDA (GPU) support.
[ "Returns", "whether", "TensorFlow", "was", "built", "with", "CUDA", "(GPU)", "support." ]
def is_built_with_cuda(): return _test_util.IsGoogleCudaEnabled()
['def', 'is_built_with_cuda():', 'return', '_test_util.IsGoogleCudaEnabled()']
183,170
DeepLearnXMU/ABDNMT-RNMT
model.py
Seq2Seq.get_targets
get_targets
Get targets from either the sample or the net's output.
[ "Get", "targets", "from", "either", "the", "sample", "or", "the", "net's", "output." ]
def get_targets(self, sample): return sample['target']
['def', 'get_targets(self,', 'sample):', 'return', "sample['target']"]
6,370
brain-research/acai
discretization.py
DiscreteBottleneck.bit_to_int
bit_to_int
Turn x_bit representing numbers bitwise (lower-endian) to int tensor.
[ "Turn", "x_bit", "representing", "numbers", "bitwise", "(lower-endian)", "to", "int", "tensor." ]
def bit_to_int(self, x_bit, num_bits, base=2): x_l = tf.stop_gradient(tf.to_int32(tf.reshape(x_bit, [-1, num_bits]))) x_labels = [] for i in range(num_bits): x_labels.append(x_l[:, i] * tf.to_int32(base) ** tf.to_int32(i)) res = sum(x_labels) return tf.to_int32(res)
['def', 'bit_to_int(self,', 'x_bit,', 'num_bits,', 'base=2):', 'x_l', '=', 'tf.stop_gradient(tf.to_int32(tf.reshape(x_bit,', '[-1,', 'num_bits])))', 'x_labels', '=', '[]', 'for', 'i', 'in', 'range(num_bits):', 'x_labels.append(x_l[:,', 'i]', '*', 'tf.to_int32(base)', '**', 'tf.to_int32(i))', 'res', '=', 'sum(x_labels)'...
406,647
arvention/STDN-PyTorch
bbox_utils.py
match
match
Match each prior box with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds.
[ "Match", "each", "prior", "box", "with", "the", "ground", "truth", "box", "of", "the", "highest", "jaccard", "overlap,", "encode", "the", "bounding", "boxes,", "then", "return", "the", "matched", "indices", "corresponding", "to", "both", "confidence", "and", "...
def match(threshold, class_target, loc_target, anchors, variances): iou = jaccard(loc_target, point_form(anchors)) (best_object_iou, best_object_i) = iou.max(0) (best_anchor_iou, best_anchor_i) = iou.max(1) best_object_iou.index_fill_(0, best_anchor_i, 2) for j in range(best_anchor_i.shape[0]): ...
['def', 'match(threshold,', 'class_target,', 'loc_target,', 'anchors,', 'variances):', 'iou', '=', 'jaccard(loc_target,', 'point_form(anchors))', '(best_object_iou,', 'best_object_i)', '=', 'iou.max(0)', '(best_anchor_iou,', 'best_anchor_i)', '=', 'iou.max(1)', 'best_object_iou.index_fill_(0,', 'best_anchor_i,', '2)', ...
873,681
marcsto/rl
collectors.py
_MultiDataCollector.set_seed
set_seed
Sets the seeds of the environments stored in the DataCollector.
[ "Sets", "the", "seeds", "of", "the", "environments", "stored", "in", "the", "DataCollector." ]
def set_seed(self, seed: int, static_seed: bool=False) -> int: _check_for_faulty_process(self.procs) for idx in range(self.num_workers): self.pipes[idx].send(((seed, static_seed), 'seed')) (new_seed, msg) = self.pipes[idx].recv() if msg != 'seeded': raise RuntimeError(f"Expec...
['def', 'set_seed(self,', 'seed:', 'int,', 'static_seed:', 'bool=False)', '->', 'int:', '_check_for_faulty_process(self.procs)', 'for', 'idx', 'in', 'range(self.num_workers):', 'self.pipes[idx].send(((seed,', 'static_seed),', "'seed'))", '(new_seed,', 'msg)', '=', 'self.pipes[idx].recv()', 'if', 'msg', '!=', "'seeded':...
858,570
Kvatsx/Artificial-Intelligence-Assignments
_dicom.py
list_files
list_files
List all files in the directory, recursively.
[ "List", "all", "files", "in", "the", "directory,", "recursively." ]
def list_files(files, path): for item in os.listdir(path): item = os.path.join(path, item) if os.path.isdir(item): list_files(files, item) elif os.path.isfile(item): files.append(item)
['def', 'list_files(files,', 'path):', 'for', 'item', 'in', 'os.listdir(path):', 'item', '=', 'os.path.join(path,', 'item)', 'if', 'os.path.isdir(item):', 'list_files(files,', 'item)', 'elif', 'os.path.isfile(item):', 'files.append(item)']
37,438
facebookresearch/ddr
eval.py
prune
prune
Prune states down to length b, sorting by val.
[ "Prune", "states", "down", "to", "length", "b,", "sorting", "by", "val." ]
def prune(states, b): return sorted(states, key=itemgetter(4))[:b]
['def', 'prune(states,', 'b):', 'return', 'sorted(states,', 'key=itemgetter(4))[:b]']
516,313
arshpreetsingh/quantopian-machinelearning
frontend_widget.py
FrontendHighlighter.transform_ipy_prompt
transform_ipy_prompt
Handle inputs that start classic IPython prompt syntax.
[ "Handle", "inputs", "that", "start", "classic", "IPython", "prompt", "syntax." ]
def transform_ipy_prompt(self, line): if not line or line.isspace(): return line m = self._ipy_prompt_re.match(line) if m: return line[len(m.group(0)):] else: return line
['def', 'transform_ipy_prompt(self,', 'line):', 'if', 'not', 'line', 'or', 'line.isspace():', 'return', 'line', 'm', '=', 'self._ipy_prompt_re.match(line)', 'if', 'm:', 'return', 'line[len(m.group(0)):]', 'else:', 'return', 'line']
892,871
sarnsdev/social-alignment-data-mining
bvls.py
compute_kkt_optimality
compute_kkt_optimality
Compute the maximum violation of KKT conditions.
[ "Compute", "the", "maximum", "violation", "of", "KKT", "conditions." ]
def compute_kkt_optimality(g, on_bound): g_kkt = g * on_bound free_set = on_bound == 0 g_kkt[free_set] = np.abs(g[free_set]) return np.max(g_kkt)
['def', 'compute_kkt_optimality(g,', 'on_bound):', 'g_kkt', '=', 'g', '*', 'on_bound', 'free_set', '=', 'on_bound', '==', '0', 'g_kkt[free_set]', '=', 'np.abs(g[free_set])', 'return', 'np.max(g_kkt)']
391,090
implus/GFocalV2
iou_balanced_neg_sampler.py
IoUBalancedNegSampler.sample_via_interval
sample_via_interval
Sample according to the iou interval.
[ "Sample", "according", "to", "the", "iou", "interval." ]
def sample_via_interval(self, max_overlaps, full_set, num_expected): max_iou = max_overlaps.max() iou_interval = (max_iou - self.floor_thr) / self.num_bins per_num_expected = int(num_expected / self.num_bins) sampled_inds = [] for i in range(self.num_bins): start_iou = self.floor_thr + i * i...
['def', 'sample_via_interval(self,', 'max_overlaps,', 'full_set,', 'num_expected):', 'max_iou', '=', 'max_overlaps.max()', 'iou_interval', '=', '(max_iou', '-', 'self.floor_thr)', '/', 'self.num_bins', 'per_num_expected', '=', 'int(num_expected', '/', 'self.num_bins)', 'sampled_inds', '=', '[]', 'for', 'i', 'in', 'rang...
557,389
Katja-M/Python_NaturalLanguageProcessing
backend_bases.py
FigureCanvasBase.leave_notify_event
leave_notify_event
Backend derived classes should call this function when leaving canvas Parameters ---------- guiEvent The native UI event that generated the Matplotlib event.
[ "Backend", "derived", "classes", "should", "call", "this", "function", "when", "leaving", "canvas", "Parameters", "----------", "guiEvent", "The", "native", "UI", "event", "that", "generated", "the", "Matplotlib", "event." ]
def leave_notify_event(self, guiEvent=None): self.callbacks.process('figure_leave_event', LocationEvent.lastevent) LocationEvent.lastevent = None (self._lastx, self._lasty) = (None, None)
['def', 'leave_notify_event(self,', 'guiEvent=None):', "self.callbacks.process('figure_leave_event',", 'LocationEvent.lastevent)', 'LocationEvent.lastevent', '=', 'None', '(self._lastx,', 'self._lasty)', '=', '(None,', 'None)']
864,275
LucasAlegre/morl-baselines
accrued_reward_buffer.py
AccruedRewardReplayBuffer.sample
sample
Sample a batch of experiences.
[ "Sample", "a", "batch", "of", "experiences." ]
def sample(self, batch_size, replace=True, use_cer=False, to_tensor=False, device=None): inds = np.random.choice(self.size, batch_size, replace=replace) if use_cer: inds[0] = self.ptr - 1 experience_tuples = (self.obs[inds], self.accrued_rewards[inds], self.actions[inds], self.rewards[inds], self.ne...
['def', 'sample(self,', 'batch_size,', 'replace=True,', 'use_cer=False,', 'to_tensor=False,', 'device=None):', 'inds', '=', 'np.random.choice(self.size,', 'batch_size,', 'replace=replace)', 'if', 'use_cer:', 'inds[0]', '=', 'self.ptr', '-', '1', 'experience_tuples', '=', '(self.obs[inds],', 'self.accrued_rewards[inds],...
655,767
ratschlab/dpsom
TempDPSOM_model.py
TDPSOM.z_dist_flat_ng
z_dist_flat_ng
Computes the distances between the centroids and the embeddings stopping the gradient of the latent embeddings.
[ "Computes", "the", "distances", "between", "the", "centroids", "and", "the", "embeddings", "stopping", "the", "gradient", "of", "the", "latent", "embeddings." ]
def z_dist_flat_ng(self): z_dist = tf.squared_difference(tf.expand_dims(tf.expand_dims(tf.stop_gradient(self.z_e_sample), 1), 1), tf.expand_dims(self.embeddings, 0)) z_dist_red = tf.reduce_sum(z_dist, axis=-1) z_dist_flat = tf.reshape(z_dist_red, [-1, self.som_dim[0] * self.som_dim[1]]) return z_dist_fl...
['def', 'z_dist_flat_ng(self):', 'z_dist', '=', 'tf.squared_difference(tf.expand_dims(tf.expand_dims(tf.stop_gradient(self.z_e_sample),', '1),', '1),', 'tf.expand_dims(self.embeddings,', '0))', 'z_dist_red', '=', 'tf.reduce_sum(z_dist,', 'axis=-1)', 'z_dist_flat', '=', 'tf.reshape(z_dist_red,', '[-1,', 'self.som_dim[0]...
166,973
google-research/scenic
losses.py
verb_hard_neg_nce
verb_hard_neg_nce
Returns HN-NCE loss when including verb hard negatives.
[ "Returns", "HN-NCE", "loss", "when", "including", "verb", "hard", "negatives." ]
def verb_hard_neg_nce(encoded_video: jnp.ndarray, encoded_text: jnp.ndarray, mask_text: jnp.ndarray, temperature: float=0.05, v2t_weight: float=1.0, t2v_weight: float=1.0, beta: float=0.0) -> float: logits = utils.compute_inners(encoded_video, encoded_text) (labels, masking, inverse_mask_hn_other_vid) = get_con...
['def', 'verb_hard_neg_nce(encoded_video:', 'jnp.ndarray,', 'encoded_text:', 'jnp.ndarray,', 'mask_text:', 'jnp.ndarray,', 'temperature:', 'float=0.05,', 'v2t_weight:', 'float=1.0,', 't2v_weight:', 'float=1.0,', 'beta:', 'float=0.0)', '->', 'float:', 'logits', '=', 'utils.compute_inners(encoded_video,', 'encoded_text)'...
847,469
AEProgrammer/object_detection
vis.py
vis_one_image_opencv
vis_one_image_opencv
Constructs a numpy array with the detections visualized.
[ "Constructs", "a", "numpy", "array", "with", "the", "detections", "visualized." ]
def vis_one_image_opencv(im, boxes, segms=None, keypoints=None, thresh=0.9, kp_thresh=2, show_box=False, dataset=None, show_class=False): if isinstance(boxes, list): (boxes, segms, keypoints, classes) = convert_from_cls_format(boxes, segms, keypoints) if boxes is None or boxes.shape[0] == 0 or max(boxes...
['def', 'vis_one_image_opencv(im,', 'boxes,', 'segms=None,', 'keypoints=None,', 'thresh=0.9,', 'kp_thresh=2,', 'show_box=False,', 'dataset=None,', 'show_class=False):', 'if', 'isinstance(boxes,', 'list):', '(boxes,', 'segms,', 'keypoints,', 'classes)', '=', 'convert_from_cls_format(boxes,', 'segms,', 'keypoints)', 'if'...
773,718
shellerbrand/machine-learning-for-artistic-style
learning.py
gram_matrix
gram_matrix
Computes the Gram matrix for a set of feature maps.
[ "Computes", "the", "Gram", "matrix", "for", "a", "set", "of", "feature", "maps." ]
def gram_matrix(feature_maps): (batch_size, height, width, channels) = tf.unstack(tf.shape(feature_maps)) denominator = tf.to_float(height * width) feature_maps = tf.reshape(feature_maps, tf.stack([batch_size, height * width, channels])) matrix = tf.matmul(feature_maps, feature_maps, adjoint_a=True) ...
['def', 'gram_matrix(feature_maps):', '(batch_size,', 'height,', 'width,', 'channels)', '=', 'tf.unstack(tf.shape(feature_maps))', 'denominator', '=', 'tf.to_float(height', '*', 'width)', 'feature_maps', '=', 'tf.reshape(feature_maps,', 'tf.stack([batch_size,', 'height', '*', 'width,', 'channels]))', 'matrix', '=', 'tf...
620,696
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nav_env.py
NavigationEnv.get_targets
get_targets
Returns the target actions from the current node.
[ "Returns", "the", "target", "actions", "from", "the", "current", "node." ]
def get_targets(self, current_node_ids, step_number): action = self.get_optimal_action(current_node_ids, step_number) action = np.expand_dims(action, axis=1) return vars(utils.Foo(action=action))
['def', 'get_targets(self,', 'current_node_ids,', 'step_number):', 'action', '=', 'self.get_optimal_action(current_node_ids,', 'step_number)', 'action', '=', 'np.expand_dims(action,', 'axis=1)', 'return', 'vars(utils.Foo(action=action))']
47,193
microsoft/maro
vector_env.py
VectorEnv.tick
tick
List[int]: Return tick of all environments.
[ "List[int]:", "Return", "tick", "of", "all", "environments." ]
def tick(self) -> List[int]: return self._send('tick')
['def', 'tick(self)', '->', 'List[int]:', 'return', "self._send('tick')"]
628,749
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes
core.py
_extrema_operation.reduce
reduce
Reduce target along the given axis.
[ "Reduce", "target", "along", "the", "given", "axis." ]
def reduce(self, target, axis=np._NoValue): target = narray(target, copy=False, subok=True) m = getmask(target) if axis is np._NoValue and target.ndim > 1: warnings.warn('In the future the default for ma.{0}.reduce will be axis=0, not the current None, to match np.{0}.reduce. Explicitly pass 0 or No...
['def', 'reduce(self,', 'target,', 'axis=np._NoValue):', 'target', '=', 'narray(target,', 'copy=False,', 'subok=True)', 'm', '=', 'getmask(target)', 'if', 'axis', 'is', 'np._NoValue', 'and', 'target.ndim', '>', '1:', "warnings.warn('In", 'the', 'future', 'the', 'default', 'for', 'ma.{0}.reduce', 'will', 'be', 'axis=0,'...
966,910
scikit-learn/scikit-learn
test_pipeline.py
test_set_feature_union_passthrough
test_set_feature_union_passthrough
Check the behaviour of setting a transformer to `"passthrough"`.
[ "Check", "the", "behaviour", "of", "setting", "a", "transformer", "to", "`\"passthrough\"`." ]
def test_set_feature_union_passthrough(): mult2 = Mult(2) mult3 = Mult(3) mult2.get_feature_names_out = lambda input_features: ['x2'] mult3.get_feature_names_out = lambda input_features: ['x3'] X = np.asarray([[1]]) ft = FeatureUnion([('m2', mult2), ('m3', mult3)]) assert_array_equal([[2, 3]...
['def', 'test_set_feature_union_passthrough():', 'mult2', '=', 'Mult(2)', 'mult3', '=', 'Mult(3)', 'mult2.get_feature_names_out', '=', 'lambda', 'input_features:', "['x2']", 'mult3.get_feature_names_out', '=', 'lambda', 'input_features:', "['x3']", 'X', '=', 'np.asarray([[1]])', 'ft', '=', "FeatureUnion([('m2',", 'mult...
854,198
augmentedstartups/AS-One
kalmanfilter.py
KalmanFilterNew.log_likelihood
log_likelihood
log-likelihood of the last measurement.
[ "log-likelihood", "of", "the", "last", "measurement." ]
def log_likelihood(self): if self._log_likelihood is None: self._log_likelihood = logpdf(x=self.y, cov=self.S) return self._log_likelihood
['def', 'log_likelihood(self):', 'if', 'self._log_likelihood', 'is', 'None:', 'self._log_likelihood', '=', 'logpdf(x=self.y,', 'cov=self.S)', 'return', 'self._log_likelihood']
402,393
devashish-patel/webcam-motion-detector
inputsplitter.py
IPythonInputSplitter.transform_cell
transform_cell
Process and translate a cell of input.
[ "Process", "and", "translate", "a", "cell", "of", "input." ]
def transform_cell(self, cell): self.reset() try: self.push(cell) self.flush_transformers() return self.source finally: self.reset()
['def', 'transform_cell(self,', 'cell):', 'self.reset()', 'try:', 'self.push(cell)', 'self.flush_transformers()', 'return', 'self.source', 'finally:', 'self.reset()']
978,651
kylechenoO/AIOPS_PLATFORM
WebApp.py
exceptions
exceptions
Logging after every Exception.
[ "Logging", "after", "every", "Exception." ]
def exceptions(e): ts = strftime('[%Y-%b-%d %H:%M]') logger.error('%s %s %s %s %s 5xx INTERNAL SERVER ERROR', ts, request.remote_addr, request.method, request.scheme, request.full_path) return ('Internal Server Error', 500)
['def', 'exceptions(e):', 'ts', '=', "strftime('[%Y-%b-%d", "%H:%M]')", "logger.error('%s", '%s', '%s', '%s', '%s', '5xx', 'INTERNAL', 'SERVER', "ERROR',", 'ts,', 'request.remote_addr,', 'request.method,', 'request.scheme,', 'request.full_path)', 'return', "('Internal", 'Server', "Error',", '500)']
86,474
TheCurryMan/MedicAI
dictconfig.py
DictConfigurator.configure_logger
configure_logger
Configure a non-root logger from a dictionary.
[ "Configure", "a", "non-root", "logger", "from", "a", "dictionary." ]
def configure_logger(self, name, config, incremental=False): logger = logging.getLogger(name) self.common_logger_config(logger, config, incremental) propagate = config.get('propagate', None) if propagate is not None: logger.propagate = propagate
['def', 'configure_logger(self,', 'name,', 'config,', 'incremental=False):', 'logger', '=', 'logging.getLogger(name)', 'self.common_logger_config(logger,', 'config,', 'incremental)', 'propagate', '=', "config.get('propagate',", 'None)', 'if', 'propagate', 'is', 'not', 'None:', 'logger.propagate', '=', 'propagate']
648,609
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
schedules_test.py
SchedulesTest.ScheduleTestHelper
ScheduleTestHelper
Run common checks for schedules.
[ "Run", "common", "checks", "for", "schedules." ]
def ScheduleTestHelper(self, config, schedule_subtype, io_values): f = schedules.make_schedule(config) self.assertTrue(isinstance(f, schedule_subtype)) fns = [schedules.make_schedule(config) for _ in xrange(3)] for (i, o) in io_values: for f in fns: f_out = f(i) self.asse...
['def', 'ScheduleTestHelper(self,', 'config,', 'schedule_subtype,', 'io_values):', 'f', '=', 'schedules.make_schedule(config)', 'self.assertTrue(isinstance(f,', 'schedule_subtype))', 'fns', '=', '[schedules.make_schedule(config)', 'for', '_', 'in', 'xrange(3)]', 'for', '(i,', 'o)', 'in', 'io_values:', 'for', 'f', 'in',...
52,542
microsoft/MASS
evaluator.py
Evaluator.get_iterator
get_iterator
Create a new iterator for a dataset.
[ "Create", "a", "new", "iterator", "for", "a", "dataset." ]
def get_iterator(self, data_set, lang1, lang2=None, stream=False): assert data_set in ['valid', 'test'] assert lang1 in self.params.langs assert lang2 is None or lang2 in self.params.langs assert stream is False or lang2 is None if len(self.params.langs) > 30: eval_lgs = set(['ar', 'bg', 'de...
['def', 'get_iterator(self,', 'data_set,', 'lang1,', 'lang2=None,', 'stream=False):', 'assert', 'data_set', 'in', "['valid',", "'test']", 'assert', 'lang1', 'in', 'self.params.langs', 'assert', 'lang2', 'is', 'None', 'or', 'lang2', 'in', 'self.params.langs', 'assert', 'stream', 'is', 'False', 'or', 'lang2', 'is', 'None...
646,055
zhang614/MicroGrid
newrange.py
newrange.index
index
Return the 0-based position of integer `value` in the sequence this range represents.
[ "Return", "the", "0-based", "position", "of", "integer", "`value`", "in", "the", "sequence", "this", "range", "represents." ]
def index(self, value): try: diff = value - self._start except TypeError: raise ValueError('%r is not in range' % value) (quotient, remainder) = divmod(diff, self._step) if remainder == 0 and 0 <= quotient < self._len: return abs(quotient) raise ValueError('%r is not in range...
['def', 'index(self,', 'value):', 'try:', 'diff', '=', 'value', '-', 'self._start', 'except', 'TypeError:', 'raise', "ValueError('%r", 'is', 'not', 'in', "range'", '%', 'value)', '(quotient,', 'remainder)', '=', 'divmod(diff,', 'self._step)', 'if', 'remainder', '==', '0', 'and', '0', '<=', 'quotient', '<', 'self._len:'...
636,524
bnpy/bnpy
MOVBBirthMergeAlg.py
MOVBBirthMergeAlg.hasMoreReasonableMoves
hasMoreReasonableMoves
Decide if more moves will feasibly change current configuration.
[ "Decide", "if", "more", "moves", "will", "feasibly", "change", "current", "configuration." ]
def hasMoreReasonableMoves(self, lapFrac, SS): if lapFrac - self.algParams['startLap'] >= self.algParams['nLap']: return False if self.hasMove('delete'): deleteStartLap = self.algParams['delete']['deleteStartLap'] nBeforeQuit = self.algParams['delete']['deleteNumStuckBeforeQuit'] ...
['def', 'hasMoreReasonableMoves(self,', 'lapFrac,', 'SS):', 'if', 'lapFrac', '-', "self.algParams['startLap']", '>=', "self.algParams['nLap']:", 'return', 'False', 'if', "self.hasMove('delete'):", 'deleteStartLap', '=', "self.algParams['delete']['deleteStartLap']", 'nBeforeQuit', '=', "self.algParams['delete']['deleteN...
464,817
drckf/paysage
gendocs.py
getfunctions
getfunctions
Get the documentation strings for each function in the item (a module or class).
[ "Get", "the", "documentation", "strings", "for", "each", "function", "in", "the", "item", "(a", "module", "or", "class)." ]
def getfunctions(item): output = list() def is_local_func(mod): return pydoc.inspect.isfunction(mod) and mod.__module__.find('paysage') > -1 methods = pydoc.inspect.getmembers(item, is_local_func) for func in methods: (func_name, reference) = func if func_name.startswith('_') an...
['def', 'getfunctions(item):', 'output', '=', 'list()', 'def', 'is_local_func(mod):', 'return', 'pydoc.inspect.isfunction(mod)', 'and', "mod.__module__.find('paysage')", '>', '-1', 'methods', '=', 'pydoc.inspect.getmembers(item,', 'is_local_func)', 'for', 'func', 'in', 'methods:', '(func_name,', 'reference)', '=', 'fun...
278,652
astooke/rlpyt
sac_agent.py
SacAgent.target_q
target_q
Compute twin target Q-values for state/observation and input action.
[ "Compute", "twin", "target", "Q-values", "for", "state/observation", "and", "input", "action." ]
def target_q(self, observation, prev_action, prev_reward, action): model_inputs = buffer_to((observation, prev_action, prev_reward, action), device=self.device) target_q1 = self.target_q1_model(*model_inputs) target_q2 = self.target_q2_model(*model_inputs) return (target_q1.cpu(), target_q2.cpu())
['def', 'target_q(self,', 'observation,', 'prev_action,', 'prev_reward,', 'action):', 'model_inputs', '=', 'buffer_to((observation,', 'prev_action,', 'prev_reward,', 'action),', 'device=self.device)', 'target_q1', '=', 'self.target_q1_model(*model_inputs)', 'target_q2', '=', 'self.target_q2_model(*model_inputs)', 'retu...
334,476
triaquae/triaquae
__init__.py
Field.get_prep_value
get_prep_value
Perform preliminary non-db specific value checks and conversions.
[ "Perform", "preliminary", "non-db", "specific", "value", "checks", "and", "conversions." ]
def get_prep_value(self, value): return value
['def', 'get_prep_value(self,', 'value):', 'return', 'value']
423,527
myothida/Supervised-Machine-Learning
test_discriminant_analysis.py
test_lda_array_api
test_lda_array_api
Check that the array_api Array gives the same results as ndarrays.
[ "Check", "that", "the", "array_api", "Array", "gives", "the", "same", "results", "as", "ndarrays." ]
def test_lda_array_api(array_namespace): xp = pytest.importorskip(array_namespace) X_xp = xp.asarray(X) y_xp = xp.asarray(y3) lda = LinearDiscriminantAnalysis() lda.fit(X, y3) array_attributes = {key: value for (key, value) in vars(lda).items() if isinstance(value, np.ndarray)} lda_xp = clon...
['def', 'test_lda_array_api(array_namespace):', 'xp', '=', 'pytest.importorskip(array_namespace)', 'X_xp', '=', 'xp.asarray(X)', 'y_xp', '=', 'xp.asarray(y3)', 'lda', '=', 'LinearDiscriminantAnalysis()', 'lda.fit(X,', 'y3)', 'array_attributes', '=', '{key:', 'value', 'for', '(key,', 'value)', 'in', 'vars(lda).items()',...
364,641
tensorflow/agents
reinforce_agent.py
ReinforceAgent.value_estimation_loss
value_estimation_loss
Computes the value estimation loss.
[ "Computes", "the", "value", "estimation", "loss." ]
def value_estimation_loss(self, value_preds: types.Tensor, returns: types.Tensor, num_episodes: types.Int, weights: Optional[types.Tensor]=None) -> types.Tensor: value_estimation_error = tf.math.squared_difference(returns, value_preds) if weights is not None: value_estimation_error *= weights value_...
['def', 'value_estimation_loss(self,', 'value_preds:', 'types.Tensor,', 'returns:', 'types.Tensor,', 'num_episodes:', 'types.Int,', 'weights:', 'Optional[types.Tensor]=None)', '->', 'types.Tensor:', 'value_estimation_error', '=', 'tf.math.squared_difference(returns,', 'value_preds)', 'if', 'weights', 'is', 'not', 'None...
23,231
ashwanitanwar/nmt-transfer-learning-xlm-r
data_utils.py
filter_by_size
filter_by_size
Filter indices based on their size.
[ "Filter", "indices", "based", "on", "their", "size." ]
def filter_by_size(indices, dataset, max_positions, raise_exception=False): if isinstance(max_positions, float) or isinstance(max_positions, int): if hasattr(dataset, 'sizes') and isinstance(dataset.sizes, np.ndarray): ignored = indices[dataset.sizes[indices] > max_positions].tolist() ...
['def', 'filter_by_size(indices,', 'dataset,', 'max_positions,', 'raise_exception=False):', 'if', 'isinstance(max_positions,', 'float)', 'or', 'isinstance(max_positions,', 'int):', 'if', 'hasattr(dataset,', "'sizes')", 'and', 'isinstance(dataset.sizes,', 'np.ndarray):', 'ignored', '=', 'indices[dataset.sizes[indices]',...
733,282
Alexander-Parker/youtube_nlp
cache.py
Cache.getsizeof
getsizeof
Return the size of a cache element's value.
[ "Return", "the", "size", "of", "a", "cache", "element's", "value." ]
def getsizeof(value): return 1
['def', 'getsizeof(value):', 'return', '1']
969,969