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
mo-cv/pycv
utils.py
createCurveFunc
createCurveFunc
Return a function derived from control points.
[ "Return", "a", "function", "derived", "from", "control", "points." ]
def createCurveFunc(points): if points is None: return None numPoints = len(points) if numPoints < 2: return None (xs, ys) = zip(*points) if numPoints < 4: kind = 'linear' else: kind = 'cubic' return scipy.interpolate.interp1d(xs, ys, kind, bounds_error=False)
['def', 'createCurveFunc(points):', 'if', 'points', 'is', 'None:', 'return', 'None', 'numPoints', '=', 'len(points)', 'if', 'numPoints', '<', '2:', 'return', 'None', '(xs,', 'ys)', '=', 'zip(*points)', 'if', 'numPoints', '<', '4:', 'kind', '=', "'linear'", 'else:', 'kind', '=', "'cubic'", 'return', 'scipy.interpolate.i...
819,502
boat-group/fancy-nlp
ner_predictor.py
NERPredictor.pretty_tag_batch
pretty_tag_batch
Analyze the tagging results of given batch of text predicted by the ner model and return the results in pretty format with detailed information.
[ "Analyze", "the", "tagging", "results", "of", "given", "batch", "of", "text", "predicted", "by", "the", "ner", "model", "and", "return", "the", "results", "in", "pretty", "format", "with", "detailed", "information." ]
def pretty_tag_batch(self, texts: Union[List[str], List[List[str]]]) -> List[Dict[str, Any]]: pred_probs = self.predict_prob_batch(texts) lengths = [min(len(text), pred_prob.shape[0]) for (text, pred_prob) in zip(texts, pred_probs)] tags = self.preprocessor.label_decode(pred_probs, lengths) pred_probs =...
['def', 'pretty_tag_batch(self,', 'texts:', 'Union[List[str],', 'List[List[str]]])', '->', 'List[Dict[str,', 'Any]]:', 'pred_probs', '=', 'self.predict_prob_batch(texts)', 'lengths', '=', '[min(len(text),', 'pred_prob.shape[0])', 'for', '(text,', 'pred_prob)', 'in', 'zip(texts,', 'pred_probs)]', 'tags', '=', 'self.prep...
559,222
openai/spinningup
serialization_utils.py
convert_json
convert_json
Convert obj to a version which can be serialized with JSON.
[ "Convert", "obj", "to", "a", "version", "which", "can", "be", "serialized", "with", "JSON." ]
def convert_json(obj): if is_json_serializable(obj): return obj else: if isinstance(obj, dict): return {convert_json(k): convert_json(v) for (k, v) in obj.items()} elif isinstance(obj, tuple): return (convert_json(x) for x in obj) elif isinstance(obj, list...
['def', 'convert_json(obj):', 'if', 'is_json_serializable(obj):', 'return', 'obj', 'else:', 'if', 'isinstance(obj,', 'dict):', 'return', '{convert_json(k):', 'convert_json(v)', 'for', '(k,', 'v)', 'in', 'obj.items()}', 'elif', 'isinstance(obj,', 'tuple):', 'return', '(convert_json(x)', 'for', 'x', 'in', 'obj)', 'elif',...
371,783
bhateharsh/computer_vision
head.py
KerasHead.call
call
The Keras model call will delegate to the `_predict` method.
[ "The", "Keras", "model", "call", "will", "delegate", "to", "the", "`_predict`", "method." ]
def call(self, features): return self._predict(features)
['def', 'call(self,', 'features):', 'return', 'self._predict(features)']
512,014
explosion/spaCy
test_pipe_methods.py
test_disable_pipes_context_restore
test_disable_pipes_context_restore
Test that a disabled component stays disabled after running the context manager.
[ "Test", "that", "a", "disabled", "component", "stays", "disabled", "after", "running", "the", "context", "manager." ]
def test_disable_pipes_context_restore(nlp, name): nlp.add_pipe('new_pipe', name=name) assert nlp.has_pipe(name) nlp.disable_pipe(name) assert not nlp.has_pipe(name) with nlp.select_pipes(disable=name): assert not nlp.has_pipe(name) assert not nlp.has_pipe(name)
['def', 'test_disable_pipes_context_restore(nlp,', 'name):', "nlp.add_pipe('new_pipe',", 'name=name)', 'assert', 'nlp.has_pipe(name)', 'nlp.disable_pipe(name)', 'assert', 'not', 'nlp.has_pipe(name)', 'with', 'nlp.select_pipes(disable=name):', 'assert', 'not', 'nlp.has_pipe(name)', 'assert', 'not', 'nlp.has_pipe(name)']
894,305
pipermerriam/flex
decorators.py
skip_if_empty
skip_if_empty
Decorator for validation functions which makes them pass if the value passed in is the EMPTY sentinal value.
[ "Decorator", "for", "validation", "functions", "which", "makes", "them", "pass", "if", "the", "value", "passed", "in", "is", "the", "EMPTY", "sentinal", "value." ]
def skip_if_empty(func): @partial_safe_wraps(func) def inner(value, *args, **kwargs): if value is EMPTY: return else: return func(value, *args, **kwargs) return inner
['def', 'skip_if_empty(func):', '@partial_safe_wraps(func)', 'def', 'inner(value,', '*args,', '**kwargs):', 'if', 'value', 'is', 'EMPTY:', 'return', 'else:', 'return', 'func(value,', '*args,', '**kwargs)', 'return', 'inner']
211,270
arshpreetsingh/quantopian-machinelearning
msvc.py
RegistryInfo.vc_for_python
vc_for_python
Microsoft Visual C++ for Python registry key.
[ "Microsoft", "Visual", "C++", "for", "Python", "registry", "key." ]
def vc_for_python(self): return 'DevDiv\\VCForPython'
['def', 'vc_for_python(self):', 'return', "'DevDiv\\\\VCForPython'"]
893,107
FreshAirTonight/af2complex
folding.py
compute_violation_metrics
compute_violation_metrics
Compute several metrics to assess the structural violations.
[ "Compute", "several", "metrics", "to", "assess", "the", "structural", "violations." ]
def compute_violation_metrics(batch: Dict[str, jnp.ndarray], atom14_pred_positions: jnp.ndarray, violations: Dict[str, jnp.ndarray]) -> Dict[str, jnp.ndarray]: ret = {} extreme_ca_ca_violations = all_atom.extreme_ca_ca_distance_violations(pred_atom_positions=atom14_pred_positions, pred_atom_mask=batch['atom14_a...
['def', 'compute_violation_metrics(batch:', 'Dict[str,', 'jnp.ndarray],', 'atom14_pred_positions:', 'jnp.ndarray,', 'violations:', 'Dict[str,', 'jnp.ndarray])', '->', 'Dict[str,', 'jnp.ndarray]:', 'ret', '=', '{}', 'extreme_ca_ca_violations', '=', 'all_atom.extreme_ca_ca_distance_violations(pred_atom_positions=atom14_p...
400,644
omarmhaimdat/twitter_nlp_native_swift
compiler.py
CodeGenerator.pop_assign_tracking
pop_assign_tracking
Pops the topmost level for assignment tracking and updates the context variables if necessary.
[ "Pops", "the", "topmost", "level", "for", "assignment", "tracking", "and", "updates", "the", "context", "variables", "if", "necessary." ]
def pop_assign_tracking(self, frame): vars = self._assign_stack.pop() if not frame.toplevel or not vars: return public_names = [x for x in vars if x[:1] != '_'] if len(vars) == 1: name = next(iter(vars)) ref = frame.symbols.ref(name) self.writeline('context.vars[%r] = %s'...
['def', 'pop_assign_tracking(self,', 'frame):', 'vars', '=', 'self._assign_stack.pop()', 'if', 'not', 'frame.toplevel', 'or', 'not', 'vars:', 'return', 'public_names', '=', '[x', 'for', 'x', 'in', 'vars', 'if', 'x[:1]', '!=', "'_']", 'if', 'len(vars)', '==', '1:', 'name', '=', 'next(iter(vars))', 'ref', '=', 'frame.sym...
953,842
joao-montanari/artificial_intelligence
__init__.py
packb
packb
Pack object `o` and return packed bytes See :class:`Packer` for options.
[ "Pack", "object", "`o`", "and", "return", "packed", "bytes", "See", ":class:`Packer`", "for", "options." ]
def packb(o, **kwargs): return Packer(**kwargs).pack(o)
['def', 'packb(o,', '**kwargs):', 'return', 'Packer(**kwargs).pack(o)']
155,311
HCIILAB/DeRPN
cpp_lint.py
ProcessLine
ProcessLine
Processes a single line in the file.
[ "Processes", "a", "single", "line", "in", "the", "file." ]
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) if nesti...
['def', 'ProcessLine(filename,', 'file_extension,', 'clean_lines,', 'line,', 'include_state,', 'function_state,', 'nesting_state,', 'error,', 'extra_check_functions=[]):', 'raw_lines', '=', 'clean_lines.raw_lines', 'ParseNolintSuppressions(filename,', 'raw_lines[line],', 'line,', 'error)', 'nesting_state.Update(filenam...
184,117
QData/deepWordBug
nodes.py
GenericNodeVisitor.default_visit
default_visit
Override for generic, uniform traversals.
[ "Override", "for", "generic,", "uniform", "traversals." ]
def default_visit(self, node): raise NotImplementedError
['def', 'default_visit(self,', 'node):', 'raise', 'NotImplementedError']
542,075
tencent-ailab/TriNet
iterators.py
CountingIterator.has_next
has_next
Whether the iterator has been exhausted.
[ "Whether", "the", "iterator", "has", "been", "exhausted." ]
def has_next(self): return self.n < self.total
['def', 'has_next(self):', 'return', 'self.n', '<', 'self.total']
425,154
Ruturaj123/Flowchart-Detection
test_utils.py
test_parameter_recovery
test_parameter_recovery
Test that a generative model fits generated data.
[ "Test", "that", "a", "generative", "model", "fits", "generated", "data." ]
def test_parameter_recovery(generate_fn, generative_model, train_iterations, test_case, seed, learning_rate=0.1, rtol=0.2, atol=0.1, train_loss_tolerance_coeff=0.99, ignore_params_fn=lambda _: (), derived_param_test_fn=lambda _: (), train_input_fn_type=input_pipeline.WholeDatasetInputFn, train_state_manager=state_manag...
['def', 'test_parameter_recovery(generate_fn,', 'generative_model,', 'train_iterations,', 'test_case,', 'seed,', 'learning_rate=0.1,', 'rtol=0.2,', 'atol=0.1,', 'train_loss_tolerance_coeff=0.99,', 'ignore_params_fn=lambda', '_:', '(),', 'derived_param_test_fn=lambda', '_:', '(),', 'train_input_fn_type=input_pipeline.Wh...
604,684
calico/basenji
sonnet_predict_bed.py
bigwig_open
bigwig_open
Open the bigwig file for writing and write the header.
[ "Open", "the", "bigwig", "file", "for", "writing", "and", "write", "the", "header." ]
def bigwig_open(bw_file, genome_file): bw_out = pyBigWig.open(bw_file, 'w') chrom_sizes = [] for line in open(genome_file): a = line.split() chrom_sizes.append((a[0], int(a[1]))) bw_out.addHeader(chrom_sizes) return bw_out
['def', 'bigwig_open(bw_file,', 'genome_file):', 'bw_out', '=', 'pyBigWig.open(bw_file,', "'w')", 'chrom_sizes', '=', '[]', 'for', 'line', 'in', 'open(genome_file):', 'a', '=', 'line.split()', 'chrom_sizes.append((a[0],', 'int(a[1])))', 'bw_out.addHeader(chrom_sizes)', 'return', 'bw_out']
94,847
Xianpeng919/MonoCon
builder.py
build_positional_encoding
build_positional_encoding
Builder for Position Encoding.
[ "Builder", "for", "Position", "Encoding." ]
def build_positional_encoding(cfg, default_args=None): return build_from_cfg(cfg, POSITIONAL_ENCODING, default_args)
['def', 'build_positional_encoding(cfg,', 'default_args=None):', 'return', 'build_from_cfg(cfg,', 'POSITIONAL_ENCODING,', 'default_args)']
654,126
sek788432/Waymo-2D-Object-Detection
train_utils.py
parse_configuration
parse_configuration
Parses ExperimentConfig from flags.
[ "Parses", "ExperimentConfig", "from", "flags." ]
def parse_configuration(flags_obj, lock_return=True, print_return=True): params = exp_factory.get_exp_config(flags_obj.experiment) for config_file in flags_obj.config_file or []: params = hyperparams.override_params_dict(params, config_file, is_strict=True) params.override({'runtime': {'tpu': flags_...
['def', 'parse_configuration(flags_obj,', 'lock_return=True,', 'print_return=True):', 'params', '=', 'exp_factory.get_exp_config(flags_obj.experiment)', 'for', 'config_file', 'in', 'flags_obj.config_file', 'or', '[]:', 'params', '=', 'hyperparams.override_params_dict(params,', 'config_file,', 'is_strict=True)', "params...
972,330
arshpreetsingh/quantopian-machinelearning
testing.py
HTMLTreeBuilderSmokeTest.assertDoctypeHandled
assertDoctypeHandled
Assert that a given doctype string is handled correctly.
[ "Assert", "that", "a", "given", "doctype", "string", "is", "handled", "correctly." ]
def assertDoctypeHandled(self, doctype_fragment): (doctype_str, soup) = self._document_with_doctype(doctype_fragment) doctype = soup.contents[0] self.assertEqual(doctype.__class__, Doctype) self.assertEqual(doctype, doctype_fragment) self.assertEqual(str(soup)[:len(doctype_str)], doctype_str) se...
['def', 'assertDoctypeHandled(self,', 'doctype_fragment):', '(doctype_str,', 'soup)', '=', 'self._document_with_doctype(doctype_fragment)', 'doctype', '=', 'soup.contents[0]', 'self.assertEqual(doctype.__class__,', 'Doctype)', 'self.assertEqual(doctype,', 'doctype_fragment)', 'self.assertEqual(str(soup)[:len(doctype_st...
816,520
sunishsheth2009/ChatterBot
ma.py
masked_binary_operation.reduce
reduce
Reduce target along the given axis with this function.
[ "Reduce", "target", "along", "the", "given", "axis", "with", "this", "function." ]
def reduce(self, target, axis=0, dtype=None): m = getmask(target) t = filled(target, self.filly) if t.shape == (): t = t.reshape(1) if m is not nomask: m = make_mask(m, copy=1) m.shape = (1,) if m is nomask: t = self.f.reduce(t, axis) else: t =...
['def', 'reduce(self,', 'target,', 'axis=0,', 'dtype=None):', 'm', '=', 'getmask(target)', 't', '=', 'filled(target,', 'self.filly)', 'if', 't.shape', '==', '():', 't', '=', 't.reshape(1)', 'if', 'm', 'is', 'not', 'nomask:', 'm', '=', 'make_mask(m,', 'copy=1)', 'm.shape', '=', '(1,)', 'if', 'm', 'is', 'nomask:', 't', '...
532,341
Eric3911/OpenAGI
data_utils.py
ais_cache_base
ais_cache_base
Return path to local cache for AIS.
[ "Return", "path", "to", "local", "cache", "for", "AIS." ]
def ais_cache_base() -> str: override_dir = os.environ.get(constants.NEMO_ENV_DATA_STORE_CACHE_DIR, '') if override_dir == '': cache_dir = resolve_cache_dir().as_posix() else: cache_dir = pathlib.Path(override_dir).resolve().as_posix() if cache_dir.endswith(NEMO_VERSION): cache_d...
['def', 'ais_cache_base()', '->', 'str:', 'override_dir', '=', 'os.environ.get(constants.NEMO_ENV_DATA_STORE_CACHE_DIR,', "'')", 'if', 'override_dir', '==', "'':", 'cache_dir', '=', 'resolve_cache_dir().as_posix()', 'else:', 'cache_dir', '=', 'pathlib.Path(override_dir).resolve().as_posix()', 'if', 'cache_dir.endswith(...
274,167
ZhangAoCanada/RADDet
drawer.py
getEllipse
getEllipse
Draw 2D Gaussian Ellipse.
[ "Draw", "2D", "Gaussian", "Ellipse." ]
def getEllipse(color, means, covariances, scale_factor=1): sign = np.sign(means[0] / means[1]) (eigen, eigen_vec) = np.linalg.eig(covariances) eigen_root_x = np.sqrt(eigen[0]) * scale_factor eigen_root_y = np.sqrt(eigen[1]) * scale_factor theta = np.degrees(np.arctan2(*eigen_vec[:, 0][::-1])) el...
['def', 'getEllipse(color,', 'means,', 'covariances,', 'scale_factor=1):', 'sign', '=', 'np.sign(means[0]', '/', 'means[1])', '(eigen,', 'eigen_vec)', '=', 'np.linalg.eig(covariances)', 'eigen_root_x', '=', 'np.sqrt(eigen[0])', '*', 'scale_factor', 'eigen_root_y', '=', 'np.sqrt(eigen[1])', '*', 'scale_factor', 'theta',...
835,777
43Carrig/recurrent_neural_networks_practice
multi_worker_util.py
is_chief
is_chief
Returns whether the given task is chief in the cluster.
[ "Returns", "whether", "the", "given", "task", "is", "chief", "in", "the", "cluster." ]
def is_chief(cluster_spec, task_type, task_id): cluster_spec = normalize_cluster_spec(cluster_spec) if task_type not in cluster_spec.jobs: raise ValueError('The task_type "%s" is not in the `cluster_spec`.' % task_type) if task_id >= cluster_spec.num_tasks(task_type): raise ValueError('The `...
['def', 'is_chief(cluster_spec,', 'task_type,', 'task_id):', 'cluster_spec', '=', 'normalize_cluster_spec(cluster_spec)', 'if', 'task_type', 'not', 'in', 'cluster_spec.jobs:', 'raise', "ValueError('The", 'task_type', '"%s"', 'is', 'not', 'in', 'the', "`cluster_spec`.'", '%', 'task_type)', 'if', 'task_id', '>=', 'cluste...
336,069
sandialabs/bcnn
utils.py
round_down
round_down
Rounds num to next lowest multiple of factor.
[ "Rounds", "num", "to", "next", "lowest", "multiple", "of", "factor." ]
def round_down(num, factor): return num // factor * factor
['def', 'round_down(num,', 'factor):', 'return', 'num', '//', 'factor', '*', 'factor']
105,976
rifqind/Agent-Programs-3KS1
guisupport.py
get_app_qt4
get_app_qt4
Create a new qt4 app or return an existing one.
[ "Create", "a", "new", "qt4", "app", "or", "return", "an", "existing", "one." ]
def get_app_qt4(*args, **kwargs): from IPython.external.qt_for_kernel import QtGui app = QtGui.QApplication.instance() if app is None: if not args: args = ([''],) app = QtGui.QApplication(*args, **kwargs) return app
['def', 'get_app_qt4(*args,', '**kwargs):', 'from', 'IPython.external.qt_for_kernel', 'import', 'QtGui', 'app', '=', 'QtGui.QApplication.instance()', 'if', 'app', 'is', 'None:', 'if', 'not', 'args:', 'args', '=', "([''],)", 'app', '=', 'QtGui.QApplication(*args,', '**kwargs)', 'return', 'app']
41,612
devashish-patel/webcam-motion-detector
test_contents_api.py
APITest.delete_file
delete_file
Delete a file at the given path if it exists.
[ "Delete", "a", "file", "at", "the", "given", "path", "if", "it", "exists." ]
def delete_file(self, api_path): if self.isfile(api_path): os.unlink(self.to_os_path(api_path))
['def', 'delete_file(self,', 'api_path):', 'if', 'self.isfile(api_path):', 'os.unlink(self.to_os_path(api_path))']
980,787
microsoft/InnerEye-DeepLearning
lightning_container.py
LightningContainer.get_callbacks
get_callbacks
Gets additional callbacks that the trainer should use when training this model.
[ "Gets", "additional", "callbacks", "that", "the", "trainer", "should", "use", "when", "training", "this", "model." ]
def get_callbacks(self) -> List[Callback]: return []
['def', 'get_callbacks(self)', '->', 'List[Callback]:', 'return', '[]']
612,901
sek788432/Waymo-2D-Object-Detection
assemblenet.py
flow_conv_stem
flow_conv_stem
Layers for an optical flow stem.
[ "Layers", "for", "an", "optical", "flow", "stem." ]
def flow_conv_stem(inputs, filters, temporal_dilation, bn_decay: float=rf.BATCH_NORM_DECAY, bn_epsilon: float=rf.BATCH_NORM_EPSILON, use_sync_bn: bool=False): if temporal_dilation < 1: temporal_dilation = 1 inputs = conv2d_fixed_padding(inputs=inputs, filters=filters, kernel_size=7, strides=2) input...
['def', 'flow_conv_stem(inputs,', 'filters,', 'temporal_dilation,', 'bn_decay:', 'float=rf.BATCH_NORM_DECAY,', 'bn_epsilon:', 'float=rf.BATCH_NORM_EPSILON,', 'use_sync_bn:', 'bool=False):', 'if', 'temporal_dilation', '<', '1:', 'temporal_dilation', '=', '1', 'inputs', '=', 'conv2d_fixed_padding(inputs=inputs,', 'filter...
973,304
MegEngine/Transfer-Learning-Library
mdd.py
GeneralModule.step
step
Gradually increase :math:`\lambda` in GRL layer.
[ "Gradually", "increase", ":math:`\\lambda`", "in", "GRL", "layer." ]
def step(self): self.grl_layer.step()
['def', 'step(self):', 'self.grl_layer.step()']
921,111
RunpeiDong/ACT
indoor3d_util.py
bbox_label_to_obj
bbox_label_to_obj
Visualization of bounding boxes.
[ "Visualization", "of", "bounding", "boxes." ]
def bbox_label_to_obj(input_filename, out_filename_prefix, easy_view=False): bbox_label = np.loadtxt(input_filename) bbox = bbox_label[:, 0:6] label = bbox_label[:, -1].astype(int) v_cnt = 0 ins_cnt = 0 for i in range(bbox.shape[0]): if easy_view and label[i] not in g_easy_view_labels: ...
['def', 'bbox_label_to_obj(input_filename,', 'out_filename_prefix,', 'easy_view=False):', 'bbox_label', '=', 'np.loadtxt(input_filename)', 'bbox', '=', 'bbox_label[:,', '0:6]', 'label', '=', 'bbox_label[:,', '-1].astype(int)', 'v_cnt', '=', '0', 'ins_cnt', '=', '0', 'for', 'i', 'in', 'range(bbox.shape[0]):', 'if', 'eas...
407,317
rifqind/Agent-Programs-3KS1
agents.py
GraphicEnvironment.run
run
Run the Environment for given number of time steps, but update the GUI too.
[ "Run", "the", "Environment", "for", "given", "number", "of", "time", "steps,", "but", "update", "the", "GUI", "too." ]
def run(self, steps=1000, delay=1): for step in range(steps): self.update(delay) if self.is_done(): break self.step() self.update(delay)
['def', 'run(self,', 'steps=1000,', 'delay=1):', 'for', 'step', 'in', 'range(steps):', 'self.update(delay)', 'if', 'self.is_done():', 'break', 'self.step()', 'self.update(delay)']
40,282
HealthML/ContIG
ukb_covariate_prediction.py
load_from_state_dict_img_only
load_from_state_dict_img_only
Loads the model weights from the state dictionary.
[ "Loads", "the", "model", "weights", "from", "the", "state", "dictionary." ]
def load_from_state_dict_img_only(model, state_dict): model_keys_prefixes = [] for (okey, oitem) in model.state_dict().items(): model_keys_prefixes.append(okey.split('.')[0]) new_state_dict = {} index = 0 for (key, item) in state_dict.items(): if (key.startswith('resnet_simclr') or k...
['def', 'load_from_state_dict_img_only(model,', 'state_dict):', 'model_keys_prefixes', '=', '[]', 'for', '(okey,', 'oitem)', 'in', 'model.state_dict().items():', "model_keys_prefixes.append(okey.split('.')[0])", 'new_state_dict', '=', '{}', 'index', '=', '0', 'for', '(key,', 'item)', 'in', 'state_dict.items():', 'if', ...
136,479
lbkchen/deep-learning
tensor_forest.py
RandomForestGraphs.training_graph
training_graph
Constructs a TF graph for training a random forest.
[ "Constructs", "a", "TF", "graph", "for", "training", "a", "random", "forest." ]
def training_graph(self, input_data, input_labels, data_spec=None, epoch=None, **tree_kwargs): data_spec = [constants.DATA_FLOAT] if data_spec is None else data_spec tree_graphs = [] for i in range(self.params.num_trees): with ops.device(self.device_assigner.get_device(i)): seed = self.p...
['def', 'training_graph(self,', 'input_data,', 'input_labels,', 'data_spec=None,', 'epoch=None,', '**tree_kwargs):', 'data_spec', '=', '[constants.DATA_FLOAT]', 'if', 'data_spec', 'is', 'None', 'else', 'data_spec', 'tree_graphs', '=', '[]', 'for', 'i', 'in', 'range(self.params.num_trees):', 'with', 'ops.device(self.dev...
518,667
matsu0228/nlp-jp
patches.py
_Style.pprint_styles
pprint_styles
A class method which returns a string of the available styles.
[ "A", "class", "method", "which", "returns", "a", "string", "of", "the", "available", "styles." ]
def pprint_styles(klass): return _pprint_styles(klass._style_list)
['def', 'pprint_styles(klass):', 'return', '_pprint_styles(klass._style_list)']
789,055
suarez12138/AI-Reversi_IMP_TextDichotomy
offsetbox.py
AuxTransformBox.get_window_extent
get_window_extent
Return the bounding box in display space.
[ "Return", "the", "bounding", "box", "in", "display", "space." ]
def get_window_extent(self, renderer): (w, h, xd, yd) = self.get_extent(renderer) (ox, oy) = self.get_offset() return mtransforms.Bbox.from_bounds(ox - xd, oy - yd, w, h)
['def', 'get_window_extent(self,', 'renderer):', '(w,', 'h,', 'xd,', 'yd)', '=', 'self.get_extent(renderer)', '(ox,', 'oy)', '=', 'self.get_offset()', 'return', 'mtransforms.Bbox.from_bounds(ox', '-', 'xd,', 'oy', '-', 'yd,', 'w,', 'h)']
96,655
Gorilla-Lab-SCUT/frustum-convnet
provider_sample_sunrgbd.py
ProviderDataset.get_center_view_box3d
get_center_view_box3d
Frustum rotation of 3D bounding box corners.
[ "Frustum", "rotation", "of", "3D", "bounding", "box", "corners." ]
def get_center_view_box3d(self, index): box3d = self.box3d_list[index] box3d_center_view = np.copy(box3d) return rotate_pc_along_y(box3d_center_view, self.get_center_view_rot_angle(index))
['def', 'get_center_view_box3d(self,', 'index):', 'box3d', '=', 'self.box3d_list[index]', 'box3d_center_view', '=', 'np.copy(box3d)', 'return', 'rotate_pc_along_y(box3d_center_view,', 'self.get_center_view_rot_angle(index))']
564,805
jimtin/Stock_Comparison
testing.py
get_data_path
get_data_path
Return the path of a data file, these are relative to the current test directory.
[ "Return", "the", "path", "of", "a", "data", "file,", "these", "are", "relative", "to", "the", "current", "test", "directory." ]
def get_data_path(f=''): (_, filename, _, _, _, _) = inspect.getouterframes(inspect.currentframe())[1] base_dir = os.path.abspath(os.path.dirname(filename)) return os.path.join(base_dir, 'data', f)
['def', "get_data_path(f=''):", '(_,', 'filename,', '_,', '_,', '_,', '_)', '=', 'inspect.getouterframes(inspect.currentframe())[1]', 'base_dir', '=', 'os.path.abspath(os.path.dirname(filename))', 'return', 'os.path.join(base_dir,', "'data',", 'f)']
388,351
rifqind/Agent-Programs-3KS1
Py25Queue.py
Queue.full
full
Return True if the queue is full, False otherwise (not reliable!).
[ "Return", "True", "if", "the", "queue", "is", "full,", "False", "otherwise", "(not", "reliable!)." ]
def full(self): self.mutex.acquire() n = self._full() self.mutex.release() return n
['def', 'full(self):', 'self.mutex.acquire()', 'n', '=', 'self._full()', 'self.mutex.release()', 'return', 'n']
46,100
devashish-patel/webcam-motion-detector
guisupport.py
is_event_loop_running_wx
is_event_loop_running_wx
Is the wx event loop running.
[ "Is", "the", "wx", "event", "loop", "running." ]
def is_event_loop_running_wx(app=None): if app is None: app = get_app_wx() if hasattr(app, '_in_event_loop'): return app._in_event_loop else: return app.IsMainLoopRunning()
['def', 'is_event_loop_running_wx(app=None):', 'if', 'app', 'is', 'None:', 'app', '=', 'get_app_wx()', 'if', 'hasattr(app,', "'_in_event_loop'):", 'return', 'app._in_event_loop', 'else:', 'return', 'app.IsMainLoopRunning()']
979,171
sunishsheth2009/ChatterBot
datastructures.py
ContentRange.unset
unset
Sets the units to `None` which indicates that the header should no longer be used.
[ "Sets", "the", "units", "to", "`None`", "which", "indicates", "that", "the", "header", "should", "no", "longer", "be", "used." ]
def unset(self): self.set(None, None, units=None)
['def', 'unset(self):', 'self.set(None,', 'None,', 'units=None)']
483,077
microsoft/InnerEye-DeepLearning
test_scalar_dataset.py
test_load_items_when_channel_missing
test_load_items_when_channel_missing
Test loading file paths from a dataframe when a subject misses a channel.
[ "Test", "loading", "file", "paths", "from", "a", "dataframe", "when", "a", "subject", "misses", "a", "channel." ]
def test_load_items_when_channel_missing() -> None: csv_string = StringIO('subject,channel,path,value\nS1,image1,img11.nii\nS1,image2,img12.nii,True\nS2,image2,image22.nii,False\n') df = pd.read_csv(csv_string, sep=',', dtype=str) items: List[ScalarDataSource] = DataSourceReader(data_frame=df, image_channel...
['def', 'test_load_items_when_channel_missing()', '->', 'None:', 'csv_string', '=', "StringIO('subject,channel,path,value\\nS1,image1,img11.nii\\nS1,image2,img12.nii,True\\nS2,image2,image22.nii,False\\n')", 'df', '=', 'pd.read_csv(csv_string,', "sep=',',", 'dtype=str)', 'items:', 'List[ScalarDataSource]', '=', 'DataSo...
613,666
openvinotoolkit/training_extensions
run_test_command.py
otx_find_testing
otx_find_testing
Performs several options of available otx find.
[ "Performs", "several", "options", "of", "available", "otx", "find." ]
def otx_find_testing(): command_line = ['otx', 'find', '--template'] check_run(command_line) for task in find_supported_tasks: command_line = ['otx', 'find', '--template', '--task', task] check_run(command_line) for backbone_backends in find_supported_backends: command_line = ['o...
['def', 'otx_find_testing():', 'command_line', '=', "['otx',", "'find',", "'--template']", 'check_run(command_line)', 'for', 'task', 'in', 'find_supported_tasks:', 'command_line', '=', "['otx',", "'find',", "'--template',", "'--task',", 'task]', 'check_run(command_line)', 'for', 'backbone_backends', 'in', 'find_support...
919,212
TrellixVulnTeam/Unsupervised_Learning_HFI7
named_commands.py
operate_and_get_next
operate_and_get_next
Accept the current line for execution and fetch the next line relative to the current line from the history for editing.
[ "Accept", "the", "current", "line", "for", "execution", "and", "fetch", "the", "next", "line", "relative", "to", "the", "current", "line", "from", "the", "history", "for", "editing." ]
def operate_and_get_next(event: E) -> None: buff = event.current_buffer new_index = buff.working_index + 1 buff.validate_and_handle() def set_working_index() -> None: if new_index < len(buff._working_lines): buff.working_index = new_index event.app.pre_run_callables.append(set_w...
['def', 'operate_and_get_next(event:', 'E)', '->', 'None:', 'buff', '=', 'event.current_buffer', 'new_index', '=', 'buff.working_index', '+', '1', 'buff.validate_and_handle()', 'def', 'set_working_index()', '->', 'None:', 'if', 'new_index', '<', 'len(buff._working_lines):', 'buff.working_index', '=', 'new_index', 'even...
435,271
NVIDIA-Omniverse/IsaacGymEnvs
rlgames_utils.py
ComplexObsRLGPUEnv.get_env_info
get_env_info
Gets information on the environment's observation, action, and privileged observation (states) spaces.
[ "Gets", "information", "on", "the", "environment's", "observation,", "action,", "and", "privileged", "observation", "(states)", "spaces." ]
def get_env_info(self) -> Dict[str, gym.spaces.Space]: info = {} info['action_space'] = self.env.action_space for (k, v) in self.obs_spec.items(): info[v['space_name']] = self.gen_obs_space(v['names'], v['concat']) return info
['def', 'get_env_info(self)', '->', 'Dict[str,', 'gym.spaces.Space]:', 'info', '=', '{}', "info['action_space']", '=', 'self.env.action_space', 'for', '(k,', 'v)', 'in', 'self.obs_spec.items():', "info[v['space_name']]", '=', "self.gen_obs_space(v['names'],", "v['concat'])", 'return', 'info']
246,698
brain-research/realistic-ssl-evaluation
dataset_utils.py
tf_gcn
tf_gcn
Performs global contrast normalization on a TF tensor of images.
[ "Performs", "global", "contrast", "normalization", "on", "a", "TF", "tensor", "of", "images." ]
def tf_gcn(inp, multiplier=55.0, eps=1e-08): inp -= tf.reduce_mean(inp, axis=[1, 2, 3], keepdims=True) denominator = tf.sqrt(tf.reduce_sum(tf.square(inp), axis=[1, 2, 3], keepdims=True)) denominator /= multiplier denominator = tf.where(tf.less(denominator, tf.constant(eps)), tf.ones_like(denominator), d...
['def', 'tf_gcn(inp,', 'multiplier=55.0,', 'eps=1e-08):', 'inp', '-=', 'tf.reduce_mean(inp,', 'axis=[1,', '2,', '3],', 'keepdims=True)', 'denominator', '=', 'tf.sqrt(tf.reduce_sum(tf.square(inp),', 'axis=[1,', '2,', '3],', 'keepdims=True))', 'denominator', '/=', 'multiplier', 'denominator', '=', 'tf.where(tf.less(denom...
308,995
zehuichen123/AutoAlignV2
prediction_kitti_to_waymo.py
KITTI2Waymo.combine
combine
Combine predictions in waymo format for each sample together.
[ "Combine", "predictions", "in", "waymo", "format", "for", "each", "sample", "together." ]
def combine(self, pathnames): combined = metrics_pb2.Objects() for pathname in pathnames: objects = metrics_pb2.Objects() with open(pathname, 'rb') as f: objects.ParseFromString(f.read()) for o in objects.objects: combined.objects.append(o) return combined
['def', 'combine(self,', 'pathnames):', 'combined', '=', 'metrics_pb2.Objects()', 'for', 'pathname', 'in', 'pathnames:', 'objects', '=', 'metrics_pb2.Objects()', 'with', 'open(pathname,', "'rb')", 'as', 'f:', 'objects.ParseFromString(f.read())', 'for', 'o', 'in', 'objects.objects:', 'combined.objects.append(o)', 'retur...
416,622
rlworkgroup/garage
_dtypes.py
TimeStep.last
last
bool: Whether this step is the last of its episode.
[ "bool:", "Whether", "this", "step", "is", "the", "last", "of", "its", "episode." ]
def last(self): return self.step_type is StepType.TERMINAL or self.step_type is StepType.TIMEOUT
['def', 'last(self):', 'return', 'self.step_type', 'is', 'StepType.TERMINAL', 'or', 'self.step_type', 'is', 'StepType.TIMEOUT']
200,134
tobegit3hub/deep_image_model
flags.py
DEFINE_boolean
DEFINE_boolean
Defines a flag of type 'boolean'.
[ "Defines", "a", "flag", "of", "type", "'boolean'." ]
def DEFINE_boolean(flag_name, default_value, docstring): def str2bool(v): return v.lower() in ('true', 't', '1') _global_parser.add_argument('--' + flag_name, nargs='?', const=True, help=docstring, default=default_value, type=str2bool) _global_parser.add_argument('--no' + flag_name, action='store_f...
['def', 'DEFINE_boolean(flag_name,', 'default_value,', 'docstring):', 'def', 'str2bool(v):', 'return', 'v.lower()', 'in', "('true',", "'t',", "'1')", "_global_parser.add_argument('--'", '+', 'flag_name,', "nargs='?',", 'const=True,', 'help=docstring,', 'default=default_value,', 'type=str2bool)', "_global_parser.add_arg...
183,153
jinfanhahaha/base-cifar-10-recurrent--.github.io
InceptionNet-v2-6.py
CifarData.next_batch
next_batch
return batch_size examples as a batch.
[ "return", "batch_size", "examples", "as", "a", "batch." ]
def next_batch(self, batch_size): end_indicator = self._indicator + batch_size if end_indicator > self._num_examples: if self._need_shuffle: self._shuffle_data() self._indicator = 0 end_indicator = batch_size else: raise Exception('have no more exa...
['def', 'next_batch(self,', 'batch_size):', 'end_indicator', '=', 'self._indicator', '+', 'batch_size', 'if', 'end_indicator', '>', 'self._num_examples:', 'if', 'self._need_shuffle:', 'self._shuffle_data()', 'self._indicator', '=', '0', 'end_indicator', '=', 'batch_size', 'else:', 'raise', "Exception('have", 'no', 'mor...
94,336
TrellixVulnTeam/Unsupervised_Learning_HFI7
numpy_.py
PandasDtype.name
name
A bit-width name for this data-type.
[ "A", "bit-width", "name", "for", "this", "data-type." ]
def name(self) -> str: return self._dtype.name
['def', 'name(self)', '->', 'str:', 'return', 'self._dtype.name']
452,814
JahJajaka/afternoon_cleaner
mobilenet_v2.py
mobilenet_base
mobilenet_base
Creates base of the mobilenet (no pooling and no logits) .
[ "Creates", "base", "of", "the", "mobilenet", "(no", "pooling", "and", "no", "logits)", "." ]
def mobilenet_base(input_tensor, depth_multiplier=1.0, **kwargs): return mobilenet(input_tensor, depth_multiplier=depth_multiplier, base_only=True, **kwargs)
['def', 'mobilenet_base(input_tensor,', 'depth_multiplier=1.0,', '**kwargs):', 'return', 'mobilenet(input_tensor,', 'depth_multiplier=depth_multiplier,', 'base_only=True,', '**kwargs)']
411,902
cheng052/BRNet
anchor_3d_generator.py
Anchor3DRangeGenerator.num_levels
num_levels
int: Number of feature levels that the generator is applied to.
[ "int:", "Number", "of", "feature", "levels", "that", "the", "generator", "is", "applied", "to." ]
def num_levels(self): return len(self.scales)
['def', 'num_levels(self):', 'return', 'len(self.scales)']
409,604
TheCurryMan/MedicAI
debug.py
unspew
unspew
Remove the trace hook installed by spew.
[ "Remove", "the", "trace", "hook", "installed", "by", "spew." ]
def unspew(): sys.settrace(None)
['def', 'unspew():', 'sys.settrace(None)']
648,216
TrellixVulnTeam/Unsupervised_Learning_HFI7
win32.py
_Win32Handles.add_win32_handle
add_win32_handle
Add a Win32 handle to the event loop.
[ "Add", "a", "Win32", "handle", "to", "the", "event", "loop." ]
def add_win32_handle(self, handle: HANDLE, callback: Callable[[], None]) -> None: handle_value = handle.value if handle_value is None: raise ValueError('Invalid handle.') self.remove_win32_handle(handle) loop = get_event_loop() self._handle_callbacks[handle_value] = callback remove_event...
['def', 'add_win32_handle(self,', 'handle:', 'HANDLE,', 'callback:', 'Callable[[],', 'None])', '->', 'None:', 'handle_value', '=', 'handle.value', 'if', 'handle_value', 'is', 'None:', 'raise', "ValueError('Invalid", "handle.')", 'self.remove_win32_handle(handle)', 'loop', '=', 'get_event_loop()', 'self._handle_callback...
435,188
accel-brain/accel-brain-code
labeled_csv_extractor.py
LabeledCSVExtractor.get_label_column
get_label_column
getter of `str` of column of label.
[ "getter", "of", "`str`", "of", "column", "of", "label." ]
def get_label_column(self): return self.__label_column
['def', 'get_label_column(self):', 'return', 'self.__label_column']
6,653
arshpreetsingh/quantopian-machinelearning
sparse.py
SparseArray.sp_index
sp_index
The SparseIndex containing the location of non- ``fill_value`` points.
[ "The", "SparseIndex", "containing", "the", "location", "of", "non-", "``fill_value``", "points." ]
def sp_index(self): return self._sparse_index
['def', 'sp_index(self):', 'return', 'self._sparse_index']
889,834
ZhangAoCanada/RADDet
loader.py
readStereoLeft
readStereoLeft
read stereo left image for verification.
[ "read", "stereo", "left", "image", "for", "verification." ]
def readStereoLeft(img_filename): if os.path.exists(img_filename): stereo_image = cv2.imread(img_filename) left_image = stereo_image[:, :stereo_image.shape[1] // 2, ...][..., ::-1] return left_image else: return None
['def', 'readStereoLeft(img_filename):', 'if', 'os.path.exists(img_filename):', 'stereo_image', '=', 'cv2.imread(img_filename)', 'left_image', '=', 'stereo_image[:,', ':stereo_image.shape[1]', '//', '2,', '...][...,', '::-1]', 'return', 'left_image', 'else:', 'return', 'None']
835,812
alibaba/EasyCV
face_keypoint.py
FaceKeypoint.with_keypoint
with_keypoint
Check if has keypoint_head.
[ "Check", "if", "has", "keypoint_head." ]
def with_keypoint(self): return hasattr(self, 'keypoint_head')
['def', 'with_keypoint(self):', 'return', 'hasattr(self,', "'keypoint_head')"]
546,650
csjunxu/Noisy-As-Clean-TIP2020
req_tracker.py
RequirementTracker.remove
remove
Remove an InstallRequirement from build tracking.
[ "Remove", "an", "InstallRequirement", "from", "build", "tracking." ]
def remove(self, req): assert req.link os.unlink(self._entry_path(req.link)) self._entries.remove(req) logger.debug('Removed %s from build tracker %r', req, self._root)
['def', 'remove(self,', 'req):', 'assert', 'req.link', 'os.unlink(self._entry_path(req.link))', 'self._entries.remove(req)', "logger.debug('Removed", '%s', 'from', 'build', 'tracker', "%r',", 'req,', 'self._root)']
294,761
matsu0228/nlp-jp
storage_uri.py
BucketStorageUri.copy_key
copy_key
Returns newly created key.
[ "Returns", "newly", "created", "key." ]
def copy_key(self, src_bucket_name, src_key_name, metadata=None, src_version_id=None, storage_class='STANDARD', preserve_acl=False, encrypt_key=False, headers=None, query_args=None, src_generation=None): self._check_object_uri('copy_key') dst_bucket = self.get_bucket(validate=False, headers=headers) if src_...
['def', 'copy_key(self,', 'src_bucket_name,', 'src_key_name,', 'metadata=None,', 'src_version_id=None,', "storage_class='STANDARD',", 'preserve_acl=False,', 'encrypt_key=False,', 'headers=None,', 'query_args=None,', 'src_generation=None):', "self._check_object_uri('copy_key')", 'dst_bucket', '=', 'self.get_bucket(valid...
783,894
coder-mano/Shi-Tomasi-Corner-Detector
misc.py
remove_auth_from_url
remove_auth_from_url
Return a copy of url with 'username:password@' removed.
[ "Return", "a", "copy", "of", "url", "with", "'username:password@'", "removed." ]
def remove_auth_from_url(url): return _transform_url(url, _get_netloc)[0]
['def', 'remove_auth_from_url(url):', 'return', '_transform_url(url,', '_get_netloc)[0]']
899,952
Kvatsx/Artificial-Intelligence-Assignments
mathtext.py
MathtextBackend.get_hinting_type
get_hinting_type
Get the FreeType hinting type to use with this particular backend.
[ "Get", "the", "FreeType", "hinting", "type", "to", "use", "with", "this", "particular", "backend." ]
def get_hinting_type(self): return LOAD_NO_HINTING
['def', 'get_hinting_type(self):', 'return', 'LOAD_NO_HINTING']
623
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
mailbox.py
_mboxMMDF.get_file
get_file
Return a file-like representation or raise a KeyError.
[ "Return", "a", "file-like", "representation", "or", "raise", "a", "KeyError." ]
def get_file(self, key, from_=False): (start, stop) = self._lookup(key) self._file.seek(start) if not from_: self._file.readline() return _PartialFile(self._file, self._file.tell(), stop)
['def', 'get_file(self,', 'key,', 'from_=False):', '(start,', 'stop)', '=', 'self._lookup(key)', 'self._file.seek(start)', 'if', 'not', 'from_:', 'self._file.readline()', 'return', '_PartialFile(self._file,', 'self._file.tell(),', 'stop)']
428,844
adamshamsudeen/vision.ai
testtools.py
ContentAccessors.xml
xml
Get an etree if possible.
[ "Get", "an", "etree", "if", "possible." ]
def xml(self): if 'xml' not in self.mimetype: raise AttributeError('Not a XML response (Content-Type: %s)' % self.mimetype) for module in ['xml.etree.ElementTree', 'ElementTree', 'elementtree.ElementTree']: etree = import_string(module, silent=True) if etree is not None: retu...
['def', 'xml(self):', 'if', "'xml'", 'not', 'in', 'self.mimetype:', 'raise', "AttributeError('Not", 'a', 'XML', 'response', '(Content-Type:', "%s)'", '%', 'self.mimetype)', 'for', 'module', 'in', "['xml.etree.ElementTree',", "'ElementTree',", "'elementtree.ElementTree']:", 'etree', '=', 'import_string(module,', 'silent...
944,732
Jittor/JDet
coco.py
COCODataset.save_results
save_results
Convert detection results to COCO json style.
[ "Convert", "detection", "results", "to", "COCO", "json", "style." ]
def save_results(self, results, save_file): def xyxy2xywh(box): (x1, y1, x2, y2) = box.tolist() return [x1, y1, x2 - x1, y2 - y1] json_results = [] for (result, target) in results: img_id = result['img_id'] for (box, score, label) in zip(result['boxes'], result['scores'], re...
['def', 'save_results(self,', 'results,', 'save_file):', 'def', 'xyxy2xywh(box):', '(x1,', 'y1,', 'x2,', 'y2)', '=', 'box.tolist()', 'return', '[x1,', 'y1,', 'x2', '-', 'x1,', 'y2', '-', 'y1]', 'json_results', '=', '[]', 'for', '(result,', 'target)', 'in', 'results:', 'img_id', '=', "result['img_id']", 'for', '(box,', ...
577,642
wandb/wandb
prodigy.py
upload_dataset
upload_dataset
Upload dataset from local database to Weights & Biases.
[ "Upload", "dataset", "from", "local", "database", "to", "Weights", "&", "Biases." ]
def upload_dataset(dataset_name): if wandb.run is None: raise ValueError('You must call wandb.init() before upload_dataset()') with wb_telemetry.context(run=wandb.run) as tel: tel.feature.prodigy = True prodigy_db = util.get_module('prodigy.components.db', required='`prodigy` library is requ...
['def', 'upload_dataset(dataset_name):', 'if', 'wandb.run', 'is', 'None:', 'raise', "ValueError('You", 'must', 'call', 'wandb.init()', 'before', "upload_dataset()')", 'with', 'wb_telemetry.context(run=wandb.run)', 'as', 'tel:', 'tel.feature.prodigy', '=', 'True', 'prodigy_db', '=', "util.get_module('prodigy.components....
941,554
wanhch/CS181-Artificial-Intelligence-I
test_inference.py
InferenceModule.setGhostPositions
setGhostPositions
Sets the position of all ghosts to the values in ghostPositions.
[ "Sets", "the", "position", "of", "all", "ghosts", "to", "the", "values", "in", "ghostPositions." ]
def setGhostPositions(self, gameState, ghostPositions): for (index, pos) in enumerate(ghostPositions): conf = game.Configuration(pos, game.Directions.STOP) gameState.data.agentStates[index + 1] = game.AgentState(conf, False) return gameState
['def', 'setGhostPositions(self,', 'gameState,', 'ghostPositions):', 'for', '(index,', 'pos)', 'in', 'enumerate(ghostPositions):', 'conf', '=', 'game.Configuration(pos,', 'game.Directions.STOP)', 'gameState.data.agentStates[index', '+', '1]', '=', 'game.AgentState(conf,', 'False)', 'return', 'gameState']
220,282
intelligent-environments-lab/CityLearn
wrappers.py
DiscreteActionWrapper.action_space
action_space
Returns action space for discretized actions.
[ "Returns", "action", "space", "for", "discretized", "actions." ]
def action_space(self) -> List[spaces.MultiDiscrete]: if self.env.central_agent: bin_sizes = [] for b in self.bin_sizes: for (_, v) in b.items(): bin_sizes.append(v) action_space = [spaces.MultiDiscrete(bin_sizes)] else: action_space = [spaces.MultiDis...
['def', 'action_space(self)', '->', 'List[spaces.MultiDiscrete]:', 'if', 'self.env.central_agent:', 'bin_sizes', '=', '[]', 'for', 'b', 'in', 'self.bin_sizes:', 'for', '(_,', 'v)', 'in', 'b.items():', 'bin_sizes.append(v)', 'action_space', '=', '[spaces.MultiDiscrete(bin_sizes)]', 'else:', 'action_space', '=', '[spaces...
105,492
aeon-toolkit/aeon
test_datagen.py
test_piecewise_poisson
test_piecewise_poisson
Test piecewise_poisson fuction returns the expected Poisson distributed array.
[ "Test", "piecewise_poisson", "fuction", "returns", "the", "expected", "Poisson", "distributed", "array." ]
def test_piecewise_poisson(lambdas, lengths, random_state, output): assert array_equal(piecewise_poisson(lambdas, lengths, random_state), output)
['def', 'test_piecewise_poisson(lambdas,', 'lengths,', 'random_state,', 'output):', 'assert', 'array_equal(piecewise_poisson(lambdas,', 'lengths,', 'random_state),', 'output)']
399,095
Alexander-Parker/youtube_nlp
message.py
_GetMore.get_message
get_message
Get a getmore message.
[ "Get", "a", "getmore", "message." ]
def get_message(self, dummy0, sock_info, use_cmd=False): ns = _UJOIN % (self.db, self.coll) ctx = sock_info.compression_context if use_cmd: spec = self.as_command(sock_info)[0] if sock_info.op_msg_enabled: (request_id, msg, size, _) = _op_msg(0, spec, self.db, ReadPreference.PRIM...
['def', 'get_message(self,', 'dummy0,', 'sock_info,', 'use_cmd=False):', 'ns', '=', '_UJOIN', '%', '(self.db,', 'self.coll)', 'ctx', '=', 'sock_info.compression_context', 'if', 'use_cmd:', 'spec', '=', 'self.as_command(sock_info)[0]', 'if', 'sock_info.op_msg_enabled:', '(request_id,', 'msg,', 'size,', '_)', '=', '_op_m...
970,463
microsoft/InnerEye-DeepLearning
test_scalar_model.py
test_run_ml_with_segmentation_model
test_run_ml_with_segmentation_model
Test training and testing of segmentation models, when it is started together via run_ml.
[ "Test", "training", "and", "testing", "of", "segmentation", "models,", "when", "it", "is", "started", "together", "via", "run_ml." ]
def test_run_ml_with_segmentation_model(test_output_dirs: OutputFolderForTests) -> None: config = DummyModel() config.num_dataload_workers = 0 config.restrict_subjects = '1' config.test_crop_size = (75, 75, 75) config.inference_on_train_set = False config.inference_on_val_set = True config.i...
['def', 'test_run_ml_with_segmentation_model(test_output_dirs:', 'OutputFolderForTests)', '->', 'None:', 'config', '=', 'DummyModel()', 'config.num_dataload_workers', '=', '0', 'config.restrict_subjects', '=', "'1'", 'config.test_crop_size', '=', '(75,', '75,', '75)', 'config.inference_on_train_set', '=', 'False', 'con...
613,697
gunthercox/ChatterBot
sourcedstring.py
SourcedStringStream.close
close
Close the underlying stream.
[ "Close", "the", "underlying", "stream." ]
def close(self): self.stream.close()
['def', 'close(self):', 'self.stream.close()']
527,354
PaddlePaddle/PARL
policy_distribution.py
PolicyDistribution.entropy
entropy
The entropy of the policy distribution.
[ "The", "entropy", "of", "the", "policy", "distribution." ]
def entropy(self): raise NotImplementedError
['def', 'entropy(self):', 'raise', 'NotImplementedError']
278,051
eora-ai/torchok
base_backbone.py
BaseBackbone.out_encoder_channels
out_encoder_channels
Number of output feature channels - channels after forward_features method.
[ "Number", "of", "output", "feature", "channels", "-", "channels", "after", "forward_features", "method." ]
def out_encoder_channels(self) -> Tuple[int]: if self._out_encoder_channels is None: raise ValueError('TorchOk Backbones must have self._out_feature_channels attribute.') return tuple(self._out_encoder_channels)
['def', 'out_encoder_channels(self)', '->', 'Tuple[int]:', 'if', 'self._out_encoder_channels', 'is', 'None:', 'raise', "ValueError('TorchOk", 'Backbones', 'must', 'have', 'self._out_feature_channels', "attribute.')", 'return', 'tuple(self._out_encoder_channels)']
903,067
ouwei-guo/mit-6.034
lab5.py
hamming_distance
hamming_distance
Given two Points, computes and returns the Hamming distance between them.
[ "Given", "two", "Points,", "computes", "and", "returns", "the", "Hamming", "distance", "between", "them." ]
def hamming_distance(point1, point2): return sum((v1 != v2 for (v1, v2) in zip(point1.coords, point2.coords)))
['def', 'hamming_distance(point1,', 'point2):', 'return', 'sum((v1', '!=', 'v2', 'for', '(v1,', 'v2)', 'in', 'zip(point1.coords,', 'point2.coords)))']
238,759
jimtin/Stock_Comparison
garbage.py
GarbageCollector.is_alive
is_alive
Is the garbage collection thread currently running? Includes checks for process shutdown or fork.
[ "Is", "the", "garbage", "collection", "thread", "currently", "running?", "Includes", "checks", "for", "process", "shutdown", "or", "fork." ]
def is_alive(self): if getpid is None or getpid() != self.pid or self.thread is None or (not self.thread.is_alive()): return False return True
['def', 'is_alive(self):', 'if', 'getpid', 'is', 'None', 'or', 'getpid()', '!=', 'self.pid', 'or', 'self.thread', 'is', 'None', 'or', '(not', 'self.thread.is_alive()):', 'return', 'False', 'return', 'True']
359,663
mpeychev/disentangled-autoencoders
util.py
get_classifier_data_dir
get_classifier_data_dir
Returns the directory of the data to be used for training the linear classifier which evaluates the disentanglement level.
[ "Returns", "the", "directory", "of", "the", "data", "to", "be", "used", "for", "training", "the", "linear", "classifier", "which", "evaluates", "the", "disentanglement", "level." ]
def get_classifier_data_dir(): return os.path.join(get_data_dir(), 'classifier')
['def', 'get_classifier_data_dir():', 'return', 'os.path.join(get_data_dir(),', "'classifier')"]
552,042
Xianpeng919/MonoCon
transforms.py
bbox_mapping
bbox_mapping
Map bboxes from the original image scale to testing scale.
[ "Map", "bboxes", "from", "the", "original", "image", "scale", "to", "testing", "scale." ]
def bbox_mapping(bboxes, img_shape, scale_factor, flip, flip_direction='horizontal'): new_bboxes = bboxes * bboxes.new_tensor(scale_factor) if flip: new_bboxes = bbox_flip(new_bboxes, img_shape, flip_direction) return new_bboxes
['def', 'bbox_mapping(bboxes,', 'img_shape,', 'scale_factor,', 'flip,', "flip_direction='horizontal'):", 'new_bboxes', '=', 'bboxes', '*', 'bboxes.new_tensor(scale_factor)', 'if', 'flip:', 'new_bboxes', '=', 'bbox_flip(new_bboxes,', 'img_shape,', 'flip_direction)', 'return', 'new_bboxes']
653,628
michellesri/cs188
inference.py
MarginalInference.elapseTime
elapseTime
Predict beliefs for a time step elapsing from a gameState.
[ "Predict", "beliefs", "for", "a", "time", "step", "elapsing", "from", "a", "gameState." ]
def elapseTime(self, gameState): if self.index == 1: jointInference.elapseTime(gameState)
['def', 'elapseTime(self,', 'gameState):', 'if', 'self.index', '==', '1:', 'jointInference.elapseTime(gameState)']
223,854
AiIsBetter/computer_vision
torch_ssd_object.py
detect
detect
Inputs will be, a frame, a ssd neural network, and a transformation to be applied on the images, and that will return the frame with the detector rectangle.
[ "Inputs", "will", "be,", "a", "frame,", "a", "ssd", "neural", "network,", "and", "a", "transformation", "to", "be", "applied", "on", "the", "images,", "and", "that", "will", "return", "the", "frame", "with", "the", "detector", "rectangle." ]
def detect(frame, net, transform): (height, width) = frame.shape[:2] frame_t = transform(frame)[0] x = torch.from_numpy(frame_t).permute(2, 0, 1) x = Variable(x.unsqueeze(0)) y = net(x) detections = y.data scale = torch.Tensor([width, height, width, height]) for i in range(detections.siz...
['def', 'detect(frame,', 'net,', 'transform):', '(height,', 'width)', '=', 'frame.shape[:2]', 'frame_t', '=', 'transform(frame)[0]', 'x', '=', 'torch.from_numpy(frame_t).permute(2,', '0,', '1)', 'x', '=', 'Variable(x.unsqueeze(0))', 'y', '=', 'net(x)', 'detections', '=', 'y.data', 'scale', '=', 'torch.Tensor([width,', ...
503,028
yanqi1811/transfer-learning
pytorch_hf_text_classification_model.py
PyTorchHFTextClassificationModel.train
train
Trains the model using the specified text classification dataset.
[ "Trains", "the", "model", "using", "the", "specified", "text", "classification", "dataset." ]
def train(self, dataset, output_dir: str, epochs: int=1, initial_checkpoints=None, learning_rate: float=1e-05, do_eval: bool=True, early_stopping: bool=False, lr_decay: bool=True, seed: int=None, extra_layers: list=None, device: str='cpu', ipex_optimize: bool=True, use_trainer: bool=False, force_download: bool=False, d...
['def', 'train(self,', 'dataset,', 'output_dir:', 'str,', 'epochs:', 'int=1,', 'initial_checkpoints=None,', 'learning_rate:', 'float=1e-05,', 'do_eval:', 'bool=True,', 'early_stopping:', 'bool=False,', 'lr_decay:', 'bool=True,', 'seed:', 'int=None,', 'extra_layers:', 'list=None,', 'device:', "str='cpu',", 'ipex_optimiz...
928,459
Katja-M/Python_NaturalLanguageProcessing
arlstem.py
ARLSTem.suff
suff
remove suffixes from the word's end.
[ "remove", "suffixes", "from", "the", "word's", "end." ]
def suff(self, token): if token.endswith('ك') and len(token) > 3: return token[:-1] if len(token) > 4: for s2 in self.su2: if token.endswith(s2): return token[:-2] if len(token) > 5: for s3 in self.su3: if token.endswith(s3): re...
['def', 'suff(self,', 'token):', 'if', "token.endswith('ك')", 'and', 'len(token)', '>', '3:', 'return', 'token[:-1]', 'if', 'len(token)', '>', '4:', 'for', 's2', 'in', 'self.su2:', 'if', 'token.endswith(s2):', 'return', 'token[:-2]', 'if', 'len(token)', '>', '5:', 'for', 's3', 'in', 'self.su3:', 'if', 'token.endswith(s...
866,941
angsten/pianonet
run.py
Run.checkpoint_method_creator
checkpoint_method_creator
Saves all relevant parts of the current run's training session and state to files within the run directory as an exact checkpoint from which a future run can be restarted without any change in the training outcome.
[ "Saves", "all", "relevant", "parts", "of", "the", "current", "run's", "training", "session", "and", "state", "to", "files", "within", "the", "run", "directory", "as", "an", "exact", "checkpoint", "from", "which", "a", "future", "run", "can", "be", "restarted...
def checkpoint_method_creator(self): def checkpoint(batch=None, logs=None): save_dictionary_to_json_file(dictionary=self.run_description, json_file_path=self.get_run_description_path(run_index=self.get_run_index())) self.save_state() self.save_model() self.save_generator_state() ...
['def', 'checkpoint_method_creator(self):', 'def', 'checkpoint(batch=None,', 'logs=None):', 'save_dictionary_to_json_file(dictionary=self.run_description,', 'json_file_path=self.get_run_description_path(run_index=self.get_run_index()))', 'self.save_state()', 'self.save_model()', 'self.save_generator_state()', 'return',...
769,467
weimin17/Object-Detection_HelmetDetection
loss_layers_test.py
PrecisionAtRecallTest.testLagrangeMultiplierUpdateDirectionWithMultipleRecalls
testLagrangeMultiplierUpdateDirectionWithMultipleRecalls
Runs Lagrange multiplier test with multiple recall values.
[ "Runs", "Lagrange", "multiplier", "test", "with", "multiple", "recall", "values." ]
def testLagrangeMultiplierUpdateDirectionWithMultipleRecalls(self): target_recall = [0.34, 0.66] for surrogate_type in ['xent', 'hinge']: scope_str = 'p-at-r_{}_{}'.format('_'.join([str(recall) for recall in target_recall]), surrogate_type) kwargs = {'target_recall': target_recall, 'dual_rate_fa...
['def', 'testLagrangeMultiplierUpdateDirectionWithMultipleRecalls(self):', 'target_recall', '=', '[0.34,', '0.66]', 'for', 'surrogate_type', 'in', "['xent',", "'hinge']:", 'scope_str', '=', "'p-at-r_{}_{}'.format('_'.join([str(recall)", 'for', 'recall', 'in', 'target_recall]),', 'surrogate_type)', 'kwargs', '=', "{'tar...
763,014
apeterswu/RL4NMT
common_layers.py
conv_block_downsample
conv_block_downsample
Implements a downwards-striding conv block, like Xception exit flow.
[ "Implements", "a", "downwards-striding", "conv", "block,", "like", "Xception", "exit", "flow." ]
def conv_block_downsample(x, kernel, strides, padding, separability=0, name=None, reuse=None): with tf.variable_scope(name, default_name='conv_block_downsample', values=[x], reuse=reuse): hidden_size = int(x.get_shape()[-1]) res = conv_block(x, int(1.25 * hidden_size), [((1, 1), kernel)], padding=pa...
['def', 'conv_block_downsample(x,', 'kernel,', 'strides,', 'padding,', 'separability=0,', 'name=None,', 'reuse=None):', 'with', 'tf.variable_scope(name,', "default_name='conv_block_downsample',", 'values=[x],', 'reuse=reuse):', 'hidden_size', '=', 'int(x.get_shape()[-1])', 'res', '=', 'conv_block(x,', 'int(1.25', '*', ...
331,044
marcsto/rl
utils.py
generate_exp_name
generate_exp_name
Generates an ID (str) for the described experiment using UUID and current date.
[ "Generates", "an", "ID", "(str)", "for", "the", "described", "experiment", "using", "UUID", "and", "current", "date." ]
def generate_exp_name(model_name: str, experiment_name: str) -> str: exp_name = '_'.join((model_name, experiment_name, str(uuid.uuid4())[:8], datetime.now().strftime('%y_%m_%d-%H_%M_%S'))) return exp_name
['def', 'generate_exp_name(model_name:', 'str,', 'experiment_name:', 'str)', '->', 'str:', 'exp_name', '=', "'_'.join((model_name,", 'experiment_name,', 'str(uuid.uuid4())[:8],', "datetime.now().strftime('%y_%m_%d-%H_%M_%S')))", 'return', 'exp_name']
859,480
tusen-ai/SST
groupfree3d_bbox_coder.py
GroupFree3DBBoxCoder.decode
decode
Decode predicted parts to bbox3d.
[ "Decode", "predicted", "parts", "to", "bbox3d." ]
def decode(self, bbox_out, prefix=''): center = bbox_out[f'{prefix}center'] (batch_size, num_proposal) = center.shape[:2] if self.with_rot: dir_class = torch.argmax(bbox_out[f'{prefix}dir_class'], -1) dir_res = torch.gather(bbox_out[f'{prefix}dir_res'], 2, dir_class.unsqueeze(-1)) di...
['def', 'decode(self,', 'bbox_out,', "prefix=''):", 'center', '=', "bbox_out[f'{prefix}center']", '(batch_size,', 'num_proposal)', '=', 'center.shape[:2]', 'if', 'self.with_rot:', 'dir_class', '=', "torch.argmax(bbox_out[f'{prefix}dir_class'],", '-1)', 'dir_res', '=', "torch.gather(bbox_out[f'{prefix}dir_res'],", '2,',...
872,166
SemiUnsupervisedLearning/DGMs_for_semi-unsupervised_
utils.py
softmax
softmax
Compute the softmax of each element along an axis of X.
[ "Compute", "the", "softmax", "of", "each", "element", "along", "an", "axis", "of", "X." ]
def softmax(X, theta=1.0, axis=None): y = np.atleast_2d(X) if axis is None: axis = next((j[0] for j in enumerate(y.shape) if j[1] > 1)) y = y * float(theta) y = y - np.expand_dims(np.max(y, axis=axis), axis) y = np.exp(y) ax_sum = np.expand_dims(np.sum(y, axis=axis), axis) p = y / ax...
['def', 'softmax(X,', 'theta=1.0,', 'axis=None):', 'y', '=', 'np.atleast_2d(X)', 'if', 'axis', 'is', 'None:', 'axis', '=', 'next((j[0]', 'for', 'j', 'in', 'enumerate(y.shape)', 'if', 'j[1]', '>', '1))', 'y', '=', 'y', '*', 'float(theta)', 'y', '=', 'y', '-', 'np.expand_dims(np.max(y,', 'axis=axis),', 'axis)', 'y', '=',...
184,420
openvinotoolkit/training_extensions
ir.py
check_if_quantized
check_if_quantized
Checks if OpenVINO model is already quantized.
[ "Checks", "if", "OpenVINO", "model", "is", "already", "quantized." ]
def check_if_quantized(model: Any) -> bool: nodes = model.get_ops() for op in nodes: if 'FakeQuantize' == op.get_type_name(): return True return False
['def', 'check_if_quantized(model:', 'Any)', '->', 'bool:', 'nodes', '=', 'model.get_ops()', 'for', 'op', 'in', 'nodes:', 'if', "'FakeQuantize'", '==', 'op.get_type_name():', 'return', 'True', 'return', 'False']
918,015
TrellixVulnTeam/Unsupervised_Learning_HFI7
style_transformation.py
SwapLightAndDarkStyleTransformation.transform_attrs
transform_attrs
Return the `Attrs` used when opposite luminosity should be used.
[ "Return", "the", "`Attrs`", "used", "when", "opposite", "luminosity", "should", "be", "used." ]
def transform_attrs(self, attrs: Attrs) -> Attrs: attrs = attrs._replace(color=get_opposite_color(attrs.color)) attrs = attrs._replace(bgcolor=get_opposite_color(attrs.bgcolor)) return attrs
['def', 'transform_attrs(self,', 'attrs:', 'Attrs)', '->', 'Attrs:', 'attrs', '=', 'attrs._replace(color=get_opposite_color(attrs.color))', 'attrs', '=', 'attrs._replace(bgcolor=get_opposite_color(attrs.bgcolor))', 'return', 'attrs']
435,494
Katja-M/Python_NaturalLanguageProcessing
transforms.py
BboxBase.containsy
containsy
Return whether *y* is in the closed (:attr:`y0`, :attr:`y1`) interval.
[ "Return", "whether", "*y*", "is", "in", "the", "closed", "(:attr:`y0`,", ":attr:`y1`)", "interval." ]
def containsy(self, y): (y0, y1) = self.intervaly return y0 <= y <= y1 or y0 >= y >= y1
['def', 'containsy(self,', 'y):', '(y0,', 'y1)', '=', 'self.intervaly', 'return', 'y0', '<=', 'y', '<=', 'y1', 'or', 'y0', '>=', 'y', '>=', 'y1']
864,963
sek788432/Waymo-2D-Object-Detection
seq_example_util.py
context_float_feature
context_float_feature
Converts a numpy float array to a context float feature.
[ "Converts", "a", "numpy", "float", "array", "to", "a", "context", "float", "feature." ]
def context_float_feature(ndarray): feature = tf.train.Feature() for val in ndarray: feature.float_list.value.append(val) return feature
['def', 'context_float_feature(ndarray):', 'feature', '=', 'tf.train.Feature()', 'for', 'val', 'in', 'ndarray:', 'feature.float_list.value.append(val)', 'return', 'feature']
974,956
TonyLianLong/VAI-ReinforcementLearning
egl_renderer.py
create_initialized_headless_egl_display
create_initialized_headless_egl_display
Creates an initialized EGL display directly on a device.
[ "Creates", "an", "initialized", "EGL", "display", "directly", "on", "a", "device." ]
def create_initialized_headless_egl_display(): all_devices = EGL.eglQueryDevicesEXT() selected_device = os.environ.get('EGL_DEVICE_ID', None) if selected_device is None: candidates = all_devices else: device_idx = int(selected_device) if not 0 <= device_idx < len(all_devices): ...
['def', 'create_initialized_headless_egl_display():', 'all_devices', '=', 'EGL.eglQueryDevicesEXT()', 'selected_device', '=', "os.environ.get('EGL_DEVICE_ID',", 'None)', 'if', 'selected_device', 'is', 'None:', 'candidates', '=', 'all_devices', 'else:', 'device_idx', '=', 'int(selected_device)', 'if', 'not', '0', '<=', ...
441,154
rifqind/Agent-Programs-3KS1
mixer_test.py
SoundTypeTest.test_sound__without_arg
test_sound__without_arg
Ensure exception raised for Sound() creation with no argument.
[ "Ensure", "exception", "raised", "for", "Sound()", "creation", "with", "no", "argument." ]
def test_sound__without_arg(self): with self.assertRaises(TypeError): mixer.Sound()
['def', 'test_sound__without_arg(self):', 'with', 'self.assertRaises(TypeError):', 'mixer.Sound()']
45,903
enuguru/artificial_intelligence_and_machine_
flask_login.py
login_fresh
login_fresh
This returns ``True`` if the current login is fresh.
[ "This", "returns", "``True``", "if", "the", "current", "login", "is", "fresh." ]
def login_fresh(): return session.get('_fresh', False)
['def', 'login_fresh():', 'return', "session.get('_fresh',", 'False)']
156,509
zachgitt/computer-vision-panorama
uiutils.py
ClickableImageWidget.push_click
push_click
Draws a point if it is in bounds and adds it to the internal list.
[ "Draws", "a", "point", "if", "it", "is", "in", "bounds", "and", "adds", "it", "to", "the", "internal", "list." ]
def push_click(self, y, x): if self.in_bounds(y, x): self.clicked_points.append((y, x)) self.draw_all_points()
['def', 'push_click(self,', 'y,', 'x):', 'if', 'self.in_bounds(y,', 'x):', 'self.clicked_points.append((y,', 'x))', 'self.draw_all_points()']
470,350
zehuichen123/AutoAlignV2
depth_points.py
DepthPoints.flip
flip
Flip the boxes in BEV along given BEV direction.
[ "Flip", "the", "boxes", "in", "BEV", "along", "given", "BEV", "direction." ]
def flip(self, bev_direction='horizontal'): if bev_direction == 'horizontal': self.tensor[:, 0] = -self.tensor[:, 0] elif bev_direction == 'vertical': self.tensor[:, 1] = -self.tensor[:, 1]
['def', 'flip(self,', "bev_direction='horizontal'):", 'if', 'bev_direction', '==', "'horizontal':", 'self.tensor[:,', '0]', '=', '-self.tensor[:,', '0]', 'elif', 'bev_direction', '==', "'vertical':", 'self.tensor[:,', '1]', '=', '-self.tensor[:,', '1]']
416,649
GatorEducator/GatorMiner
streamlit_web.py
student_senti
student_senti
Page for display individual student's sentiment.
[ "Page", "for", "display", "individual", "student's", "sentiment." ]
def student_senti(input_df): students = st.multiselect(label='Select specific students below:', options=input_df[stu_id].unique()) plots_range = st.sidebar.slider('Select the number of plots per row', 1, 5, value=3) df_selected_stu = ut.return_assignment(input_df, stu_id, students) if len(students) != 0...
['def', 'student_senti(input_df):', 'students', '=', "st.multiselect(label='Select", 'specific', 'students', "below:',", 'options=input_df[stu_id].unique())', 'plots_range', '=', "st.sidebar.slider('Select", 'the', 'number', 'of', 'plots', 'per', "row',", '1,', '5,', 'value=3)', 'df_selected_stu', '=', 'ut.return_assig...
567,422
megvii-research/TreeEnergyLoss
video_helper.py
VideoHelper.cut_video
cut_video
Cut a clip from a video.
[ "Cut", "a", "clip", "from", "a", "video." ]
def cut_video(in_file, out_file, start=None, end=None, vcodec=None, acodec=None, log_level='info', print_cmd=False, **kwargs): options = {'log_level': log_level} if vcodec is None: options['vcodec'] = 'copy' if acodec is None: options['acodec'] = 'copy' if start: options['ss'] = ...
['def', 'cut_video(in_file,', 'out_file,', 'start=None,', 'end=None,', 'vcodec=None,', 'acodec=None,', "log_level='info',", 'print_cmd=False,', '**kwargs):', 'options', '=', "{'log_level':", 'log_level}', 'if', 'vcodec', 'is', 'None:', "options['vcodec']", '=', "'copy'", 'if', 'acodec', 'is', 'None:', "options['acodec'...
951,459
nlp-uoregon/trankit
modeling_tf_utils.py
BeamHypotheses.add
add
Add a new hypothesis to the list.
[ "Add", "a", "new", "hypothesis", "to", "the", "list." ]
def add(self, hyp, sum_logprobs): score = sum_logprobs / len(hyp) ** self.length_penalty if len(self) < self.num_beams or score > self.worst_score: self.beams.append((score, hyp)) if len(self) > self.num_beams: sorted_scores = sorted([(s, idx) for (idx, (s, _)) in enumerate(self.beam...
['def', 'add(self,', 'hyp,', 'sum_logprobs):', 'score', '=', 'sum_logprobs', '/', 'len(hyp)', '**', 'self.length_penalty', 'if', 'len(self)', '<', 'self.num_beams', 'or', 'score', '>', 'self.worst_score:', 'self.beams.append((score,', 'hyp))', 'if', 'len(self)', '>', 'self.num_beams:', 'sorted_scores', '=', 'sorted([(s...
920,180
DYCI2/Dicy2-python
factor_oracle_model.py
FactorOracle.follow_suffix_links_from
follow_suffix_links_from
Suffix path from a given index.
[ "Suffix", "path", "from", "a", "given", "index." ]
def follow_suffix_links_from(self, index_state: int, include_init_state: bool=True) -> List[int]: index_pointed_by_suffix_link = self.suffix_links.get(index_state) if index_pointed_by_suffix_link is None: return [] elif index_pointed_by_suffix_link == 0: if include_init_state: re...
['def', 'follow_suffix_links_from(self,', 'index_state:', 'int,', 'include_init_state:', 'bool=True)', '->', 'List[int]:', 'index_pointed_by_suffix_link', '=', 'self.suffix_links.get(index_state)', 'if', 'index_pointed_by_suffix_link', 'is', 'None:', 'return', '[]', 'elif', 'index_pointed_by_suffix_link', '==', '0:', '...
550,330