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
aws/sagemaker-python-sdk
model.py
TensorFlowModel.register
register
Creates a model package for creating SageMaker models or listing on Marketplace.
[ "Creates", "a", "model", "package", "for", "creating", "SageMaker", "models", "or", "listing", "on", "Marketplace." ]
def register(self, content_types: List[Union[str, PipelineVariable]]=None, response_types: List[Union[str, PipelineVariable]]=None, inference_instances: Optional[List[Union[str, PipelineVariable]]]=None, transform_instances: Optional[List[Union[str, PipelineVariable]]]=None, model_package_name: Optional[Union[str, Pipe...
['def', 'register(self,', 'content_types:', 'List[Union[str,', 'PipelineVariable]]=None,', 'response_types:', 'List[Union[str,', 'PipelineVariable]]=None,', 'inference_instances:', 'Optional[List[Union[str,', 'PipelineVariable]]]=None,', 'transform_instances:', 'Optional[List[Union[str,', 'PipelineVariable]]]=None,', '...
830,555
triaquae/triaquae
forms.py
AdminPasswordChangeForm.save
save
Saves the new password.
[ "Saves", "the", "new", "password." ]
def save(self, commit=True): self.user.set_password(self.cleaned_data['password1']) if commit: self.user.save() return self.user
['def', 'save(self,', 'commit=True):', "self.user.set_password(self.cleaned_data['password1'])", 'if', 'commit:', 'self.user.save()', 'return', 'self.user']
357,071
myothida/Supervised-Machine-Learning
__init__.py
fromtree
fromtree
Convert an XML tree to a plist structure.
[ "Convert", "an", "XML", "tree", "to", "a", "plist", "structure." ]
def fromtree(tree: etree.Element, use_builtin_types: Optional[bool]=None, dict_type: Type[MutableMapping[str, Any]]=dict) -> Any: target = PlistTarget(use_builtin_types=use_builtin_types, dict_type=dict_type) for (action, element) in etree.iterwalk(tree, events=('start', 'end')): if action == 'start': ...
['def', 'fromtree(tree:', 'etree.Element,', 'use_builtin_types:', 'Optional[bool]=None,', 'dict_type:', 'Type[MutableMapping[str,', 'Any]]=dict)', '->', 'Any:', 'target', '=', 'PlistTarget(use_builtin_types=use_builtin_types,', 'dict_type=dict_type)', 'for', '(action,', 'element)', 'in', 'etree.iterwalk(tree,', "events...
361,045
MycroftAI/mycroft-core
base.py
Enclosure.send
send
Send to all registered GUIs.
[ "Send", "to", "all", "registered", "GUIs." ]
def send(self, msg_dict): for connection in GUIWebsocketHandler.clients: try: connection.send(msg_dict) except Exception as e: LOG.exception(repr(e))
['def', 'send(self,', 'msg_dict):', 'for', 'connection', 'in', 'GUIWebsocketHandler.clients:', 'try:', 'connection.send(msg_dict)', 'except', 'Exception', 'as', 'e:', 'LOG.exception(repr(e))']
290,255
kukuruza/shuffler
modify_test.py
Test_syncPolygonIdsWithDb_SyntheticDb.test_noUpdateBecauseOfDifferentObject
test_noUpdateBecauseOfDifferentObject
No update is expected because the objects mismatch.
[ "No", "update", "is", "expected", "because", "the", "objects", "mismatch." ]
def test_noUpdateBecauseOfDifferentObject(self): vals = [(1, 1, 10, 20, 'name1'), (2, 1, 10, 20, 'name2')] vals_ref = [(1, 2, 10, 20, 'name1'), (2, 2, 10, 20, 'name2')] self._insertPolygonsValue(vals, vals_ref) c = self.conn.cursor() args = argparse.Namespace(ref_db_file=self.ref_db_path, epsilon=1....
['def', 'test_noUpdateBecauseOfDifferentObject(self):', 'vals', '=', '[(1,', '1,', '10,', '20,', "'name1'),", '(2,', '1,', '10,', '20,', "'name2')]", 'vals_ref', '=', '[(1,', '2,', '10,', '20,', "'name1'),", '(2,', '2,', '10,', '20,', "'name2')]", 'self._insertPolygonsValue(vals,', 'vals_ref)', 'c', '=', 'self.conn.cur...
933,862
lishunyao97/Pun-GAN
misc_utils.py
print_out
print_out
Similar to print but with support to flush and output to a file.
[ "Similar", "to", "print", "but", "with", "support", "to", "flush", "and", "output", "to", "a", "file." ]
def print_out(s, f=None, new_line=True): if isinstance(s, bytes): s = s.decode('utf-8') if f: f.write(s.encode('utf-8')) if new_line: f.write(b'\n') out_s = s.encode('utf-8') if not isinstance(out_s, str): out_s = out_s.decode('utf-8') print(out_s, end='',...
['def', 'print_out(s,', 'f=None,', 'new_line=True):', 'if', 'isinstance(s,', 'bytes):', 's', '=', "s.decode('utf-8')", 'if', 'f:', "f.write(s.encode('utf-8'))", 'if', 'new_line:', "f.write(b'\\n')", 'out_s', '=', "s.encode('utf-8')", 'if', 'not', 'isinstance(out_s,', 'str):', 'out_s', '=', "out_s.decode('utf-8')", 'pri...
818,766
nicknochnack/RealTimeSignLanguageTFJS
bert_token_classifier_test.py
BertTokenClassifierTest.test_bert_trainer_tensor_call
test_bert_trainer_tensor_call
Validate that the Keras object can be invoked.
[ "Validate", "that", "the", "Keras", "object", "can", "be", "invoked." ]
def test_bert_trainer_tensor_call(self): test_network = networks.BertEncoder(vocab_size=100, num_layers=2, max_sequence_length=2) bert_trainer_model = bert_token_classifier.BertTokenClassifier(test_network, num_classes=2) word_ids = tf.constant([[1, 1], [2, 2]], dtype=tf.int32) mask = tf.constant([[1, 1...
['def', 'test_bert_trainer_tensor_call(self):', 'test_network', '=', 'networks.BertEncoder(vocab_size=100,', 'num_layers=2,', 'max_sequence_length=2)', 'bert_trainer_model', '=', 'bert_token_classifier.BertTokenClassifier(test_network,', 'num_classes=2)', 'word_ids', '=', 'tf.constant([[1,', '1],', '[2,', '2]],', 'dtyp...
850,417
sshaoshuai/PointRCNN
fastai_optim.py
OptimWrapper.read_defaults
read_defaults
Read the values inside the optimizer for the hyper-parameters.
[ "Read", "the", "values", "inside", "the", "optimizer", "for", "the", "hyper-parameters." ]
def read_defaults(self) -> None: self._beta = None if 'lr' in self.opt_keys: self._lr = self.read_val('lr') if 'momentum' in self.opt_keys: self._mom = self.read_val('momentum') if 'alpha' in self.opt_keys: self._beta = self.read_val('alpha') if 'betas' in self.opt_keys: ...
['def', 'read_defaults(self)', '->', 'None:', 'self._beta', '=', 'None', 'if', "'lr'", 'in', 'self.opt_keys:', 'self._lr', '=', "self.read_val('lr')", 'if', "'momentum'", 'in', 'self.opt_keys:', 'self._mom', '=', "self.read_val('momentum')", 'if', "'alpha'", 'in', 'self.opt_keys:', 'self._beta', '=', "self.read_val('al...
781,277
sek788432/Waymo-2D-Object-Detection
utils.py
list_t_bxn_to_list_b_txn
list_t_bxn_to_list_b_txn
Convert a length T list of BxN numpy tensors of length B list of TxN numpy tensors.
[ "Convert", "a", "length", "T", "list", "of", "BxN", "numpy", "tensors", "of", "length", "B", "list", "of", "TxN", "numpy", "tensors." ]
def list_t_bxn_to_list_b_txn(values_t_bxn): T = len(values_t_bxn) (B, N) = values_t_bxn[0].shape values_b_txn = [] for b in range(B): values_pb_txn = np.zeros([T, N]) for t in range(T): values_pb_txn[t, :] = values_t_bxn[t][b, :] values_b_txn.append(values_pb_txn) ...
['def', 'list_t_bxn_to_list_b_txn(values_t_bxn):', 'T', '=', 'len(values_t_bxn)', '(B,', 'N)', '=', 'values_t_bxn[0].shape', 'values_b_txn', '=', '[]', 'for', 'b', 'in', 'range(B):', 'values_pb_txn', '=', 'np.zeros([T,', 'N])', 'for', 't', 'in', 'range(T):', 'values_pb_txn[t,', ':]', '=', 'values_t_bxn[t][b,', ':]', 'v...
974,458
Kvatsx/Artificial-Intelligence-Assignments
test_magic.py
test_macro_run
test_macro_run
Test that we can run a multi-line macro successfully.
[ "Test", "that", "we", "can", "run", "a", "multi-line", "macro", "successfully." ]
def test_macro_run(): ip = get_ipython() ip.history_manager.reset() cmds = ['a=10', 'a+=1', 'print(a)', '%macro test 2-3'] for cmd in cmds: ip.run_cell(cmd, store_history=True) nt.assert_equal(ip.user_ns['test'].value, 'a+=1\nprint(a)\n') with tt.AssertPrints('12'): ip.run_cell('...
['def', 'test_macro_run():', 'ip', '=', 'get_ipython()', 'ip.history_manager.reset()', 'cmds', '=', "['a=10',", "'a+=1',", "'print(a)',", "'%macro", 'test', "2-3']", 'for', 'cmd', 'in', 'cmds:', 'ip.run_cell(cmd,', 'store_history=True)', "nt.assert_equal(ip.user_ns['test'].value,", "'a+=1\\nprint(a)\\n')", 'with', "tt....
38,434
yinyunie/ScenePriors
distributed.py
run
run
Runs a function from a child process.
[ "Runs", "a", "function", "from", "a", "child", "process." ]
def run(proc_rank, world_size, port, error_queue, fun, fun_args, fun_kwargs): try: init_process_group(proc_rank, world_size, port) fun(*fun_args, **fun_kwargs) except: error_queue.put(traceback.format_exc()) finally: destroy_process_group()
['def', 'run(proc_rank,', 'world_size,', 'port,', 'error_queue,', 'fun,', 'fun_args,', 'fun_kwargs):', 'try:', 'init_process_group(proc_rank,', 'world_size,', 'port)', 'fun(*fun_args,', '**fun_kwargs)', 'except:', 'error_queue.put(traceback.format_exc())', 'finally:', 'destroy_process_group()']
330,267
neurospin/pylearn-parsimony
estimators.py
LogisticRegressionEstimator.predict
predict
Return a predicted y corresponding to the X given and the beta previously determined.
[ "Return", "a", "predicted", "y", "corresponding", "to", "the", "X", "given", "and", "the", "beta", "previously", "determined." ]
def predict(self, X): X = check_arrays(X) prob = self.predict_probability(X) y = np.ones((X.shape[0], 1)) y[prob < 0.5] = 0.0 return y
['def', 'predict(self,', 'X):', 'X', '=', 'check_arrays(X)', 'prob', '=', 'self.predict_probability(X)', 'y', '=', 'np.ones((X.shape[0],', '1))', 'y[prob', '<', '0.5]', '=', '0.0', 'return', 'y']
819,883
juliancervos/stdp-nmnist
annotate.py
load_state
load_state
Load the annotation state stored in filename.
[ "Load", "the", "annotation", "state", "stored", "in", "filename." ]
def load_state(filename): with open(filename, 'rb') as input_state_file: loaded_state = pickle.load(input_state_file) return loaded_state
['def', 'load_state(filename):', 'with', 'open(filename,', "'rb')", 'as', 'input_state_file:', 'loaded_state', '=', 'pickle.load(input_state_file)', 'return', 'loaded_state']
384,108
gunthercox/ChatterBot
utils.py
Cycler.current
current
Returns the current item.
[ "Returns", "the", "current", "item." ]
def current(self): return self.items[self.pos]
['def', 'current(self):', 'return', 'self.items[self.pos]']
479,400
neurospin/pylearn-parsimony
grad.py
L2.grad
grad
Sub-gradient of the function f(x) = |x|_2, where |x|_2 is the L2-norm.
[ "Sub-gradient", "of", "the", "function", "f(x)", "=", "|x|_2,", "where", "|x|_2", "is", "the", "L2-norm." ]
def grad(self, x): norm_beta = norm2(x) if norm_beta > TOLERANCE: return x * (1.0 / norm_beta) else: D = x.shape[0] u = self.rng(D, 1) * 2.0 - 1.0 norm_u = norm2(u) a = self.rng() return self.l * (a / norm_u) * u
['def', 'grad(self,', 'x):', 'norm_beta', '=', 'norm2(x)', 'if', 'norm_beta', '>', 'TOLERANCE:', 'return', 'x', '*', '(1.0', '/', 'norm_beta)', 'else:', 'D', '=', 'x.shape[0]', 'u', '=', 'self.rng(D,', '1)', '*', '2.0', '-', '1.0', 'norm_u', '=', 'norm2(u)', 'a', '=', 'self.rng()', 'return', 'self.l', '*', '(a', '/', '...
820,011
paulorauber/rl
test_transforms.py
test_transform_parent_cache
test_transform_parent_cache
Tests the caching and uncaching of the transformed envs.
[ "Tests", "the", "caching", "and", "uncaching", "of", "the", "transformed", "envs." ]
def test_transform_parent_cache(): env = TransformedEnv(ContinuousActionVecMockEnv(), FrameSkipTransform(3)) assert type(env.transform.parent.transform) is Compose and len(env.transform.parent.transform) == 0 transform = env.transform parent1 = env.transform.parent parent2 = env.transform.parent ...
['def', 'test_transform_parent_cache():', 'env', '=', 'TransformedEnv(ContinuousActionVecMockEnv(),', 'FrameSkipTransform(3))', 'assert', 'type(env.transform.parent.transform)', 'is', 'Compose', 'and', 'len(env.transform.parent.transform)', '==', '0', 'transform', '=', 'env.transform', 'parent1', '=', 'env.transform.pa...
858,440
NVIDIA-Omniverse/IsaacGymEnvs
reformat.py
omegaconf_to_dict
omegaconf_to_dict
Converts an omegaconf DictConfig to a python Dict, respecting variable interpolation.
[ "Converts", "an", "omegaconf", "DictConfig", "to", "a", "python", "Dict,", "respecting", "variable", "interpolation." ]
def omegaconf_to_dict(d: DictConfig) -> Dict: ret = {} for (k, v) in d.items(): if isinstance(v, DictConfig): ret[k] = omegaconf_to_dict(v) else: ret[k] = v return ret
['def', 'omegaconf_to_dict(d:', 'DictConfig)', '->', 'Dict:', 'ret', '=', '{}', 'for', '(k,', 'v)', 'in', 'd.items():', 'if', 'isinstance(v,', 'DictConfig):', 'ret[k]', '=', 'omegaconf_to_dict(v)', 'else:', 'ret[k]', '=', 'v', 'return', 'ret']
246,692
explosion/spacy-models
util.py
apply_transition_sequence
apply_transition_sequence
Perform a series of pre-specified transitions, to put the parser in a desired state.
[ "Perform", "a", "series", "of", "pre-specified", "transitions,", "to", "put", "the", "parser", "in", "a", "desired", "state." ]
def apply_transition_sequence(parser, doc, sequence): for action_name in sequence: if '-' in action_name: (move, label) = action_name.split('-') parser.add_label(label) with parser.step_through(doc) as stepwise: for transition in sequence: stepwise.transition(...
['def', 'apply_transition_sequence(parser,', 'doc,', 'sequence):', 'for', 'action_name', 'in', 'sequence:', 'if', "'-'", 'in', 'action_name:', '(move,', 'label)', '=', "action_name.split('-')", 'parser.add_label(label)', 'with', 'parser.step_through(doc)', 'as', 'stepwise:', 'for', 'transition', 'in', 'sequence:', 'ste...
894,447
nmndeep/robust-segmentation
infer.py
worse_case_eval
worse_case_eval
Compute worse case across 4-losses in SEA.
[ "Compute", "worse", "case", "across", "4-losses", "in", "SEA." ]
def worse_case_eval(data_loder, l_output, n_cls=21, ignore_index=-1): acc = 0 n_ex = 0 int_cls = torch.zeros(n_cls) union_cls = torch.zeros(n_cls) aa = [l_output] final_acc_1 = None final_acc_2 = None class_wise_logits = torch.stack(l_output) aaacc = [] ious = [] unions = [] ...
['def', 'worse_case_eval(data_loder,', 'l_output,', 'n_cls=21,', 'ignore_index=-1):', 'acc', '=', '0', 'n_ex', '=', '0', 'int_cls', '=', 'torch.zeros(n_cls)', 'union_cls', '=', 'torch.zeros(n_cls)', 'aa', '=', '[l_output]', 'final_acc_1', '=', 'None', 'final_acc_2', '=', 'None', 'class_wise_logits', '=', 'torch.stack(l...
826,209
scikit-learn/scikit-learn
test_plot.py
test_curve_display_parameters_validation
test_curve_display_parameters_validation
Check that we raise a proper error when passing invalid parameters.
[ "Check", "that", "we", "raise", "a", "proper", "error", "when", "passing", "invalid", "parameters." ]
def test_curve_display_parameters_validation(pyplot, data, params, err_type, err_msg, CurveDisplay, specific_params): (X, y) = data estimator = DecisionTreeClassifier(random_state=0) with pytest.raises(err_type, match=err_msg): CurveDisplay.from_estimator(estimator, X, y, **specific_params, **params...
['def', 'test_curve_display_parameters_validation(pyplot,', 'data,', 'params,', 'err_type,', 'err_msg,', 'CurveDisplay,', 'specific_params):', '(X,', 'y)', '=', 'data', 'estimator', '=', 'DecisionTreeClassifier(random_state=0)', 'with', 'pytest.raises(err_type,', 'match=err_msg):', 'CurveDisplay.from_estimator(estimato...
853,790
matsu0228/nlp-jp
cmdshell.py
LocalClient.put_file
put_file
Copy a file from one directory to another.
[ "Copy", "a", "file", "from", "one", "directory", "to", "another." ]
def put_file(self, src, dst): shutil.copyfile(src, dst)
['def', 'put_file(self,', 'src,', 'dst):', 'shutil.copyfile(src,', 'dst)']
784,884
zihuitang/medical_AI_platform
pytree.py
BasePattern.match_seq
match_seq
Does this pattern exactly match a sequence of nodes? Default implementation for non-wildcard patterns.
[ "Does", "this", "pattern", "exactly", "match", "a", "sequence", "of", "nodes?", "Default", "implementation", "for", "non-wildcard", "patterns." ]
def match_seq(self, nodes, results=None): if len(nodes) != 1: return False return self.match(nodes[0], results)
['def', 'match_seq(self,', 'nodes,', 'results=None):', 'if', 'len(nodes)', '!=', '1:', 'return', 'False', 'return', 'self.match(nodes[0],', 'results)']
283,004
rudranil723/mini-main
test_mplot3d.py
test_pan
test_pan
Test mouse panning using the middle mouse button.
[ "Test", "mouse", "panning", "using", "the", "middle", "mouse", "button." ]
def test_pan(): def convert_lim(dmin, dmax): center = (dmin + dmax) / 2 range_ = dmax - dmin return (center, range_) ax = plt.figure().add_subplot(projection='3d') ax.scatter(0, 0, 0) ax.figure.canvas.draw() (x_center0, x_range0) = convert_lim(*ax.get_xlim3d()) (y_center...
['def', 'test_pan():', 'def', 'convert_lim(dmin,', 'dmax):', 'center', '=', '(dmin', '+', 'dmax)', '/', '2', 'range_', '=', 'dmax', '-', 'dmin', 'return', '(center,', 'range_)', 'ax', '=', "plt.figure().add_subplot(projection='3d')", 'ax.scatter(0,', '0,', '0)', 'ax.figure.canvas.draw()', '(x_center0,', 'x_range0)', '=...
320,469
ilya16/MultINN
auxiliary.py
get_current_scope
get_current_scope
Returns current TF scope.
[ "Returns", "current", "TF", "scope." ]
def get_current_scope(): current_name_scope = tf.get_default_graph().get_name_scope() current_name_scope += '/' if current_name_scope else '' return current_name_scope
['def', 'get_current_scope():', 'current_name_scope', '=', 'tf.get_default_graph().get_name_scope()', 'current_name_scope', '+=', "'/'", 'if', 'current_name_scope', 'else', "''", 'return', 'current_name_scope']
644,364
ZumoLabs/zpy
client_util.py
convert_size
convert_size
Converts a number of bytes into a pretty string.
[ "Converts", "a", "number", "of", "bytes", "into", "a", "pretty", "string." ]
def convert_size(size_bytes: int): if size_bytes == 0: return '0B' size_name = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB') i = int(math.floor(math.log(size_bytes, 1024))) p = math.pow(1024, i) s = round(size_bytes / p, 2) return '%s %s' % (s, size_name[i])
['def', 'convert_size(size_bytes:', 'int):', 'if', 'size_bytes', '==', '0:', 'return', "'0B'", 'size_name', '=', "('B',", "'KB',", "'MB',", "'GB',", "'TB',", "'PB',", "'EB',", "'ZB',", "'YB')", 'i', '=', 'int(math.floor(math.log(size_bytes,', '1024)))', 'p', '=', 'math.pow(1024,', 'i)', 's', '=', 'round(size_bytes', '/...
971,993
google-research/batch_rl
fixed_replay_runner_test.py
FixedReplayRunnerIntegrationTest.testIntegrationFixedReplayREM
testIntegrationFixedReplayREM
Test the FixedReplayMultiHeadDQN agent.
[ "Test", "the", "FixedReplayMultiHeadDQN", "agent." ]
def testIntegrationFixedReplayREM(self): assert FLAGS.replay_dir is not None, 'Please provide a replay directory' tf.logging.info('####### Training the REM agent #####') tf.logging.info('####### REM base_dir: {}'.format(FLAGS.base_dir)) tf.logging.info('####### replay_dir: {}'.format(FLAGS.replay_dir))...
['def', 'testIntegrationFixedReplayREM(self):', 'assert', 'FLAGS.replay_dir', 'is', 'not', 'None,', "'Please", 'provide', 'a', 'replay', "directory'", "tf.logging.info('#######", 'Training', 'the', 'REM', 'agent', "#####')", "tf.logging.info('#######", 'REM', 'base_dir:', "{}'.format(FLAGS.base_dir))", "tf.logging.info...
105,898
srai-lab/srai
embedder.py
GTFS2VecEmbedder.save
save
Save the model to a directory.
[ "Save", "the", "model", "to", "a", "directory." ]
def save(self, path: Union[Path, str]) -> None: embedder_config = {'hidden_size': self._hidden_size, 'embedding_size': self._embedding_size, 'skip_autoencoder': self._skip_autoencoder} self._save(path, embedder_config)
['def', 'save(self,', 'path:', 'Union[Path,', 'str])', '->', 'None:', 'embedder_config', '=', "{'hidden_size':", 'self._hidden_size,', "'embedding_size':", 'self._embedding_size,', "'skip_autoencoder':", 'self._skip_autoencoder}', 'self._save(path,', 'embedder_config)']
371,860
enuguru/artificial_intelligence_and_machine_learning
wrappers.py
BaseRequest.base_url
base_url
Like :attr:`url` but without the querystring See also: :attr:`trusted_hosts`.
[ "Like", ":attr:`url`", "but", "without", "the", "querystring", "See", "also:", ":attr:`trusted_hosts`." ]
def base_url(self): return get_current_url(self.environ, strip_querystring=True, trusted_hosts=self.trusted_hosts)
['def', 'base_url(self):', 'return', 'get_current_url(self.environ,', 'strip_querystring=True,', 'trusted_hosts=self.trusted_hosts)']
132,485
gunthercox/ChatterBot
collections.py
MappedCollection.set
set
Add an item by value, consulting the keyfunc for the key.
[ "Add", "an", "item", "by", "value,", "consulting", "the", "keyfunc", "for", "the", "key." ]
def set(self, value, _sa_initiator=None): key = self.keyfunc(value) self.__setitem__(key, value, _sa_initiator)
['def', 'set(self,', 'value,', '_sa_initiator=None):', 'key', '=', 'self.keyfunc(value)', 'self.__setitem__(key,', 'value,', '_sa_initiator)']
481,231
surafelml/adapt-mnmt
tokenizer.py
Tokenizer.detokenize_stream
detokenize_stream
Detokenizes a stream of sentences.
[ "Detokenizes", "a", "stream", "of", "sentences." ]
def detokenize_stream(self, input_stream=sys.stdin, output_stream=sys.stdout, delimiter=' '): for line in input_stream: tokens = line.strip().split(delimiter) string = self.detokenize(tokens) print_bytes(tf.compat.as_bytes(string), stream=output_stream)
['def', 'detokenize_stream(self,', 'input_stream=sys.stdin,', 'output_stream=sys.stdout,', "delimiter='", "'):", 'for', 'line', 'in', 'input_stream:', 'tokens', '=', 'line.strip().split(delimiter)', 'string', '=', 'self.detokenize(tokens)', 'print_bytes(tf.compat.as_bytes(string),', 'stream=output_stream)']
407,830
open-mmlab/mmrotate
test_rutils.py
test_rotated_anchor_inside_flags
test_rotated_anchor_inside_flags
Test rotated anchor inside flags.
[ "Test", "rotated", "anchor", "inside", "flags." ]
def test_rotated_anchor_inside_flags(): from mmrotate.core.anchor import rotated_anchor_inside_flags flat_ranchors = torch.tensor([[0.0, 0.0, 10.0, 10.0, 0.0], [95.0, 0.0, 10.0, 10.0, 0.0], [0.0, 100.0, 10.0, 10.0, 0.0], [101.0, 100.0, 10.0, 10.0, 0.0]]) valid_flags = torch.tensor([1, 1, 0, 1]) img_shap...
['def', 'test_rotated_anchor_inside_flags():', 'from', 'mmrotate.core.anchor', 'import', 'rotated_anchor_inside_flags', 'flat_ranchors', '=', 'torch.tensor([[0.0,', '0.0,', '10.0,', '10.0,', '0.0],', '[95.0,', '0.0,', '10.0,', '10.0,', '0.0],', '[0.0,', '100.0,', '10.0,', '10.0,', '0.0],', '[101.0,', '100.0,', '10.0,',...
625,266
CAMeL-Lab/camel_tools
test_transliterate.py
TestTransliteratorInit.test_init_valid_marker2
test_init_valid_marker2
Test that init doesn't raise an error when given a valid marker.
[ "Test", "that", "init", "doesn't", "raise", "an", "error", "when", "given", "a", "valid", "marker." ]
def test_init_valid_marker2(self): assert Transliterator(TEST_MAPPER, u'@@LAT@@')
['def', 'test_init_valid_marker2(self):', 'assert', 'Transliterator(TEST_MAPPER,', "u'@@LAT@@')"]
411,247
Zhany829/CS540--Introduction-to-Artificial-
dataloader.py
download_url
download_url
Download a file from a url and place it in folder.
[ "Download", "a", "file", "from", "a", "url", "and", "place", "it", "in", "folder." ]
def download_url(url, folder): fpath = os.path.join(os.path.expanduser(folder), os.path.basename(url)) os.makedirs(os.path.expanduser(folder), exist_ok=True) if os.path.exists(fpath): return try: print('Downloading ' + url + ' to ' + fpath) urllib.request.urlretrieve(url, fpath, ...
['def', 'download_url(url,', 'folder):', 'fpath', '=', 'os.path.join(os.path.expanduser(folder),', 'os.path.basename(url))', 'os.makedirs(os.path.expanduser(folder),', 'exist_ok=True)', 'if', 'os.path.exists(fpath):', 'return', 'try:', "print('Downloading", "'", '+', 'url', '+', "'", 'to', "'", '+', 'fpath)', 'urllib.r...
192,830
loicmarie/hands-detection
pixelda_model.py
dcgan_generator
dcgan_generator
Transforms the visual style of the input images.
[ "Transforms", "the", "visual", "style", "of", "the", "input", "images." ]
def dcgan_generator(images, output_shape, hparams, scope=None): if not isinstance(output_shape, (tuple, list)): raise ValueError('output_shape must be a tuple or list.') elif len(output_shape) != 3: raise ValueError('output_shape must have three elements.') if output_shape[0] != output_shape...
['def', 'dcgan_generator(images,', 'output_shape,', 'hparams,', 'scope=None):', 'if', 'not', 'isinstance(output_shape,', '(tuple,', 'list)):', 'raise', "ValueError('output_shape", 'must', 'be', 'a', 'tuple', 'or', "list.')", 'elif', 'len(output_shape)', '!=', '3:', 'raise', "ValueError('output_shape", 'must', 'have', '...
574,604
s3prl/s3prl
dataset.py
KaldiData.load_wav
load_wav
Load wavfile given recid, start time and end time.
[ "Load", "wavfile", "given", "recid,", "start", "time", "and", "end", "time." ]
def load_wav(self, recid, start=0, end=None): (data, rate) = self._load_wav(self.wavs[recid], start, end) return (data, rate)
['def', 'load_wav(self,', 'recid,', 'start=0,', 'end=None):', '(data,', 'rate)', '=', 'self._load_wav(self.wavs[recid],', 'start,', 'end)', 'return', '(data,', 'rate)']
327,442
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
config.py
load_config
load_config
Loads a dictionary from configuration file.
[ "Loads", "a", "dictionary", "from", "configuration", "file." ]
def load_config(path): return toml.load(path)
['def', 'load_config(path):', 'return', 'toml.load(path)']
11,898
rudranil723/mini-main
sounddevice.py
_StreamBase.device
device
IDs of the input/output device.
[ "IDs", "of", "the", "input/output", "device." ]
def device(self): return self._device
['def', 'device(self):', 'return', 'self._device']
314,061
TrellixVulnTeam/Unsupervised_Learning_HFI7
handlers.py
PUBHandler.emit
emit
Emit a log message on my socket.
[ "Emit", "a", "log", "message", "on", "my", "socket." ]
def emit(self, record): try: (topic, record.msg) = record.msg.split(TOPIC_DELIM, 1) except Exception: topic = '' try: bmsg = cast_bytes(self.format(record)) except Exception: self.handleError(record) return topic_list = [] if self.root_topic: topic...
['def', 'emit(self,', 'record):', 'try:', '(topic,', 'record.msg)', '=', 'record.msg.split(TOPIC_DELIM,', '1)', 'except', 'Exception:', 'topic', '=', "''", 'try:', 'bmsg', '=', 'cast_bytes(self.format(record))', 'except', 'Exception:', 'self.handleError(record)', 'return', 'topic_list', '=', '[]', 'if', 'self.root_topi...
438,101
TrellixVulnTeam/Unsupervised_Learning_HFI7
test_online_lda.py
test_dirichlet_expectation
test_dirichlet_expectation
Test Cython version of Dirichlet expectation calculation.
[ "Test", "Cython", "version", "of", "Dirichlet", "expectation", "calculation." ]
def test_dirichlet_expectation(): x = np.logspace(-100, 10, 10000) expectation = np.empty_like(x) _dirichlet_expectation_1d(x, 0, expectation) assert_allclose(expectation, np.exp(psi(x) - psi(np.sum(x))), atol=1e-19) x = x.reshape(100, 100) assert_allclose(_dirichlet_expectation_2d(x), psi(x) - ...
['def', 'test_dirichlet_expectation():', 'x', '=', 'np.logspace(-100,', '10,', '10000)', 'expectation', '=', 'np.empty_like(x)', '_dirichlet_expectation_1d(x,', '0,', 'expectation)', 'assert_allclose(expectation,', 'np.exp(psi(x)', '-', 'psi(np.sum(x))),', 'atol=1e-19)', 'x', '=', 'x.reshape(100,', '100)', 'assert_allc...
436,769
pranjaldatta/PyVision
toymaker.py
Geppetto.add
add
Adds a toy that will be rendered.
[ "Adds", "a", "toy", "that", "will", "be", "rendered." ]
def add(self, toy): self.toys.append(toy) self.frames = max(self.frames, toy.frames)
['def', 'add(self,', 'toy):', 'self.toys.append(toy)', 'self.frames', '=', 'max(self.frames,', 'toy.frames)']
815,952
RE-OWOD/RE-OWOD
logger.py
setup_logger
setup_logger
Initialize the detectron2 logger and set its verbosity level to "DEBUG".
[ "Initialize", "the", "detectron2", "logger", "and", "set", "its", "verbosity", "level", "to", "\"DEBUG\"." ]
def setup_logger(output=None, distributed_rank=0, *, color=True, name='detectron2', abbrev_name=None): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) logger.propagate = False if abbrev_name is None: abbrev_name = 'd2' if name == 'detectron2' else name plain_formatter = loggi...
['def', 'setup_logger(output=None,', 'distributed_rank=0,', '*,', 'color=True,', "name='detectron2',", 'abbrev_name=None):', 'logger', '=', 'logging.getLogger(name)', 'logger.setLevel(logging.DEBUG)', 'logger.propagate', '=', 'False', 'if', 'abbrev_name', 'is', 'None:', 'abbrev_name', '=', "'d2'", 'if', 'name', '==', "...
849,125
alexlee-gk/slac
slac_agent.py
SlacAgent.critic_loss
critic_loss
Computes the critic loss for SAC training.
[ "Computes", "the", "critic", "loss", "for", "SAC", "training." ]
def critic_loss(self, time_steps, actions, next_time_steps, actor_next_time_steps, td_errors_loss_fn, gamma=1.0, reward_scale_factor=1.0, weights=None): with tf.name_scope('critic_loss'): if self._critic_input_stop_gradient: time_steps = tf.nest.map_structure(tf.stop_gradient, time_steps) ...
['def', 'critic_loss(self,', 'time_steps,', 'actions,', 'next_time_steps,', 'actor_next_time_steps,', 'td_errors_loss_fn,', 'gamma=1.0,', 'reward_scale_factor=1.0,', 'weights=None):', 'with', "tf.name_scope('critic_loss'):", 'if', 'self._critic_input_stop_gradient:', 'time_steps', '=', 'tf.nest.map_structure(tf.stop_gr...
878,189
tslearn-team/tslearn
neighbors.py
KNeighborsTimeSeries.fit
fit
Fit the model using X as training data Parameters ---------- X : array-like, shape (n_ts, sz, d) Training data.
[ "Fit", "the", "model", "using", "X", "as", "training", "data", "Parameters", "----------", "X", ":", "array-like,", "shape", "(n_ts,", "sz,", "d)", "Training", "data." ]
def fit(self, X, y=None): if self.metric in TSLEARN_VALID_METRICS: self._ts_metric = self.metric self.metric = 'precomputed' X = check_array(X, allow_nd=True, force_all_finite=self.metric != 'precomputed') X = to_time_series_dataset(X) X = check_dims(X) if self.metric == 'precomputed...
['def', 'fit(self,', 'X,', 'y=None):', 'if', 'self.metric', 'in', 'TSLEARN_VALID_METRICS:', 'self._ts_metric', '=', 'self.metric', 'self.metric', '=', "'precomputed'", 'X', '=', 'check_array(X,', 'allow_nd=True,', 'force_all_finite=self.metric', '!=', "'precomputed')", 'X', '=', 'to_time_series_dataset(X)', 'X', '=', '...
952,538
enuguru/artificial_intelligence_and_machine_learning
results.py
Numbers.set_precision
set_precision
Set the number of decimal places used to report percentages.
[ "Set", "the", "number", "of", "decimal", "places", "used", "to", "report", "percentages." ]
def set_precision(cls, precision): assert 0 <= precision < 10 cls._precision = precision cls._near0 = 1.0 / 10 ** precision cls._near100 = 100.0 - cls._near0
['def', 'set_precision(cls,', 'precision):', 'assert', '0', '<=', 'precision', '<', '10', 'cls._precision', '=', 'precision', 'cls._near0', '=', '1.0', '/', '10', '**', 'precision', 'cls._near100', '=', '100.0', '-', 'cls._near0']
147,925
sunishsheth2009/ChatterBot
test_search.py
SearchTestCase.test_search_no_results
test_search_no_results
An exception should be raised if there is no data to return.
[ "An", "exception", "should", "be", "raised", "if", "there", "is", "no", "data", "to", "return." ]
def test_search_no_results(self): statement = Statement(text='What is your quest?') with self.assertRaises(StopIteration): next(self.search_algorithm.search(statement))
['def', 'test_search_no_results(self):', 'statement', '=', "Statement(text='What", 'is', 'your', "quest?')", 'with', 'self.assertRaises(StopIteration):', 'next(self.search_algorithm.search(statement))']
485,893
0xangelo/raylab
mixins.py
UniformModelPriorMixin.sample_model
sample_model
Return a model and its index sampled uniformly at random.
[ "Return", "a", "model", "and", "its", "index", "sampled", "uniformly", "at", "random." ]
def sample_model(self) -> Tuple[nn.Module, int]: models = self.models idx = self._rng.integers(len(models)) return (models[idx], idx)
['def', 'sample_model(self)', '->', 'Tuple[nn.Module,', 'int]:', 'models', '=', 'self.models', 'idx', '=', 'self._rng.integers(len(models))', 'return', '(models[idx],', 'idx)']
848,335
jimtin/Stock_Comparison
data.py
YamlLexer.set_indent
set_indent
Set the previously saved indentation level.
[ "Set", "the", "previously", "saved", "indentation", "level." ]
def set_indent(token_class, implicit=False): def callback(lexer, match, context): text = match.group() if context.indent < context.next_indent: context.indent_stack.append(context.indent) context.indent = context.next_indent if not implicit: context.next_...
['def', 'set_indent(token_class,', 'implicit=False):', 'def', 'callback(lexer,', 'match,', 'context):', 'text', '=', 'match.group()', 'if', 'context.indent', '<', 'context.next_indent:', 'context.indent_stack.append(context.indent)', 'context.indent', '=', 'context.next_indent', 'if', 'not', 'implicit:', 'context.next_...
358,453
zhaocq-nlp/NJUNMT-tf
ensemble_experiment.py
EnsembleExperiment.default_inferdata_params
default_inferdata_params
Returns a dictionary of default infer data parameters.
[ "Returns", "a", "dictionary", "of", "default", "infer", "data", "parameters." ]
def default_inferdata_params(): return {'features_file': None, 'output_file': None, 'labels_file': None}
['def', 'default_inferdata_params():', 'return', "{'features_file':", 'None,', "'output_file':", 'None,', "'labels_file':", 'None}']
782,780
karbmk/CS4705-NLP
p4.py
find_rare_words
find_rare_words
Return the set of all words that are rare (Count < 5).
[ "Return", "the", "set", "of", "all", "words", "that", "are", "rare", "(Count", "<", "5)." ]
def find_rare_words(count_infile): freq_dict = defaultdict(int) for line in count_infile: count_info = line.split() if len(count_info) > 3 and count_info[1] == 'UNARYRULE': word = count_info[3] count = int(count_info[0]) freq_dict[word] += count rare_set =...
['def', 'find_rare_words(count_infile):', 'freq_dict', '=', 'defaultdict(int)', 'for', 'line', 'in', 'count_infile:', 'count_info', '=', 'line.split()', 'if', 'len(count_info)', '>', '3', 'and', 'count_info[1]', '==', "'UNARYRULE':", 'word', '=', 'count_info[3]', 'count', '=', 'int(count_info[0])', 'freq_dict[word]', '...
508,226
Jamie725/Multimodal-Object-Detection-via-Probabilistic-Ensembling
resnet.py
make_stage
make_stage
Create a resnet stage by creating many blocks.
[ "Create", "a", "resnet", "stage", "by", "creating", "many", "blocks." ]
def make_stage(block_class, num_blocks, first_stride, **kwargs): blocks = [] for i in range(num_blocks): blocks.append(block_class(stride=first_stride if i == 0 else 1, **kwargs)) kwargs['in_channels'] = kwargs['out_channels'] return blocks
['def', 'make_stage(block_class,', 'num_blocks,', 'first_stride,', '**kwargs):', 'blocks', '=', '[]', 'for', 'i', 'in', 'range(num_blocks):', 'blocks.append(block_class(stride=first_stride', 'if', 'i', '==', '0', 'else', '1,', '**kwargs))', "kwargs['in_channels']", '=', "kwargs['out_channels']", 'return', 'blocks']
643,870
BioGeek/aima
text.py
IRSystem.present
present
Present the results as a list.
[ "Present", "the", "results", "as", "a", "list." ]
def present(self, results): for (score, d) in results: doc = self.documents[d] print('%5.2f|%25s | %s' % (100 * score, doc.url, doc.title[:45].expandtabs()))
['def', 'present(self,', 'results):', 'for', '(score,', 'd)', 'in', 'results:', 'doc', '=', 'self.documents[d]', "print('%5.2f|%25s", '|', "%s'", '%', '(100', '*', 'score,', 'doc.url,', 'doc.title[:45].expandtabs()))']
86,164
keyonvafa/career-code
fairseq_task.py
FairseqTask.build_bpe
build_bpe
Build the tokenizer for this task.
[ "Build", "the", "tokenizer", "for", "this", "task." ]
def build_bpe(self, args): return encoders.build_bpe(args)
['def', 'build_bpe(self,', 'args):', 'return', 'encoders.build_bpe(args)']
455,763
open-mmlab/mmdetection3d
base_3d_dense_head.py
Base3DDenseHead.predict
predict
Perform forward propagation of the 3D detection head and predict detection results on the features of the upstream network.
[ "Perform", "forward", "propagation", "of", "the", "3D", "detection", "head", "and", "predict", "detection", "results", "on", "the", "features", "of", "the", "upstream", "network." ]
def predict(self, x: Tuple[Tensor], batch_data_samples: SampleList, rescale: bool=False) -> InstanceList: batch_input_metas = [data_samples.metainfo for data_samples in batch_data_samples] outs = self(x) predictions = self.predict_by_feat(*outs, batch_input_metas=batch_input_metas, rescale=rescale) retu...
['def', 'predict(self,', 'x:', 'Tuple[Tensor],', 'batch_data_samples:', 'SampleList,', 'rescale:', 'bool=False)', '->', 'InstanceList:', 'batch_input_metas', '=', '[data_samples.metainfo', 'for', 'data_samples', 'in', 'batch_data_samples]', 'outs', '=', 'self(x)', 'predictions', '=', 'self.predict_by_feat(*outs,', 'bat...
631,872
tencent-ailab/TriNet
attention.py
MultiHeadedAttention.forward_attention
forward_attention
Compute attention context vector.
[ "Compute", "attention", "context", "vector." ]
def forward_attention(self, value: torch.Tensor, scores: torch.Tensor, mask: Optional[torch.Tensor]) -> torch.Tensor: n_batch = value.size(0) if mask is not None: mask = mask.unsqueeze(1).eq(0) scores = scores.masked_fill(mask, -float('inf')) attn = torch.softmax(scores, dim=-1).masked_f...
['def', 'forward_attention(self,', 'value:', 'torch.Tensor,', 'scores:', 'torch.Tensor,', 'mask:', 'Optional[torch.Tensor])', '->', 'torch.Tensor:', 'n_batch', '=', 'value.size(0)', 'if', 'mask', 'is', 'not', 'None:', 'mask', '=', 'mask.unsqueeze(1).eq(0)', 'scores', '=', 'scores.masked_fill(mask,', "-float('inf'))", '...
425,481
ryu-ed/SpaceInvaders_Ros
utils.py
get_exception_handlers
get_exception_handlers
Return the collections of handlers handling the exception in arguments.
[ "Return", "the", "collections", "of", "handlers", "handling", "the", "exception", "in", "arguments." ]
def get_exception_handlers(node: astroid.node_classes.NodeNG, exception=Exception) -> Optional[List[astroid.ExceptHandler]]: context = find_try_except_wrapper_node(node) if isinstance(context, astroid.TryExcept): return [handler for handler in context.handlers if error_of_type(handler, exception)] r...
['def', 'get_exception_handlers(node:', 'astroid.node_classes.NodeNG,', 'exception=Exception)', '->', 'Optional[List[astroid.ExceptHandler]]:', 'context', '=', 'find_try_except_wrapper_node(node)', 'if', 'isinstance(context,', 'astroid.TryExcept):', 'return', '[handler', 'for', 'handler', 'in', 'context.handlers', 'if'...
370,021
SerpentBit/ovl
straight_rectangle_filter.py
straight_rectangle_filter
straight_rectangle_filter
Receives a list of contours and returns only those that are approximately a rectangle that its sides are parallel to the frame of the image :param contour: List of Contours to filter :param min_area_ratio: The minimum ratio between the rectangle and the contour :type min_area_ratio: float :return: the contour list filt...
[ "Receives", "a", "list", "of", "contours", "and", "returns", "only", "those", "that", "are", "approximately", "a", "rectangle", "that", "its", "sides", "are", "parallel", "to", "the", "frame", "of", "the", "image", ":param", "contour:", "List", "of", "Contou...
def straight_rectangle_filter(contour, min_area_ratio: RangedNumber(0, 1)=0.8): (fill_ratio, _, _) = rectangle_fill_ratio_straight(contour) perimeter = cv2.arcLength(contour, True) approximation = cv2.approxPolyDP(contour, 0.02 * perimeter, True) return fill_ratio > min_area_ratio and len(approximation)...
['def', 'straight_rectangle_filter(contour,', 'min_area_ratio:', 'RangedNumber(0,', '1)=0.8):', '(fill_ratio,', '_,', '_)', '=', 'rectangle_fill_ratio_straight(contour)', 'perimeter', '=', 'cv2.arcLength(contour,', 'True)', 'approximation', '=', 'cv2.approxPolyDP(contour,', '0.02', '*', 'perimeter,', 'True)', 'return',...
776,839
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
data.py
SnippetGen
SnippetGen
Generates consecutive snippets between start and end tokens.
[ "Generates", "consecutive", "snippets", "between", "start", "and", "end", "tokens." ]
def SnippetGen(text, start_tok, end_tok, inclusive=True): cur = 0 while True: try: start_p = text.index(start_tok, cur) end_p = text.index(end_tok, start_p + 1) cur = end_p + len(end_tok) if inclusive: yield text[start_p:cur] el...
['def', 'SnippetGen(text,', 'start_tok,', 'end_tok,', 'inclusive=True):', 'cur', '=', '0', 'while', 'True:', 'try:', 'start_p', '=', 'text.index(start_tok,', 'cur)', 'end_p', '=', 'text.index(end_tok,', 'start_p', '+', '1)', 'cur', '=', 'end_p', '+', 'len(end_tok)', 'if', 'inclusive:', 'yield', 'text[start_p:cur]', 'el...
29,863
darylclimb/cvml_project
utils.py
bilinear_sampler
bilinear_sampler
Construct a new image by bilinear sampling from the input image.
[ "Construct", "a", "new", "image", "by", "bilinear", "sampling", "from", "the", "input", "image." ]
def bilinear_sampler(imgs, coords): def _repeat(x, n_repeats): rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([n_repeats])), 1), [1, 0]) rep = tf.cast(rep, 'float32') x = tf.matmul(tf.reshape(x, (-1, 1)), rep) return tf.reshape(x, [-1]) (coords_x, coords_y) = tf.split(...
['def', 'bilinear_sampler(imgs,', 'coords):', 'def', '_repeat(x,', 'n_repeats):', 'rep', '=', 'tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([n_repeats])),', '1),', '[1,', '0])', 'rep', '=', 'tf.cast(rep,', "'float32')", 'x', '=', 'tf.matmul(tf.reshape(x,', '(-1,', '1)),', 'rep)', 'return', 'tf.reshape(x,', '[-1])...
509,641
PaddlePaddle/PaddleSpeech
wavenet_denoiser.py
WaveNetDenoiser.apply_weight_norm
apply_weight_norm
Recursively apply weight normalization to all the Convolution layers in the sublayers.
[ "Recursively", "apply", "weight", "normalization", "to", "all", "the", "Convolution", "layers", "in", "the", "sublayers." ]
def apply_weight_norm(self): def _apply_weight_norm(layer): if isinstance(layer, (nn.Conv1D, nn.Conv2D)): nn.utils.weight_norm(layer) self.apply(_apply_weight_norm)
['def', 'apply_weight_norm(self):', 'def', '_apply_weight_norm(layer):', 'if', 'isinstance(layer,', '(nn.Conv1D,', 'nn.Conv2D)):', 'nn.utils.weight_norm(layer)', 'self.apply(_apply_weight_norm)']
277,254
nicknochnack/RealTimeSignLanguageTFJS
context.py
Context.create_vars
create_vars
Create tf variables for contexts.
[ "Create", "tf", "variables", "for", "contexts." ]
def create_vars(self, name, agent=None): if agent is not None: meta_vars = agent.create_vars(name) else: meta_vars = {} assert name not in self.context_vars, 'Conflict! %s is already initialized.' % name self.context_vars[name] = tuple([tf.Variable(tf.zeros(shape=spec.shape, dtype=spec.d...
['def', 'create_vars(self,', 'name,', 'agent=None):', 'if', 'agent', 'is', 'not', 'None:', 'meta_vars', '=', 'agent.create_vars(name)', 'else:', 'meta_vars', '=', '{}', 'assert', 'name', 'not', 'in', 'self.context_vars,', "'Conflict!", '%s', 'is', 'already', "initialized.'", '%', 'name', 'self.context_vars[name]', '=',...
851,771
piggyandy/artificial-intelligence
mrecords.py
openfile
openfile
Opens the file handle of file `fname`.
[ "Opens", "the", "file", "handle", "of", "file", "`fname`." ]
def openfile(fname): if hasattr(fname, 'readline'): return fname try: f = open(fname) except IOError: raise IOError("No such file: '%s'" % fname) if f.readline()[:2] != '\\x': f.seek(0, 0) return f f.close() raise NotImplementedError('Wow, binary file')
['def', 'openfile(fname):', 'if', 'hasattr(fname,', "'readline'):", 'return', 'fname', 'try:', 'f', '=', 'open(fname)', 'except', 'IOError:', 'raise', 'IOError("No', 'such', 'file:', '\'%s\'"', '%', 'fname)', 'if', 'f.readline()[:2]', '!=', "'\\\\x':", 'f.seek(0,', '0)', 'return', 'f', 'f.close()', 'raise', "NotImpleme...
172,266
sktime/sktime
test_all_estimators.py
TestAllEstimators.test_fit_idempotent
test_fit_idempotent
Check that calling fit twice is equivalent to calling it once.
[ "Check", "that", "calling", "fit", "twice", "is", "equivalent", "to", "calling", "it", "once." ]
def test_fit_idempotent(self, estimator_instance, scenario, method_nsc_arraylike): estimator = estimator_instance if isinstance(estimator_instance, BaseForecaster) and method_nsc_arraylike == 'predict_proba': return None set_random_state(estimator) results = scenario.run(estimator, method_sequen...
['def', 'test_fit_idempotent(self,', 'estimator_instance,', 'scenario,', 'method_nsc_arraylike):', 'estimator', '=', 'estimator_instance', 'if', 'isinstance(estimator_instance,', 'BaseForecaster)', 'and', 'method_nsc_arraylike', '==', "'predict_proba':", 'return', 'None', 'set_random_state(estimator)', 'results', '=', ...
877,619
chainer/chainer
optimizer.py
GradientMethod.use_fp32_update
use_fp32_update
Enables use of parameter update in fp32.
[ "Enables", "use", "of", "parameter", "update", "in", "fp32." ]
def use_fp32_update(self, flag=True): self._use_fp32_update = flag link = getattr(self, 'target', None) if link is not None: for param in link.params(): param.update_rule.use_fp32_update()
['def', 'use_fp32_update(self,', 'flag=True):', 'self._use_fp32_update', '=', 'flag', 'link', '=', 'getattr(self,', "'target',", 'None)', 'if', 'link', 'is', 'not', 'None:', 'for', 'param', 'in', 'link.params():', 'param.update_rule.use_fp32_update()']
477,046
rlgraph/rlgraph
test_python_memory_performance.py
TestPythonMemoryPerformance.test_rlgraph_combined_ops
test_rlgraph_combined_ops
Tests a combined workflow of insert, sample, update on the prioritized replay memory.
[ "Tests", "a", "combined", "workflow", "of", "insert,", "sample,", "update", "on", "the", "prioritized", "replay", "memory." ]
def test_rlgraph_combined_ops(self): memory = ApexMemory(capacity=self.capacity, alpha=1.0) chunksize = 32 chunks = int(self.inserts / chunksize) records = [self.record_space.sample(size=chunksize) for _ in range_(chunks)] loss_values = [np.random.random(size=self.sample_batch_size) for _ in range_(...
['def', 'test_rlgraph_combined_ops(self):', 'memory', '=', 'ApexMemory(capacity=self.capacity,', 'alpha=1.0)', 'chunksize', '=', '32', 'chunks', '=', 'int(self.inserts', '/', 'chunksize)', 'records', '=', '[self.record_space.sample(size=chunksize)', 'for', '_', 'in', 'range_(chunks)]', 'loss_values', '=', '[np.random.r...
862,816
mmetcalfe/car-detection
fileutils.py
find_in_ancestors
find_in_ancestors
Finds a file with the given name in the current directory its parent, or any ancestor.
[ "Finds", "a", "file", "with", "the", "given", "name", "in", "the", "current", "directory", "its", "parent,", "or", "any", "ancestor." ]
def find_in_ancestors(fname): dirname = os.curdir while True: if not os.path.isdir(dirname): abspath = os.path.abspath(dirname) raise IOError("The directory '{}' does not exist ('{}').".format(dirname, abspath)) test_fname = os.path.join(dirname, fname) if os.path...
['def', 'find_in_ancestors(fname):', 'dirname', '=', 'os.curdir', 'while', 'True:', 'if', 'not', 'os.path.isdir(dirname):', 'abspath', '=', 'os.path.abspath(dirname)', 'raise', 'IOError("The', 'directory', "'{}'", 'does', 'not', 'exist', '(\'{}\').".format(dirname,', 'abspath))', 'test_fname', '=', 'os.path.join(dirnam...
454,833
ifwe/digsby
infobox.py
HtmlCacher.memo_format
memo_format
Calls format with the format, acct, and htmlfonts.
[ "Calls", "format", "with", "the", "format,", "acct,", "and", "htmlfonts." ]
def memo_format(self, htmlfonts, cachekey): if isinstance(cachekey, tuple): acct = cachekey[0] return format(self.format[acct.service][cachekey[1]], acct, htmlfonts) else: acct = cachekey return format(self.format[acct.service], acct, htmlfonts)
['def', 'memo_format(self,', 'htmlfonts,', 'cachekey):', 'if', 'isinstance(cachekey,', 'tuple):', 'acct', '=', 'cachekey[0]', 'return', 'format(self.format[acct.service][cachekey[1]],', 'acct,', 'htmlfonts)', 'else:', 'acct', '=', 'cachekey', 'return', 'format(self.format[acct.service],', 'acct,', 'htmlfonts)']
185,500
viko-3/DiffSeqMol
utils.py
parse_rendezvous_endpoint
parse_rendezvous_endpoint
Extracts the hostname and the port number from a rendezvous endpoint.
[ "Extracts", "the", "hostname", "and", "the", "port", "number", "from", "a", "rendezvous", "endpoint." ]
def parse_rendezvous_endpoint(endpoint: Optional[str], default_port: int) -> Tuple[str, int]: if endpoint is not None: endpoint = endpoint.strip() if not endpoint: return ('localhost', default_port) if endpoint[0] == '[' and endpoint[-1] == ']': (host, *rest) = (endpoint, *[]) el...
['def', 'parse_rendezvous_endpoint(endpoint:', 'Optional[str],', 'default_port:', 'int)', '->', 'Tuple[str,', 'int]:', 'if', 'endpoint', 'is', 'not', 'None:', 'endpoint', '=', 'endpoint.strip()', 'if', 'not', 'endpoint:', 'return', "('localhost',", 'default_port)', 'if', 'endpoint[0]', '==', "'['", 'and', 'endpoint[-1]...
551,454
43Carrig/recurrent_neural_networks_practice
gen_nn_ops.py
conv3d_backprop_input
conv3d_backprop_input
Computes the gradients of 3-D convolution with respect to the input.
[ "Computes", "the", "gradients", "of", "3-D", "convolution", "with", "respect", "to", "the", "input." ]
def conv3d_backprop_input(input, filter, out_backprop, strides, padding, dilations=[1, 1, 1, 1, 1], name=None): _ctx = _context._context if _ctx is None or not _ctx._eager_context.is_eager: if not isinstance(strides, (list, tuple)): raise TypeError("Expected list for 'strides' argument to 'c...
['def', 'conv3d_backprop_input(input,', 'filter,', 'out_backprop,', 'strides,', 'padding,', 'dilations=[1,', '1,', '1,', '1,', '1],', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'if', 'not', 'isinstance(strides,', '(list,', 'tuple)):', 'rais...
338,320
sony/nnabla-rl
replay_buffer.py
ReplayBuffer.append
append
Add new experience to the replay buffer.
[ "Add", "new", "experience", "to", "the", "replay", "buffer." ]
def append(self, experience: Experience): self._buffer.append(experience)
['def', 'append(self,', 'experience:', 'Experience):', 'self._buffer.append(experience)']
734,313
ludwig-ai/ludwig
test_validate_config_misc.py
test_combiner_descriptions
test_combiner_descriptions
This test tests that each combiner in the enum for available combiners has a description.
[ "This", "test", "tests", "that", "each", "combiner", "in", "the", "enum", "for", "available", "combiners", "has", "a", "description." ]
def test_combiner_descriptions(): combiner_json_schema = get_combiner_jsonschema() type_data = combiner_json_schema['properties']['type'] assert len(set(type_data['enumDescriptions'].keys())) > 0 assert set(type_data['enumDescriptions'].keys()).issubset(set(type_data['enum']))
['def', 'test_combiner_descriptions():', 'combiner_json_schema', '=', 'get_combiner_jsonschema()', 'type_data', '=', "combiner_json_schema['properties']['type']", 'assert', "len(set(type_data['enumDescriptions'].keys()))", '>', '0', 'assert', "set(type_data['enumDescriptions'].keys()).issubset(set(type_data['enum']))"]
617,380
deepmind/xmanager
docker_lib.py
build_docker_image
build_docker_image
Builds a Docker image locally.
[ "Builds", "a", "Docker", "image", "locally." ]
def build_docker_image(image: str, directory: str, dockerfile: Optional[str]=None, use_docker_command: bool=True, show_docker_command_progress: bool=False) -> str: logging.info('Building Docker image') docker_client = docker.from_env() if not dockerfile: dockerfile = os.path.join(directory, 'Dockerf...
['def', 'build_docker_image(image:', 'str,', 'directory:', 'str,', 'dockerfile:', 'Optional[str]=None,', 'use_docker_command:', 'bool=True,', 'show_docker_command_progress:', 'bool=False)', '->', 'str:', "logging.info('Building", 'Docker', "image')", 'docker_client', '=', 'docker.from_env()', 'if', 'not', 'dockerfile:'...
968,705
enlite-ai/maze
dict_action_conversion.py
ActionConversion.space_to_maze
space_to_maze
Converts agent dictionary action to environment MazeAction object.
[ "Converts", "agent", "dictionary", "action", "to", "environment", "MazeAction", "object." ]
def space_to_maze(self, action: Dict[str, int], maze_state: Cutting2DMazeState) -> Cutting2DMazeAction: return Cutting2DMazeAction(piece_id=action['piece_idx'], rotate=bool(action['cut_rotation']), reverse_cutting_order=bool(action['cut_order']))
['def', 'space_to_maze(self,', 'action:', 'Dict[str,', 'int],', 'maze_state:', 'Cutting2DMazeState)', '->', 'Cutting2DMazeAction:', 'return', "Cutting2DMazeAction(piece_id=action['piece_idx'],", "rotate=bool(action['cut_rotation']),", "reverse_cutting_order=bool(action['cut_order']))"]
647,650
MycroftAI/mycroft-core
padatious_service.py
PadatiousMatcher.match_low
match_low
Intent matcher for low confidence.
[ "Intent", "matcher", "for", "low", "confidence." ]
def match_low(self, utterances, _=None, __=None): return self._match_level(utterances, 0.5)
['def', 'match_low(self,', 'utterances,', '_=None,', '__=None):', 'return', 'self._match_level(utterances,', '0.5)']
290,576
TARGET-SIDE-DATA-AUG/TSDASG
composite_encoder.py
CompositeEncoder.reorder_encoder_out
reorder_encoder_out
Reorder encoder output according to new_order.
[ "Reorder", "encoder", "output", "according", "to", "new_order." ]
def reorder_encoder_out(self, encoder_out, new_order): for key in self.encoders: encoder_out[key] = self.encoders[key].reorder_encoder_out(encoder_out[key], new_order) return encoder_out
['def', 'reorder_encoder_out(self,', 'encoder_out,', 'new_order):', 'for', 'key', 'in', 'self.encoders:', 'encoder_out[key]', '=', 'self.encoders[key].reorder_encoder_out(encoder_out[key],', 'new_order)', 'return', 'encoder_out']
952,073
ForrestPi/ObjectDetectionTricks
wavelet_test.py
TestWavelet.testRescaleOneIsANoOp
testRescaleOneIsANoOp
Tests that rescale(x, 1) = x.
[ "Tests", "that", "rescale(x,", "1)", "=", "x." ]
def testRescaleOneIsANoOp(self): im = np.random.uniform(size=(2, 32, 32)) pyr = wavelet.construct(im, 4, 'LeGall5/3') pyr_rescaled = wavelet.rescale(pyr, 1.0) self._assert_pyramids_close(pyr, pyr_rescaled, 1e-08)
['def', 'testRescaleOneIsANoOp(self):', 'im', '=', 'np.random.uniform(size=(2,', '32,', '32))', 'pyr', '=', 'wavelet.construct(im,', '4,', "'LeGall5/3')", 'pyr_rescaled', '=', 'wavelet.rescale(pyr,', '1.0)', 'self._assert_pyramids_close(pyr,', 'pyr_rescaled,', '1e-08)']
744,734
udacity/artificial-intelligence
conftest.py
check_fpu_mode
check_fpu_mode
Check FPU precision mode was not changed during the test.
[ "Check", "FPU", "precision", "mode", "was", "not", "changed", "during", "the", "test." ]
def check_fpu_mode(request): old_mode = get_fpu_mode() yield new_mode = get_fpu_mode() if old_mode != new_mode: raise AssertionError('FPU precision mode changed from {0:#x} to {1:#x} during the test'.format(old_mode, new_mode)) collect_result = _collect_results.get(request.node) if colle...
['def', 'check_fpu_mode(request):', 'old_mode', '=', 'get_fpu_mode()', 'yield', 'new_mode', '=', 'get_fpu_mode()', 'if', 'old_mode', '!=', 'new_mode:', 'raise', "AssertionError('FPU", 'precision', 'mode', 'changed', 'from', '{0:#x}', 'to', '{1:#x}', 'during', 'the', "test'.format(old_mode,", 'new_mode))', 'collect_resu...
59,074
Megvii-BaseDetection/DynamicRouting
visualizer.py
Visualizer.draw_instance_predictions
draw_instance_predictions
Draw instance-level prediction results on an image.
[ "Draw", "instance-level", "prediction", "results", "on", "an", "image." ]
def draw_instance_predictions(self, predictions): boxes = predictions.pred_boxes if predictions.has('pred_boxes') else None scores = predictions.scores if predictions.has('scores') else None classes = predictions.pred_classes if predictions.has('pred_classes') else None labels = _create_text_labels(clas...
['def', 'draw_instance_predictions(self,', 'predictions):', 'boxes', '=', 'predictions.pred_boxes', 'if', "predictions.has('pred_boxes')", 'else', 'None', 'scores', '=', 'predictions.scores', 'if', "predictions.has('scores')", 'else', 'None', 'classes', '=', 'predictions.pred_classes', 'if', "predictions.has('pred_clas...
555,330
lixingjian/DELTA
base_solver.py
Solver.get_train_op
get_train_op
Get the training operator.
[ "Get", "the", "training", "operator." ]
def get_train_op(self, loss, global_step=None): apply_gradient_op = self.get_apply_gradients_op(loss, global_step) self.var_avg(global_step) with tf.control_dependencies([apply_gradient_op]): update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) train_op = tf.group(*update_ops) utils.l...
['def', 'get_train_op(self,', 'loss,', 'global_step=None):', 'apply_gradient_op', '=', 'self.get_apply_gradients_op(loss,', 'global_step)', 'self.var_avg(global_step)', 'with', 'tf.control_dependencies([apply_gradient_op]):', 'update_ops', '=', 'tf.get_collection(tf.GraphKeys.UPDATE_OPS)', 'train_op', '=', 'tf.group(*u...
537,662
enuguru/artificial_intelligence_and_machine_
__init__.py
SQLAlchemy.make_declarative_base
make_declarative_base
Creates the declarative base.
[ "Creates", "the", "declarative", "base." ]
def make_declarative_base(self, metadata=None): base = declarative_base(cls=Model, name='Model', metadata=metadata, metaclass=_BoundDeclarativeMeta) base.query = _QueryProperty(self) return base
['def', 'make_declarative_base(self,', 'metadata=None):', 'base', '=', 'declarative_base(cls=Model,', "name='Model',", 'metadata=metadata,', 'metaclass=_BoundDeclarativeMeta)', 'base.query', '=', '_QueryProperty(self)', 'return', 'base']
157,939
lebrice/Sequoia
policy_head.py
PolicyHead.create_buffers
create_buffers
Creates the buffers to hold the items from each env.
[ "Creates", "the", "buffers", "to", "hold", "the", "items", "from", "each", "env." ]
def create_buffers(self): logger.debug(f'Creating buffers (batch size={self.batch_size})') logger.debug(f'Maximum buffer length: {self.hparams.max_episode_window_length}') self.representations = self._make_buffers() self.actions = self._make_buffers() self.rewards = self._make_buffers() self.num...
['def', 'create_buffers(self):', "logger.debug(f'Creating", 'buffers', '(batch', "size={self.batch_size})')", "logger.debug(f'Maximum", 'buffer', 'length:', "{self.hparams.max_episode_window_length}')", 'self.representations', '=', 'self._make_buffers()', 'self.actions', '=', 'self._make_buffers()', 'self.rewards', '='...
344,363
kornia/kornia
camera_model.py
CameraModelBase.width
width
Returns the width of the image.
[ "Returns", "the", "width", "of", "the", "image." ]
def width(self) -> int | Tensor: return self._width
['def', 'width(self)', '->', 'int', '|', 'Tensor:', 'return', 'self._width']
622,266
openvinotoolkit/training_extensions
color.py
ColorEntity.hex_str
hex_str
Returns the color in a Hex representation.
[ "Returns", "the", "color", "in", "a", "Hex", "representation." ]
def hex_str(self) -> str: raise NotImplementedError
['def', 'hex_str(self)', '->', 'str:', 'raise', 'NotImplementedError']
918,479
amarack/python-rl
fitted_qiteration.py
FittedQIteration.getAction
getAction
Get the action under the current plan policy for the given state.
[ "Get", "the", "action", "under", "the", "current", "plan", "policy", "for", "the", "given", "state." ]
def getAction(self, state): if self.has_plan: return self.learner.predict([self.getStateAction(state, a) for a in range(self.actions)]).argmax() else: return self.randGenerator.randint(0, self.actions - 1)
['def', 'getAction(self,', 'state):', 'if', 'self.has_plan:', 'return', 'self.learner.predict([self.getStateAction(state,', 'a)', 'for', 'a', 'in', 'range(self.actions)]).argmax()', 'else:', 'return', 'self.randGenerator.randint(0,', 'self.actions', '-', '1)']
297,507
scotthuang1989/object_detection_with_tensorflow
runners.py
create_dataset_and_model
create_dataset_and_model
Creates the dataset and model for a given config.
[ "Creates", "the", "dataset", "and", "model", "for", "a", "given", "config." ]
def create_dataset_and_model(config, split, shuffle, repeat): if config.dataset_type == 'pianoroll': (inputs, targets, lengths, mean) = datasets.create_pianoroll_dataset(config.dataset_path, split, config.batch_size, shuffle=shuffle, repeat=repeat) generative_bias_init = -tf.log(1.0 / tf.clip_by_val...
['def', 'create_dataset_and_model(config,', 'split,', 'shuffle,', 'repeat):', 'if', 'config.dataset_type', '==', "'pianoroll':", '(inputs,', 'targets,', 'lengths,', 'mean)', '=', 'datasets.create_pianoroll_dataset(config.dataset_path,', 'split,', 'config.batch_size,', 'shuffle=shuffle,', 'repeat=repeat)', 'generative_b...
797,092
openvinotoolkit/training_extensions
label_schema.py
LabelSchemaEntity.get_siblings_in_group
get_siblings_in_group
Return a list of the 'siblings', which are all labels within the same group as a label.
[ "Return", "a", "list", "of", "the", "'siblings',", "which", "are", "all", "labels", "within", "the", "same", "group", "as", "a", "label." ]
def get_siblings_in_group(self, label: LabelEntity) -> List[LabelEntity]: containing_group = self.get_group_containing_label(label) if containing_group is None: return [] return [label_iter for label_iter in containing_group.labels if not label_iter == label]
['def', 'get_siblings_in_group(self,', 'label:', 'LabelEntity)', '->', 'List[LabelEntity]:', 'containing_group', '=', 'self.get_group_containing_label(label)', 'if', 'containing_group', 'is', 'None:', 'return', '[]', 'return', '[label_iter', 'for', 'label_iter', 'in', 'containing_group.labels', 'if', 'not', 'label_iter...
918,574
KalleHallden/InstaAutomator
_dicom.py
SimpleDicomReader.get_numpy_array
get_numpy_array
Get numpy arra for this DICOM file, with the correct shape, and pixel values scaled appropriately.
[ "Get", "numpy", "arra", "for", "this", "DICOM", "file,", "with", "the", "correct", "shape,", "and", "pixel", "values", "scaled", "appropriately." ]
def get_numpy_array(self): if 'PixelData' not in self: raise TypeError('No pixel data found in this dataset.') if self._pixel_data_loc and len(self.PixelData) < 100: close_file = False if self._file is None: close_file = True self._file = open(self._filename, 'rb'...
['def', 'get_numpy_array(self):', 'if', "'PixelData'", 'not', 'in', 'self:', 'raise', "TypeError('No", 'pixel', 'data', 'found', 'in', 'this', "dataset.')", 'if', 'self._pixel_data_loc', 'and', 'len(self.PixelData)', '<', '100:', 'close_file', '=', 'False', 'if', 'self._file', 'is', 'None:', 'close_file', '=', 'True', ...
242,462
srai-lab/srai
test_h3_regionalizer.py
expected_h3_indexes
expected_h3_indexes
Get expected h3 indexes.
[ "Get", "expected", "h3", "indexes." ]
def expected_h3_indexes() -> List[str]: return ['837559fffffffff', '83754efffffffff', '83754cfffffffff', '837541fffffffff', '83755dfffffffff', '837543fffffffff', '83754afffffffff']
['def', 'expected_h3_indexes()', '->', 'List[str]:', 'return', "['837559fffffffff',", "'83754efffffffff',", "'83754cfffffffff',", "'837541fffffffff',", "'83755dfffffffff',", "'837543fffffffff',", "'83754afffffffff']"]
372,116
fudan-zvg/GSS
class_names.py
isaid_classes
isaid_classes
iSAID class names for external use.
[ "iSAID", "class", "names", "for", "external", "use." ]
def isaid_classes(): return ['background', 'ship', 'store_tank', 'baseball_diamond', 'tennis_court', 'basketball_court', 'Ground_Track_Field', 'Bridge', 'Large_Vehicle', 'Small_Vehicle', 'Helicopter', 'Swimming_pool', 'Roundabout', 'Soccer_ball_field', 'plane', 'Harbor']
['def', 'isaid_classes():', 'return', "['background',", "'ship',", "'store_tank',", "'baseball_diamond',", "'tennis_court',", "'basketball_court',", "'Ground_Track_Field',", "'Bridge',", "'Large_Vehicle',", "'Small_Vehicle',", "'Helicopter',", "'Swimming_pool',", "'Roundabout',", "'Soccer_ball_field',", "'plane',", "'H...
571,988
Hironsan/tensorflow-nlp-examples
char_lstm.py
load_text
load_text
Load text into memory.
[ "Load", "text", "into", "memory." ]
def load_text(filename): with open(filename, 'r') as f: text = f.read() return text
['def', 'load_text(filename):', 'with', 'open(filename,', "'r')", 'as', 'f:', 'text', '=', 'f.read()', 'return', 'text']
908,705
suarez12138/AI-Reversi_IMP_TextDichotomy
afm.py
AFM.get_kern_dist_from_name
get_kern_dist_from_name
Return the kerning pair distance (possibly 0) for chars *name1* and *name2*.
[ "Return", "the", "kerning", "pair", "distance", "(possibly", "0)", "for", "chars", "*name1*", "and", "*name2*." ]
def get_kern_dist_from_name(self, name1, name2): return self._kern.get((name1, name2), 0)
['def', 'get_kern_dist_from_name(self,', 'name1,', 'name2):', 'return', 'self._kern.get((name1,', 'name2),', '0)']
96,014
srai-lab/srai
test_no_regions.py
test_get_neighbours_up_to_distance
test_get_neighbours_up_to_distance
Test get_neighbours_up_to_distance of H3Neighbourhood.
[ "Test", "get_neighbours_up_to_distance", "of", "H3Neighbourhood." ]
def test_get_neighbours_up_to_distance(index: str, distance: int, expected: Set[str], expected_with_include_center: Set[str]) -> None: neighbourhood = H3Neighbourhood() assert neighbourhood.get_neighbours_up_to_distance(index, distance) == expected assert neighbourhood.get_neighbours_up_to_distance(index, d...
['def', 'test_get_neighbours_up_to_distance(index:', 'str,', 'distance:', 'int,', 'expected:', 'Set[str],', 'expected_with_include_center:', 'Set[str])', '->', 'None:', 'neighbourhood', '=', 'H3Neighbourhood()', 'assert', 'neighbourhood.get_neighbours_up_to_distance(index,', 'distance)', '==', 'expected', 'assert', 'ne...
372,092
Ixiaohuihuihui/AO2-DETR
transforms.py
obb2poly_np_oc
obb2poly_np_oc
Convert oriented bounding boxes to polygons.
[ "Convert", "oriented", "bounding", "boxes", "to", "polygons." ]
def obb2poly_np_oc(rbboxes): x = rbboxes[:, 0] y = rbboxes[:, 1] w = rbboxes[:, 2] h = rbboxes[:, 3] a = rbboxes[:, 4] score = rbboxes[:, 5] cosa = np.cos(a) sina = np.sin(a) (wx, wy) = (w / 2 * cosa, w / 2 * sina) (hx, hy) = (-h / 2 * sina, h / 2 * cosa) (p1x, p1y) = (x - wx...
['def', 'obb2poly_np_oc(rbboxes):', 'x', '=', 'rbboxes[:,', '0]', 'y', '=', 'rbboxes[:,', '1]', 'w', '=', 'rbboxes[:,', '2]', 'h', '=', 'rbboxes[:,', '3]', 'a', '=', 'rbboxes[:,', '4]', 'score', '=', 'rbboxes[:,', '5]', 'cosa', '=', 'np.cos(a)', 'sina', '=', 'np.sin(a)', '(wx,', 'wy)', '=', '(w', '/', '2', '*', 'cosa,'...
401,382
palVikram/Machine-Learning-using-Python
basic.py
Composite.init_py_impls
init_py_impls
Return a list of functions that compute each output of self.
[ "Return", "a", "list", "of", "functions", "that", "compute", "each", "output", "of", "self." ]
def init_py_impls(self): memo = {} def compose_impl(r): if r in memo: return memo[r] if r in self.fgraph.inputs: idx = self.fgraph.inputs.index(r) def f(inputs): return inputs[idx] memo[r] = f return f elif r.o...
['def', 'init_py_impls(self):', 'memo', '=', '{}', 'def', 'compose_impl(r):', 'if', 'r', 'in', 'memo:', 'return', 'memo[r]', 'if', 'r', 'in', 'self.fgraph.inputs:', 'idx', '=', 'self.fgraph.inputs.index(r)', 'def', 'f(inputs):', 'return', 'inputs[idx]', 'memo[r]', '=', 'f', 'return', 'f', 'elif', 'r.owner', 'is', 'None...
714,176
microsoft/InnerEye-DeepLearning
run_ml.py
is_classification_model
is_classification_model
Returns True if the given object is an InnerEye classification, but not a sequence model.
[ "Returns", "True", "if", "the", "given", "object", "is", "an", "InnerEye", "classification,", "but", "not", "a", "sequence", "model." ]
def is_classification_model(model: Any) -> bool: return isinstance(model, ScalarModelBase)
['def', 'is_classification_model(model:', 'Any)', '->', 'bool:', 'return', 'isinstance(model,', 'ScalarModelBase)']
613,058
Djaizz/Djaizz
zero_shot_classification.py
PreTrainedHuggingFaceZeroShotClassifier.predict
predict
Zero-Shot Classification of Text(s).
[ "Zero-Shot", "Classification", "of", "Text(s)." ]
def predict(self, text_or_texts: Union[ZeroShotClassificationInputType, Sequence[ZeroShotClassificationInputType]], candidate_labels: list[str], hypothesis_template: str='This example is {}.', multi_label: bool=False) -> Union[ZeroShotClassificationOutputType, list[ZeroShotClassificationOutputType]]: single_text: b...
['def', 'predict(self,', 'text_or_texts:', 'Union[ZeroShotClassificationInputType,', 'Sequence[ZeroShotClassificationInputType]],', 'candidate_labels:', 'list[str],', 'hypothesis_template:', "str='This", 'example', 'is', "{}.',", 'multi_label:', 'bool=False)', '->', 'Union[ZeroShotClassificationOutputType,', 'list[Zero...
189,458
Qualcomm-AI-research/weakly-supervised-causal-representation-
graph.py
LearnedGraph.get_graph_parameters
get_graph_parameters
Get graph parameters for logging purposes.
[ "Get", "graph", "parameters", "for", "logging", "purposes." ]
def get_graph_parameters(self): raise NotImplementedError
['def', 'get_graph_parameters(self):', 'raise', 'NotImplementedError']
373,160
befelix/safe_learning
test_functions.py
TestGridworld.test_integer_numpoints
test_integer_numpoints
Check integer numpoints argument.
[ "Check", "integer", "numpoints", "argument." ]
def test_integer_numpoints(self): grid = GridWorld([[1, 2], [3, 4]], 2) assert_equal(grid.num_points, np.array([2, 2]))
['def', 'test_integer_numpoints(self):', 'grid', '=', 'GridWorld([[1,', '2],', '[3,', '4]],', '2)', 'assert_equal(grid.num_points,', 'np.array([2,', '2]))']
328,238
nttcslab/byol-a
models.py
AudioNTT2020Task6X.load_weight
load_weight
Whapper function for loading BYOL-A pre-trained weights.
[ "Whapper", "function", "for", "loading", "BYOL-A", "pre-trained", "weights." ]
def load_weight(self, weight_file, device): namemap = {'features.0': 'conv1.0', 'features.1': 'conv1.1', 'features.4': 'conv2.0', 'features.5': 'conv2.1', 'features.8': 'conv3.0', 'features.9': 'conv3.1', 'fc.0': 'fc1.0', 'fc.3': 'fc2.1'} state_dict = torch.load(weight_file, map_location=device) new_dict = ...
['def', 'load_weight(self,', 'weight_file,', 'device):', 'namemap', '=', "{'features.0':", "'conv1.0',", "'features.1':", "'conv1.1',", "'features.4':", "'conv2.0',", "'features.5':", "'conv2.1',", "'features.8':", "'conv3.0',", "'features.9':", "'conv3.1',", "'fc.0':", "'fc1.0',", "'fc.3':", "'fc2.1'}", 'state_dict', ...
108,582
KKKSQJ/DeepLearning
onnx2trt.py
create_trt_engine
create_trt_engine
Create a tensorrt engine from ONNX.
[ "Create", "a", "tensorrt", "engine", "from", "ONNX." ]
def create_trt_engine(onnx_model: Union[str, onnx.ModelProto], input_shapes: Dict[str, Sequence[int]], log_level: trt.Logger.Severity=trt.Logger.ERROR, fp16_mode: bool=False, int8_mode: bool=False, int8_param: dict=None, max_workspace_size: int=0, device_id: int=0, **kwargs) -> trt.ICudaEngine: device = torch.devic...
['def', 'create_trt_engine(onnx_model:', 'Union[str,', 'onnx.ModelProto],', 'input_shapes:', 'Dict[str,', 'Sequence[int]],', 'log_level:', 'trt.Logger.Severity=trt.Logger.ERROR,', 'fp16_mode:', 'bool=False,', 'int8_mode:', 'bool=False,', 'int8_param:', 'dict=None,', 'max_workspace_size:', 'int=0,', 'device_id:', 'int=0...
180,606
depu0217/cs8803-AI4R
robot.py
robot.move
move
This function turns the robot and then moves it forward.
[ "This", "function", "turns", "the", "robot", "and", "then", "moves", "it", "forward." ]
def move(self, turning, distance, tolerance=0.001, max_turning_angle=pi): turning = random.gauss(turning, self.turning_noise) distance = random.gauss(distance, self.distance_noise) turning = max(-max_turning_angle, turning) turning = min(max_turning_angle, turning) distance = max(0.0, distance) ...
['def', 'move(self,', 'turning,', 'distance,', 'tolerance=0.001,', 'max_turning_angle=pi):', 'turning', '=', 'random.gauss(turning,', 'self.turning_noise)', 'distance', '=', 'random.gauss(distance,', 'self.distance_noise)', 'turning', '=', 'max(-max_turning_angle,', 'turning)', 'turning', '=', 'min(max_turning_angle,',...
192,858