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
NVIDIA-Omniverse/IsaacGymEnvs
adr_vec_task.py
VecTaskDextreme.get_state
get_state
Returns the state buffer of the environment (the priviledged observations for asymmetric training).
[ "Returns", "the", "state", "buffer", "of", "the", "environment", "(the", "priviledged", "observations", "for", "asymmetric", "training)." ]
def get_state(self): if self.use_dict_obs: raise NotImplementedError('No states in vec task when `use_dict_obs=True`') return torch.clamp(self.states_buf, -self.clip_obs, self.clip_obs).to(self.rl_device)
['def', 'get_state(self):', 'if', 'self.use_dict_obs:', 'raise', "NotImplementedError('No", 'states', 'in', 'vec', 'task', 'when', "`use_dict_obs=True`')", 'return', 'torch.clamp(self.states_buf,', '-self.clip_obs,', 'self.clip_obs).to(self.rl_device)']
246,622
AxeldeRomblay/MLBox
test_drift_thresholder.py
test_drifts
test_drifts
Test drifts method of Drift_thresholder class.
[ "Test", "drifts", "method", "of", "Drift_thresholder", "class." ]
def test_drifts(): drift_thresholder = Drift_thresholder() with pytest.raises(ValueError): drift_thresholder.drifts() reader = Reader(sep=',') dict = reader.train_test_split(Lpath=['data_for_tests/train.csv', 'data_for_tests/test.csv'], target_name='Survived') drift_thresholder.fit_transform...
['def', 'test_drifts():', 'drift_thresholder', '=', 'Drift_thresholder()', 'with', 'pytest.raises(ValueError):', 'drift_thresholder.drifts()', 'reader', '=', "Reader(sep=',')", 'dict', '=', "reader.train_test_split(Lpath=['data_for_tests/train.csv',", "'data_for_tests/test.csv'],", "target_name='Survived')", 'drift_thr...
630,034
bachiraoun/fullrmc
AtomicCoordinationConstraints.py
AtomicCoordinationNumberConstraint.data
data
Coordination number constraint data.
[ "Coordination", "number", "constraint", "data." ]
def data(self): return self.__coordNumData
['def', 'data(self):', 'return', 'self.__coordNumData']
213,499
tensorflow/agents
composite.py
reshape
reshape
Reshape composite tensor `t` to `shape`.
[ "Reshape", "composite", "tensor", "`t`", "to", "`shape`." ]
def reshape(t, shape): return tf.sparse.reshape(t, shape) if isinstance(t, tf.SparseTensor) else tf.reshape(t, shape)
['def', 'reshape(t,', 'shape):', 'return', 'tf.sparse.reshape(t,', 'shape)', 'if', 'isinstance(t,', 'tf.SparseTensor)', 'else', 'tf.reshape(t,', 'shape)']
23,094
scottemmons/rvs
step.py
get_total_steps
get_total_steps
Calculate the total number of environment steps (trajs * steps / traj).
[ "Calculate", "the", "total", "number", "of", "environment", "steps", "(trajs", "*", "steps", "/", "traj)." ]
def get_total_steps(rollout_dir: str) -> int: (s_obs_vecs, s_ach_goal_vecs, a_vecs) = load_rollouts(rollout_dir) assert s_obs_vecs.shape[0] == s_ach_goal_vecs.shape[0] == a_vecs.shape[0] assert s_obs_vecs.shape[1] == s_ach_goal_vecs.shape[1] == a_vecs.shape[1] total_steps = s_obs_vecs.shape[0] * s_obs_v...
['def', 'get_total_steps(rollout_dir:', 'str)', '->', 'int:', '(s_obs_vecs,', 's_ach_goal_vecs,', 'a_vecs)', '=', 'load_rollouts(rollout_dir)', 'assert', 's_obs_vecs.shape[0]', '==', 's_ach_goal_vecs.shape[0]', '==', 'a_vecs.shape[0]', 'assert', 's_obs_vecs.shape[1]', '==', 's_ach_goal_vecs.shape[1]', '==', 'a_vecs.sha...
326,993
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
inspect.py
Signature.from_function
from_function
Constructs Signature for the given python function.
[ "Constructs", "Signature", "for", "the", "given", "python", "function." ]
def from_function(cls, func): warnings.warn('inspect.Signature.from_function() is deprecated, use Signature.from_callable()', DeprecationWarning, stacklevel=2) return _signature_from_function(cls, func)
['def', 'from_function(cls,', 'func):', "warnings.warn('inspect.Signature.from_function()", 'is', 'deprecated,', 'use', "Signature.from_callable()',", 'DeprecationWarning,', 'stacklevel=2)', 'return', '_signature_from_function(cls,', 'func)']
428,699
liah-chan/transferNER
anntoconll.py
text_to_conll
text_to_conll
Convert plain text into CoNLL format.
[ "Convert", "plain", "text", "into", "CoNLL", "format." ]
def text_to_conll(f): global options if options.nosplit: sentences = f.readlines() else: sentences = [] for l in f: sentences.extend([s for s in NEWLINE_TERM_REGEX.split(l) if s]) lines = [] offset = 0 for s in sentences: nonspace_token_seen = False ...
['def', 'text_to_conll(f):', 'global', 'options', 'if', 'options.nosplit:', 'sentences', '=', 'f.readlines()', 'else:', 'sentences', '=', '[]', 'for', 'l', 'in', 'f:', 'sentences.extend([s', 'for', 's', 'in', 'NEWLINE_TERM_REGEX.split(l)', 'if', 's])', 'lines', '=', '[]', 'offset', '=', '0', 'for', 's', 'in', 'sentence...
905,106
deephyper/deephyper
_nest_asyncio.py
apply
apply
Patch asyncio to make its event loop reentrant.
[ "Patch", "asyncio", "to", "make", "its", "event", "loop", "reentrant." ]
def apply(loop=None): _patch_asyncio() _patch_task() _patch_tornado() loop = loop or asyncio.get_event_loop() _patch_loop(loop)
['def', 'apply(loop=None):', '_patch_asyncio()', '_patch_task()', '_patch_tornado()', 'loop', '=', 'loop', 'or', 'asyncio.get_event_loop()', '_patch_loop(loop)']
520,813
rlworkgroup/garage
test_multi_headed_mlp_module.py
test_invalid_settings
test_invalid_settings
Test Multi-headed MLPModule with invalid parameters.
[ "Test", "Multi-headed", "MLPModule", "with", "invalid", "parameters." ]
def test_invalid_settings(input_dim, output_dim, hidden_sizes, n_heads, nonlinearity, w_init, b_init): expected_msg_template = 'should be either an integer or a collection of length n_heads' with pytest.raises(ValueError, match=expected_msg_template): MultiHeadedMLPModule(n_heads=n_heads, input_dim=inpu...
['def', 'test_invalid_settings(input_dim,', 'output_dim,', 'hidden_sizes,', 'n_heads,', 'nonlinearity,', 'w_init,', 'b_init):', 'expected_msg_template', '=', "'should", 'be', 'either', 'an', 'integer', 'or', 'a', 'collection', 'of', 'length', "n_heads'", 'with', 'pytest.raises(ValueError,', 'match=expected_msg_template...
201,037
TrellixVulnTeam/Unsupervised_Learning_HFI7
styles.py
sheet_from_template
sheet_from_template
Use one of the base templates, and set bg/fg/select colors.
[ "Use", "one", "of", "the", "base", "templates,", "and", "set", "bg/fg/select", "colors." ]
def sheet_from_template(name, colors='lightbg'): colors = colors.lower() if colors == 'lightbg': return default_light_style_template % get_colors(name) elif colors == 'linux': return default_dark_style_template % get_colors(name) elif colors == 'nocolor': return default_bw_style_...
['def', 'sheet_from_template(name,', "colors='lightbg'):", 'colors', '=', 'colors.lower()', 'if', 'colors', '==', "'lightbg':", 'return', 'default_light_style_template', '%', 'get_colors(name)', 'elif', 'colors', '==', "'linux':", 'return', 'default_dark_style_template', '%', 'get_colors(name)', 'elif', 'colors', '==',...
435,902
jimtin/Stock_Comparison
history.py
HistoryManager.writeout_cache
writeout_cache
Write any entries in the cache to the database.
[ "Write", "any", "entries", "in", "the", "cache", "to", "the", "database." ]
def writeout_cache(self, conn=None): if conn is None: conn = self.db with self.db_input_cache_lock: try: self._writeout_input_cache(conn) except sqlite3.IntegrityError: self.new_session(conn) print('ERROR! Session/line number was not unique in', 'datab...
['def', 'writeout_cache(self,', 'conn=None):', 'if', 'conn', 'is', 'None:', 'conn', '=', 'self.db', 'with', 'self.db_input_cache_lock:', 'try:', 'self._writeout_input_cache(conn)', 'except', 'sqlite3.IntegrityError:', 'self.new_session(conn)', "print('ERROR!", 'Session/line', 'number', 'was', 'not', 'unique', "in',", "...
384,685
cbaziotis/seq3
seq3_losses.py
kl_length
kl_length
Length control loss, using a sequence of length labels (with eos token).
[ "Length", "control", "loss,", "using", "a", "sequence", "of", "length", "labels", "(with", "eos", "token)." ]
def kl_length(logits, lengths, eos): mask = sequence_mask(lengths - 1, lengths.max()) eos_labels = ((1 - mask) * eos).long().contiguous().view(-1) _logits = logits.contiguous().view(-1, logits.size(-1)) loss = F.cross_entropy(_logits, eos_labels, ignore_index=0) return loss
['def', 'kl_length(logits,', 'lengths,', 'eos):', 'mask', '=', 'sequence_mask(lengths', '-', '1,', 'lengths.max())', 'eos_labels', '=', '((1', '-', 'mask)', '*', 'eos).long().contiguous().view(-1)', '_logits', '=', 'logits.contiguous().view(-1,', 'logits.size(-1))', 'loss', '=', 'F.cross_entropy(_logits,', 'eos_labels,...
876,495
wandb/wandb
wandb_require.py
require
require
Indicate which experimental features are used by the script.
[ "Indicate", "which", "experimental", "features", "are", "used", "by", "the", "script." ]
def require(requirement: Optional[Union[str, Sequence[str]]]=None, experiment: Optional[Union[str, Sequence[str]]]=None) -> None: features = requirement or experiment if not features: return f = _Requires(features=features) f.apply()
['def', 'require(requirement:', 'Optional[Union[str,', 'Sequence[str]]]=None,', 'experiment:', 'Optional[Union[str,', 'Sequence[str]]]=None)', '->', 'None:', 'features', '=', 'requirement', 'or', 'experiment', 'if', 'not', 'features:', 'return', 'f', '=', '_Requires(features=features)', 'f.apply()']
941,599
Cheng-Lin-Li/AI
shop.py
FruitShop.getPriceOfOrder
getPriceOfOrder
orderList: List of (fruit, numPounds) tuples Returns cost of orderList, only including the values of fruits that this fruit shop has.
[ "orderList:", "List", "of", "(fruit,", "numPounds)", "tuples", "Returns", "cost", "of", "orderList,", "only", "including", "the", "values", "of", "fruits", "that", "this", "fruit", "shop", "has." ]
def getPriceOfOrder(self, orderList): totalCost = 0.0 for (fruit, numPounds) in orderList: costPerPound = self.getCostPerPound(fruit) if costPerPound != None: totalCost += numPounds * costPerPound return totalCost
['def', 'getPriceOfOrder(self,', 'orderList):', 'totalCost', '=', '0.0', 'for', '(fruit,', 'numPounds)', 'in', 'orderList:', 'costPerPound', '=', 'self.getCostPerPound(fruit)', 'if', 'costPerPound', '!=', 'None:', 'totalCost', '+=', 'numPounds', '*', 'costPerPound', 'return', 'totalCost']
24,817
lujiazho/SegDrawer
amg.py
mask_to_rle_pytorch
mask_to_rle_pytorch
Encodes masks to an uncompressed RLE, in the format expected by pycoco tools.
[ "Encodes", "masks", "to", "an", "uncompressed", "RLE,", "in", "the", "format", "expected", "by", "pycoco", "tools." ]
def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: (b, h, w) = tensor.shape tensor = tensor.permute(0, 2, 1).flatten(1) diff = tensor[:, 1:] ^ tensor[:, :-1] change_indices = diff.nonzero() out = [] for i in range(b): cur_idxs = change_indices[change_indices[:, 0] == ...
['def', 'mask_to_rle_pytorch(tensor:', 'torch.Tensor)', '->', 'List[Dict[str,', 'Any]]:', '(b,', 'h,', 'w)', '=', 'tensor.shape', 'tensor', '=', 'tensor.permute(0,', '2,', '1).flatten(1)', 'diff', '=', 'tensor[:,', '1:]', '^', 'tensor[:,', ':-1]', 'change_indices', '=', 'diff.nonzero()', 'out', '=', '[]', 'for', 'i', '...
842,205
TrellixVulnTeam/Unsupervised_Learning_HFI7
_test_decorators.py
check_file_leaks
check_file_leaks
Decorate a test function to check that we are not leaking file descriptors.
[ "Decorate", "a", "test", "function", "to", "check", "that", "we", "are", "not", "leaking", "file", "descriptors." ]
def check_file_leaks(func) -> Callable: with file_leak_context(): return func
['def', 'check_file_leaks(func)', '->', 'Callable:', 'with', 'file_leak_context():', 'return', 'func']
453,955
greydanus/pythonic_ocr
urls.py
BaseURL.decode_netloc
decode_netloc
Decodes the netloc part into a string.
[ "Decodes", "the", "netloc", "part", "into", "a", "string." ]
def decode_netloc(self): rv = _decode_idna(self.host or '') if ':' in rv: rv = '[%s]' % rv port = self.port if port is not None: rv = '%s:%d' % (rv, port) auth = ':'.join(filter(None, [_url_unquote_legacy(self.raw_username or '', '/:%@'), _url_unquote_legacy(self.raw_password or '', ...
['def', 'decode_netloc(self):', 'rv', '=', '_decode_idna(self.host', 'or', "'')", 'if', "':'", 'in', 'rv:', 'rv', '=', "'[%s]'", '%', 'rv', 'port', '=', 'self.port', 'if', 'port', 'is', 'not', 'None:', 'rv', '=', "'%s:%d'", '%', '(rv,', 'port)', 'auth', '=', "':'.join(filter(None,", '[_url_unquote_legacy(self.raw_usern...
301,133
TrellixVulnTeam/Unsupervised_Learning_HFI7
client.py
KernelClient.iopub_channel
iopub_channel
Get the iopub channel object for this kernel.
[ "Get", "the", "iopub", "channel", "object", "for", "this", "kernel." ]
def iopub_channel(self): if self._iopub_channel is None: url = self._make_url('iopub') self.log.debug('connecting iopub channel to %s', url) socket = self.connect_iopub() self._iopub_channel = self.iopub_channel_class(socket, self.session, self.ioloop) return self._iopub_channel
['def', 'iopub_channel(self):', 'if', 'self._iopub_channel', 'is', 'None:', 'url', '=', "self._make_url('iopub')", "self.log.debug('connecting", 'iopub', 'channel', 'to', "%s',", 'url)', 'socket', '=', 'self.connect_iopub()', 'self._iopub_channel', '=', 'self.iopub_channel_class(socket,', 'self.session,', 'self.ioloop)...
449,779
gunthercox/ChatterBot
fst.py
Values.subtract
subtract
Subtracts the "common" part (the prefix) from the given value.
[ "Subtracts", "the", "\"common\"", "part", "(the", "prefix)", "from", "the", "given", "value." ]
def subtract(v, prefix): raise NotImplementedError
['def', 'subtract(v,', 'prefix):', 'raise', 'NotImplementedError']
484,331
Ruturaj123/Flowchart-Detection
debug_test.py
DebugClassifierTest.testMultiClass_MatrixData_Labels1D
testMultiClass_MatrixData_Labels1D
Same as the last test, but label shape is [150] instead of [150, 1].
[ "Same", "as", "the", "last", "test,", "but", "label", "shape", "is", "[150]", "instead", "of", "[150,", "1]." ]
def testMultiClass_MatrixData_Labels1D(self): def _input_fn(): iris = base.load_iris() return ({'feature': constant_op.constant(iris.data, dtype=dtypes.float32)}, constant_op.constant(iris.target, shape=[150], dtype=dtypes.int32)) classifier = debug.DebugClassifier(n_classes=3) classifier.f...
['def', 'testMultiClass_MatrixData_Labels1D(self):', 'def', '_input_fn():', 'iris', '=', 'base.load_iris()', 'return', "({'feature':", 'constant_op.constant(iris.data,', 'dtype=dtypes.float32)},', 'constant_op.constant(iris.target,', 'shape=[150],', 'dtype=dtypes.int32))', 'classifier', '=', 'debug.DebugClassifier(n_cl...
603,861
mo-cv/pycv
utils.py
widthHeightDividedBy
widthHeightDividedBy
Return an image's dimensions, divided by a value.
[ "Return", "an", "image's", "dimensions,", "divided", "by", "a", "value." ]
def widthHeightDividedBy(image, divisor): (h, w) = image.shape[:2] return (w / divisor, h / divisor)
['def', 'widthHeightDividedBy(image,', 'divisor):', '(h,', 'w)', '=', 'image.shape[:2]', 'return', '(w', '/', 'divisor,', 'h', '/', 'divisor)']
819,477
Ruturaj123/Flowchart-Detection
base_ui.py
BaseUI.set_help_intro
set_help_intro
Set an introductory message to the help output of the command registry.
[ "Set", "an", "introductory", "message", "to", "the", "help", "output", "of", "the", "command", "registry." ]
def set_help_intro(self, help_intro): self._command_handler_registry.set_help_intro(help_intro=help_intro)
['def', 'set_help_intro(self,', 'help_intro):', 'self._command_handler_registry.set_help_intro(help_intro=help_intro)']
605,007
uci-cbcl/HLA-bind
HLA_CNN.py
inference
inference
Makes inference prediction on the test file.
[ "Makes", "inference", "prediction", "on", "the", "test", "file." ]
def inference(dirnames): (datasets, _) = read_in_datasets(dirnames) Y_pred = make_predictions(dirnames, datasets) write_predictions(dirnames, Y_pred)
['def', 'inference(dirnames):', '(datasets,', '_)', '=', 'read_in_datasets(dirnames)', 'Y_pred', '=', 'make_predictions(dirnames,', 'datasets)', 'write_predictions(dirnames,', 'Y_pred)']
206,674
aasimkhan0207/computer_vision
cpp_lint.py
GetLineWidth
GetLineWidth
Determines the width of the line in column positions.
[ "Determines", "the", "width", "of", "the", "line", "in", "column", "positions." ]
def GetLineWidth(line): if isinstance(line, unicode): width = 0 for uc in unicodedata.normalize('NFC', line): if unicodedata.east_asian_width(uc) in ('W', 'F'): width += 2 elif not unicodedata.combining(uc): width += 1 return width ...
['def', 'GetLineWidth(line):', 'if', 'isinstance(line,', 'unicode):', 'width', '=', '0', 'for', 'uc', 'in', "unicodedata.normalize('NFC',", 'line):', 'if', 'unicodedata.east_asian_width(uc)', 'in', "('W',", "'F'):", 'width', '+=', '2', 'elif', 'not', 'unicodedata.combining(uc):', 'width', '+=', '1', 'return', 'width', ...
473,705
microsoft/nni
trial.py
generate_predict_json
generate_predict_json
Generate json by prediction.
[ "Generate", "json", "by", "prediction." ]
def generate_predict_json(position1_result, position2_result, ids, passage_tokens): predict_len = len(position1_result) logger.debug('total prediction num is %s', str(predict_len)) answers = {} for i in range(predict_len): sample_id = ids[i] (passage, tokens) = passage_tokens[i] ...
['def', 'generate_predict_json(position1_result,', 'position2_result,', 'ids,', 'passage_tokens):', 'predict_len', '=', 'len(position1_result)', "logger.debug('total", 'prediction', 'num', 'is', "%s',", 'str(predict_len))', 'answers', '=', '{}', 'for', 'i', 'in', 'range(predict_len):', 'sample_id', '=', 'ids[i]', '(pas...
728,194
jbalogh/jingo
__init__.py
Template.render
render
Render's a template, context can be a Django Context or a dictionary.
[ "Render's", "a", "template,", "context", "can", "be", "a", "Django", "Context", "or", "a", "dictionary." ]
def render(self, context={}): context_dict = {} if hasattr(context, 'dicts'): for d in context.dicts: context_dict.update(d) else: context_dict = context class FakeRequestContext: dicts = [context] context = FakeRequestContext() if settings.TEMPLA...
['def', 'render(self,', 'context={}):', 'context_dict', '=', '{}', 'if', 'hasattr(context,', "'dicts'):", 'for', 'd', 'in', 'context.dicts:', 'context_dict.update(d)', 'else:', 'context_dict', '=', 'context', 'class', 'FakeRequestContext:', 'dicts', '=', '[context]', 'context', '=', 'FakeRequestContext()', 'if', 'setti...
247,131
TengXiaoDai/DistributedCrawling
codecs.py
IncrementalEncoder.getstate
getstate
Return the current state of the encoder.
[ "Return", "the", "current", "state", "of", "the", "encoder." ]
def getstate(self): return 0
['def', 'getstate(self):', 'return', '0']
187,780
microsoft/InnerEye-DeepLearning
test_crop_size_multiple.py
test_restrict_crop_size_too_small
test_restrict_crop_size_too_small
Test the modification of crop sizes when the image size is below the minimum.
[ "Test", "the", "modification", "of", "crop", "sizes", "when", "the", "image", "size", "is", "below", "the", "minimum." ]
def test_restrict_crop_size_too_small() -> None: shape = (10, 30, 40) crop_size = (20, 40, 20) stride = (10, 20, 20) constraint = CropSizeConstraints(multiple_of=16) with pytest.raises(ValueError) as e: constraint.restrict_crop_size_to_image(shape, crop_size, stride) assert str(shape) in...
['def', 'test_restrict_crop_size_too_small()', '->', 'None:', 'shape', '=', '(10,', '30,', '40)', 'crop_size', '=', '(20,', '40,', '20)', 'stride', '=', '(10,', '20,', '20)', 'constraint', '=', 'CropSizeConstraints(multiple_of=16)', 'with', 'pytest.raises(ValueError)', 'as', 'e:', 'constraint.restrict_crop_size_to_imag...
613,709
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjModelWrapper.actuator_length0
actuator_length0
actuator length in qpos0 (nu x 1).
[ "actuator", "length", "in", "qpos0", "(nu", "x", "1)." ]
def actuator_length0(self): return util.buf_to_npy(self._ptr.contents.actuator_length0, (self.nu,))
['def', 'actuator_length0(self):', 'return', 'util.buf_to_npy(self._ptr.contents.actuator_length0,', '(self.nu,))']
440,447
rlgraph/rlgraph
activation_functions.py
get_activation_function
get_activation_function
Returns an activation function (callable) to use in a NN layer.
[ "Returns", "an", "activation", "function", "(callable)", "to", "use", "in", "a", "NN", "layer." ]
def get_activation_function(activation_function=None, *other_parameters): if get_backend() == 'tf': if activation_function is None or callable(activation_function): return activation_function elif activation_function == 'linear': return tf.identity elif activation_fun...
['def', 'get_activation_function(activation_function=None,', '*other_parameters):', 'if', 'get_backend()', '==', "'tf':", 'if', 'activation_function', 'is', 'None', 'or', 'callable(activation_function):', 'return', 'activation_function', 'elif', 'activation_function', '==', "'linear':", 'return', 'tf.identity', 'elif',...
862,487
ryu-ed/SpaceInvaders_Ros
math2html.py
FilePosition.extract
extract
Extract the next string of the given length, or None if not enough text.
[ "Extract", "the", "next", "string", "of", "the", "given", "length,", "or", "None", "if", "not", "enough", "text." ]
def extract(self, length): if self.pos + length > len(self.reader.currentline()): return None return self.reader.currentline()[self.pos:self.pos + length]
['def', 'extract(self,', 'length):', 'if', 'self.pos', '+', 'length', '>', 'len(self.reader.currentline()):', 'return', 'None', 'return', 'self.reader.currentline()[self.pos:self.pos', '+', 'length]']
395,138
asyml/texar
rnn_encoders.py
BidirectionalRNNEncoder.cell_fw
cell_fw
The forward RNN cell.
[ "The", "forward", "RNN", "cell." ]
def cell_fw(self): return self._cell_fw
['def', 'cell_fw(self):', 'return', 'self._cell_fw']
924,717
triaquae/triaquae
storage.py
Storage.get_valid_name
get_valid_name
Returns a filename, based on the provided filename, that's suitable for use in the target storage system.
[ "Returns", "a", "filename,", "based", "on", "the", "provided", "filename,", "that's", "suitable", "for", "use", "in", "the", "target", "storage", "system." ]
def get_valid_name(self, name): return get_valid_filename(name)
['def', 'get_valid_name(self,', 'name):', 'return', 'get_valid_filename(name)']
358,281
43Carrig/recurrent_neural_networks_practice
common_shapes.py
unchanged_shape
unchanged_shape
Shape function for ops that output a tensor like their first input.
[ "Shape", "function", "for", "ops", "that", "output", "a", "tensor", "like", "their", "first", "input." ]
def unchanged_shape(op): return [op.inputs[0].get_shape()]
['def', 'unchanged_shape(op):', 'return', '[op.inputs[0].get_shape()]']
336,241
softwarearchitect817/Efficient-Geometry-aware-3D
util.py
get_obj_by_name
get_obj_by_name
Finds the python object with the given name.
[ "Finds", "the", "python", "object", "with", "the", "given", "name." ]
def get_obj_by_name(name: str) -> Any: (module, obj_name) = get_module_from_obj_name(name) return get_obj_from_module(module, obj_name)
['def', 'get_obj_by_name(name:', 'str)', '->', 'Any:', '(module,', 'obj_name)', '=', 'get_module_from_obj_name(name)', 'return', 'get_obj_from_module(module,', 'obj_name)']
548,611
rudranil723/mini-main
sql.py
Identifier.is_wildcard
is_wildcard
Return ``True`` if this identifier contains a wildcard.
[ "Return", "``True``", "if", "this", "identifier", "contains", "a", "wildcard." ]
def is_wildcard(self): (_, token) = self.token_next_by(t=T.Wildcard) return token is not None
['def', 'is_wildcard(self):', '(_,', 'token)', '=', 'self.token_next_by(t=T.Wildcard)', 'return', 'token', 'is', 'not', 'None']
270,672
usmancheema89/computer_vision
sast_process.py
SASTProcessTrain.vector_angle
vector_angle
Calculate the angle between vector AB and x-axis positive direction.
[ "Calculate", "the", "angle", "between", "vector", "AB", "and", "x-axis", "positive", "direction." ]
def vector_angle(self, A, B): AB = np.array([B[1] - A[1], B[0] - A[0]]) return np.arctan2(*AB)
['def', 'vector_angle(self,', 'A,', 'B):', 'AB', '=', 'np.array([B[1]', '-', 'A[1],', 'B[0]', '-', 'A[0]])', 'return', 'np.arctan2(*AB)']
502,109
NoGameNoLife00/mybolg
itsdangerous.py
is_text_serializer
is_text_serializer
Checks wheather a serializer generates text or binary.
[ "Checks", "wheather", "a", "serializer", "generates", "text", "or", "binary." ]
def is_text_serializer(serializer): return isinstance(serializer.dumps({}), text_type)
['def', 'is_text_serializer(serializer):', 'return', 'isinstance(serializer.dumps({}),', 'text_type)']
289,061
rishab-sharma/object_detection
dataset.py
eval_pascal_one_class
eval_pascal_one_class
Evaluate the detection result for one class on PASCAL dataset.
[ "Evaluate", "the", "detection", "result", "for", "one", "class", "on", "PASCAL", "dataset." ]
def eval_pascal_one_class(pascal, detections, c): gts = {} num_objs = 0 for img_name in pascal: gts[img_name] = [] for obj in pascal[img_name]: if obj['class_id'] == c and obj['difficult'] == 0: gts[img_name] += [{'bbox': obj['bbox'], 'detected': False}] ...
['def', 'eval_pascal_one_class(pascal,', 'detections,', 'c):', 'gts', '=', '{}', 'num_objs', '=', '0', 'for', 'img_name', 'in', 'pascal:', 'gts[img_name]', '=', '[]', 'for', 'obj', 'in', 'pascal[img_name]:', 'if', "obj['class_id']", '==', 'c', 'and', "obj['difficult']", '==', '0:', 'gts[img_name]', '+=', "[{'bbox':", "...
744,959
43Carrig/recurrent_neural_networks_practice
nccl_ops.py
broadcast
broadcast
Returns a tensor that can be efficiently transferred to other devices.
[ "Returns", "a", "tensor", "that", "can", "be", "efficiently", "transferred", "to", "other", "devices." ]
def broadcast(tensor): _validate_and_load_nccl_so() _check_device(tensor) with ops.device(tensor.device): return gen_nccl_ops.nccl_broadcast(input=tensor, shape=tensor.shape)
['def', 'broadcast(tensor):', '_validate_and_load_nccl_so()', '_check_device(tensor)', 'with', 'ops.device(tensor.device):', 'return', 'gen_nccl_ops.nccl_broadcast(input=tensor,', 'shape=tensor.shape)']
335,004
matsu0228/nlp-jp
named_commands.py
get_by_name
get_by_name
Return the handler for the (Readline) command with the given name.
[ "Return", "the", "handler", "for", "the", "(Readline)", "command", "with", "the", "given", "name." ]
def get_by_name(name): try: return _readline_commands[name] except KeyError: raise KeyError('Unknown readline command: %r' % name)
['def', 'get_by_name(name):', 'try:', 'return', '_readline_commands[name]', 'except', 'KeyError:', 'raise', "KeyError('Unknown", 'readline', 'command:', "%r'", '%', 'name)']
804,446
inseq-team/inseq
misc.py
scalar_to_numpy
scalar_to_numpy
From scalar value to numpy type.
[ "From", "scalar", "value", "to", "numpy", "type." ]
def scalar_to_numpy(data, dtype): import numpy as nptypes dtype = getattr(nptypes, dtype) return dtype(data)
['def', 'scalar_to_numpy(data,', 'dtype):', 'import', 'numpy', 'as', 'nptypes', 'dtype', '=', 'getattr(nptypes,', 'dtype)', 'return', 'dtype(data)']
613,986
yogeshbalaji/InvGAN
whitebox.py
whitebox
whitebox
Based on MNIST tutorial from cleverhans.
[ "Based", "on", "MNIST", "tutorial", "from", "cleverhans." ]
def whitebox(gan, rec_data_path=None, batch_size=128, learning_rate=0.001, nb_epochs=10, eps=0.3, online_training=False, test_on_dev=False, attack_type='fgsm', defense_type='gan', num_tests=-1, num_train=-1, cfg=None): FLAGS = tf.flags.FLAGS rng = np.random.RandomState([11, 24, 1990]) set_log_level(logging....
['def', 'whitebox(gan,', 'rec_data_path=None,', 'batch_size=128,', 'learning_rate=0.001,', 'nb_epochs=10,', 'eps=0.3,', 'online_training=False,', 'test_on_dev=False,', "attack_type='fgsm',", "defense_type='gan',", 'num_tests=-1,', 'num_train=-1,', 'cfg=None):', 'FLAGS', '=', 'tf.flags.FLAGS', 'rng', '=', 'np.random.Ran...
576,519
openvinotoolkit/training_extensions
apis.py
NaiveExporter.export2backend
export2backend
Function for exporting to openvino.
[ "Function", "for", "exporting", "to", "openvino." ]
def export2backend(output_dir: str, model_builder: Callable, cfg: mmcv.Config, input_data: Dict[Any, Any], *, precision: str='FP32', model_name: str='model', input_names: Optional[List[str]]=None, output_names: Optional[List[str]]=None, opset_version: int=11, dynamic_axes: Optional[Dict[Any, Any]]=None, mo_transforms: ...
['def', 'export2backend(output_dir:', 'str,', 'model_builder:', 'Callable,', 'cfg:', 'mmcv.Config,', 'input_data:', 'Dict[Any,', 'Any],', '*,', 'precision:', "str='FP32',", 'model_name:', "str='model',", 'input_names:', 'Optional[List[str]]=None,', 'output_names:', 'Optional[List[str]]=None,', 'opset_version:', 'int=11...
917,950
microsoft/MT-DNN
modeling_t5.py
make_3block_relative_position_ids
make_3block_relative_position_ids
Makes 3-blocked relative position ids for local attention.
[ "Makes", "3-blocked", "relative", "position", "ids", "for", "local", "attention." ]
def make_3block_relative_position_ids(block_len: int) -> torch.Tensor: position_ids = torch.arange(3 * block_len, dtype=torch.int32) center_position_ids = position_ids[block_len:-block_len] relative_position_ids = position_ids.unsqueeze(0) - center_position_ids.unsqueeze(1) return relative_position_ids
['def', 'make_3block_relative_position_ids(block_len:', 'int)', '->', 'torch.Tensor:', 'position_ids', '=', 'torch.arange(3', '*', 'block_len,', 'dtype=torch.int32)', 'center_position_ids', '=', 'position_ids[block_len:-block_len]', 'relative_position_ids', '=', 'position_ids.unsqueeze(0)', '-', 'center_position_ids.un...
642,536
suarez12138/AI-Reversi_IMP_TextDichotomy
utils.py
integer_repr
integer_repr
Return the signed-magnitude interpretation of the binary representation of x.
[ "Return", "the", "signed-magnitude", "interpretation", "of", "the", "binary", "representation", "of", "x." ]
def integer_repr(x): import numpy as np if x.dtype == np.float16: return _integer_repr(x, np.int16, np.int16(-2 ** 15)) elif x.dtype == np.float32: return _integer_repr(x, np.int32, np.int32(-2 ** 31)) elif x.dtype == np.float64: return _integer_repr(x, np.int64, np.int64(-2 ** 6...
['def', 'integer_repr(x):', 'import', 'numpy', 'as', 'np', 'if', 'x.dtype', '==', 'np.float16:', 'return', '_integer_repr(x,', 'np.int16,', 'np.int16(-2', '**', '15))', 'elif', 'x.dtype', '==', 'np.float32:', 'return', '_integer_repr(x,', 'np.int32,', 'np.int32(-2', '**', '31))', 'elif', 'x.dtype', '==', 'np.float64:',...
98,258
DrGFreeman/rps-cv
camera.py
Camera.stop
stop
Stops the camera continuous recording and stops the preview if active.
[ "Stops", "the", "camera", "continuous", "recording", "and", "stops", "the", "preview", "if", "active." ]
def stop(self): self.active = False self.picam.stop_recording() self.stopPreview()
['def', 'stop(self):', 'self.active', '=', 'False', 'self.picam.stop_recording()', 'self.stopPreview()']
827,963
clovaai/assembled-cnn
autoaugment.py
policy_v0
policy_v0
Autoaugment policy that was used in AutoAugment Paper.
[ "Autoaugment", "policy", "that", "was", "used", "in", "AutoAugment", "Paper." ]
def policy_v0(): policy = [[('Equalize', 0.8, 1), ('ShearY', 0.8, 4)], [('Color', 0.4, 9), ('Equalize', 0.6, 3)], [('Color', 0.4, 1), ('Rotate', 0.6, 8)], [('Solarize', 0.8, 3), ('Equalize', 0.4, 7)], [('Solarize', 0.4, 2), ('Solarize', 0.6, 2)], [('Color', 0.2, 0), ('Equalize', 0.8, 8)], [('Equalize', 0.4, 8), ('S...
['def', 'policy_v0():', 'policy', '=', "[[('Equalize',", '0.8,', '1),', "('ShearY',", '0.8,', '4)],', "[('Color',", '0.4,', '9),', "('Equalize',", '0.6,', '3)],', "[('Color',", '0.4,', '1),', "('Rotate',", '0.6,', '8)],', "[('Solarize',", '0.8,', '3),', "('Equalize',", '0.4,', '7)],', "[('Solarize',", '0.4,', '2),', "(...
92,475
matsu0228/nlp-jp
textpath.py
TextPath.is_math_text
is_math_text
Returns True if the given string *s* contains any mathtext.
[ "Returns", "True", "if", "the", "given", "string", "*s*", "contains", "any", "mathtext." ]
def is_math_text(self, s): dollar_count = s.count('$') - s.count('\\$') even_dollars = dollar_count > 0 and dollar_count % 2 == 0 if rcParams['text.usetex']: return (s, 'TeX') if even_dollars: return (s, True) else: return (s.replace('\\$', '$'), False)
['def', 'is_math_text(self,', 's):', 'dollar_count', '=', "s.count('$')", '-', "s.count('\\\\$')", 'even_dollars', '=', 'dollar_count', '>', '0', 'and', 'dollar_count', '%', '2', '==', '0', 'if', "rcParams['text.usetex']:", 'return', '(s,', "'TeX')", 'if', 'even_dollars:', 'return', '(s,', 'True)', 'else:', 'return', "...
789,322
6chaoran/nlp
trainer.py
Trainer.stat_params
stat_params
Collects and logs parameter statisitics.
[ "Collects", "and", "logs", "parameter", "statisitics." ]
def stat_params(self): param_names = self.parameters.keys() param_info = 'name={} shape={} val_mean={:.5f} val_max={:.5f} val_std={:.5f}' for p in param_names: self.logger.info(param_info.format(p, self.parameters.get_shape(p), np.absolute(self.parameters.get(p)).mean(), self.parameters.get(p).max()...
['def', 'stat_params(self):', 'param_names', '=', 'self.parameters.keys()', 'param_info', '=', "'name={}", 'shape={}', 'val_mean={:.5f}', 'val_max={:.5f}', "val_std={:.5f}'", 'for', 'p', 'in', 'param_names:', 'self.logger.info(param_info.format(p,', 'self.parameters.get_shape(p),', 'np.absolute(self.parameters.get(p))....
808,613
AlbertoSabater/Robust-and-efficient-post-processing-for-video--
module.py
Module.save_optimizer_states
save_optimizer_states
Save optimizer (updater) state to file Parameters ---------- fname : str Path to output states file.
[ "Save", "optimizer", "(updater)", "state", "to", "file", "Parameters", "----------", "fname", ":", "str", "Path", "to", "output", "states", "file." ]
def save_optimizer_states(self, fname): assert self.optimizer_initialized if self._update_on_kvstore: self._kvstore.save_optimizer_states(fname) else: with open(fname, 'wb') as fout: fout.write(self._updater.get_states())
['def', 'save_optimizer_states(self,', 'fname):', 'assert', 'self.optimizer_initialized', 'if', 'self._update_on_kvstore:', 'self._kvstore.save_optimizer_states(fname)', 'else:', 'with', 'open(fname,', "'wb')", 'as', 'fout:', 'fout.write(self._updater.get_states())']
826,043
sbjelogr/TransferBoost
utils.py
check_numeric_dtypes
check_numeric_dtypes
Checks if all entries in an array are of a data type that can be interpreted as numeric (int, float or bool).
[ "Checks", "if", "all", "entries", "in", "an", "array", "are", "of", "a", "data", "type", "that", "can", "be", "interpreted", "as", "numeric", "(int,", "float", "or", "bool)." ]
def check_numeric_dtypes(x): x = assure_numpy_array(x) allowed_types = [bool, int, float] for element in np.nditer(x): if type(element.item()) not in allowed_types: raise TypeError('Please supply an array with only floats, ints or booleans') return x
['def', 'check_numeric_dtypes(x):', 'x', '=', 'assure_numpy_array(x)', 'allowed_types', '=', '[bool,', 'int,', 'float]', 'for', 'element', 'in', 'np.nditer(x):', 'if', 'type(element.item())', 'not', 'in', 'allowed_types:', 'raise', "TypeError('Please", 'supply', 'an', 'array', 'with', 'only', 'floats,', 'ints', 'or', "...
930,183
zackmcnulty/CSE_446-Machine_Learning
backend_bases.py
NavigationToolbar2.drag_pan
drag_pan
Callback for dragging in pan/zoom mode.
[ "Callback", "for", "dragging", "in", "pan/zoom", "mode." ]
def drag_pan(self, event): for (a, ind) in self._xypress: a.drag_pan(self._button_pressed, event.key, event.x, event.y) self.canvas.draw_idle()
['def', 'drag_pan(self,', 'event):', 'for', '(a,', 'ind)', 'in', 'self._xypress:', 'a.drag_pan(self._button_pressed,', 'event.key,', 'event.x,', 'event.y)', 'self.canvas.draw_idle()']
194,092
deepmind/dm_control
util.py
AtomicAction.begin
begin
Begins the action, signing it with the specified watermark.
[ "Begins", "the", "action,", "signing", "it", "with", "the", "specified", "watermark." ]
def begin(self, watermark): if self._watermark is None: self._watermark = watermark if self._state_change_callback is not None: self._state_change_callback(watermark)
['def', 'begin(self,', 'watermark):', 'if', 'self._watermark', 'is', 'None:', 'self._watermark', '=', 'watermark', 'if', 'self._state_change_callback', 'is', 'not', 'None:', 'self._state_change_callback(watermark)']
166,608
43Carrig/recurrent_neural_networks_practice
queue_runner_impl.py
QueueRunner.from_proto
from_proto
Returns a `QueueRunner` object created from `queue_runner_def`.
[ "Returns", "a", "`QueueRunner`", "object", "created", "from", "`queue_runner_def`." ]
def from_proto(queue_runner_def, import_scope=None): return QueueRunner(queue_runner_def=queue_runner_def, import_scope=import_scope)
['def', 'from_proto(queue_runner_def,', 'import_scope=None):', 'return', 'QueueRunner(queue_runner_def=queue_runner_def,', 'import_scope=import_scope)']
339,698
TonyLianLong/VAI-ReinforcementLearning
wrappers.py
MjrContextWrapper.skinnormalVBO
skinnormalVBO
skin vertex normal VBOs.
[ "skin", "vertex", "normal", "VBOs." ]
def skinnormalVBO(self): return self._ptr.contents.skinnormalVBO
['def', 'skinnormalVBO(self):', 'return', 'self._ptr.contents.skinnormalVBO']
440,654
giotto-ai/giotto-tda
test_simplicial.py
gen_n_neighbors
gen_n_neighbors
Generates number of neighbors as integers.
[ "Generates", "number", "of", "neighbors", "as", "integers." ]
def gen_n_neighbors(draw): n_neighbor1 = draw(integers(min_value=1, max_value=20)) n_neighbor2 = draw(integers(min_value=n_neighbor1 + 1, max_value=30)) return (n_neighbor1, n_neighbor2)
['def', 'gen_n_neighbors(draw):', 'n_neighbor1', '=', 'draw(integers(min_value=1,', 'max_value=20))', 'n_neighbor2', '=', 'draw(integers(min_value=n_neighbor1', '+', '1,', 'max_value=30))', 'return', '(n_neighbor1,', 'n_neighbor2)']
578,011
deepmind/bsuite
memory_size.py
load
load
Memory Chain environment, with variable number of bits.
[ "Memory", "Chain", "environment,", "with", "variable", "number", "of", "bits." ]
def load(num_bits: int, seed: Optional[int]=0): env = memory_chain.MemoryChain(memory_length=2, num_bits=num_bits, seed=seed) env.bsuite_num_episodes = sweep.NUM_EPISODES return env
['def', 'load(num_bits:', 'int,', 'seed:', 'Optional[int]=0):', 'env', '=', 'memory_chain.MemoryChain(memory_length=2,', 'num_bits=num_bits,', 'seed=seed)', 'env.bsuite_num_episodes', '=', 'sweep.NUM_EPISODES', 'return', 'env']
410,220
zihuitang/medical_AI_platform
_exceptions.py
SAXParseException.getColumnNumber
getColumnNumber
The column number of the end of the text where the exception occurred.
[ "The", "column", "number", "of", "the", "end", "of", "the", "text", "where", "the", "exception", "occurred." ]
def getColumnNumber(self): return self._colnum
['def', 'getColumnNumber(self):', 'return', 'self._colnum']
284,607
43Carrig/recurrent_neural_networks_practice
debug_data.py
DebugDumpDir.node_traceback
node_traceback
Try to retrieve the Python traceback of node's construction.
[ "Try", "to", "retrieve", "the", "Python", "traceback", "of", "node's", "construction." ]
def node_traceback(self, element_name): if self._python_graph is None: raise LookupError('Python graph is not available for traceback lookup') node_name = debug_graphs.get_node_name(element_name) if node_name not in self._node_traceback: raise KeyError('Cannot find node "%s" in Python graph'...
['def', 'node_traceback(self,', 'element_name):', 'if', 'self._python_graph', 'is', 'None:', 'raise', "LookupError('Python", 'graph', 'is', 'not', 'available', 'for', 'traceback', "lookup')", 'node_name', '=', 'debug_graphs.get_node_name(element_name)', 'if', 'node_name', 'not', 'in', 'self._node_traceback:', 'raise', ...
335,959
SamsungLabs/fcaf3d
image_vis.py
plot_rect3d_on_img
plot_rect3d_on_img
Plot the boundary lines of 3D rectangular on 2D images.
[ "Plot", "the", "boundary", "lines", "of", "3D", "rectangular", "on", "2D", "images." ]
def plot_rect3d_on_img(img, num_rects, rect_corners, color=(0, 255, 0), thickness=1): line_indices = ((0, 1), (0, 3), (0, 4), (1, 2), (1, 5), (3, 2), (3, 7), (4, 5), (4, 7), (2, 6), (5, 6), (6, 7)) for i in range(num_rects): corners = rect_corners[i].astype(np.int) for (start, end) in line_indic...
['def', 'plot_rect3d_on_img(img,', 'num_rects,', 'rect_corners,', 'color=(0,', '255,', '0),', 'thickness=1):', 'line_indices', '=', '((0,', '1),', '(0,', '3),', '(0,', '4),', '(1,', '2),', '(1,', '5),', '(3,', '2),', '(3,', '7),', '(4,', '5),', '(4,', '7),', '(2,', '6),', '(5,', '6),', '(6,', '7))', 'for', 'i', 'in', '...
560,280
aws/sagemaker-python-sdk
helpers.py
_IsModelCardObject.decode
decode
Decode the value to a custom class object.
[ "Decode", "the", "value", "to", "a", "custom", "class", "object." ]
def decode(self, value: dict): try: return self.custom_class._from_dict(value) except TypeError as e: raise TypeError(f'class {self.custom_class} {str(e)}')
['def', 'decode(self,', 'value:', 'dict):', 'try:', 'return', 'self.custom_class._from_dict(value)', 'except', 'TypeError', 'as', 'e:', 'raise', "TypeError(f'class", '{self.custom_class}', "{str(e)}')"]
830,371
jindongwang/transferlearning
ctc_aligner.py
make_pad_mask
make_pad_mask
Make mask for padding.
[ "Make", "mask", "for", "padding." ]
def make_pad_mask(seq_lens): bs = seq_lens.size(0) max_time = seq_lens.max() seq_range = torch.arange(0, max_time, dtype=torch.int32, device=seq_lens.device) seq_range = seq_range.unsqueeze(0).expand(bs, max_time) mask = seq_range < seq_lens.unsqueeze(-1) return mask
['def', 'make_pad_mask(seq_lens):', 'bs', '=', 'seq_lens.size(0)', 'max_time', '=', 'seq_lens.max()', 'seq_range', '=', 'torch.arange(0,', 'max_time,', 'dtype=torch.int32,', 'device=seq_lens.device)', 'seq_range', '=', 'seq_range.unsqueeze(0).expand(bs,', 'max_time)', 'mask', '=', 'seq_range', '<', 'seq_lens.unsqueeze(...
904,501
leimao/DeepLab-V3
pix2pix.py
pix2pix_discriminator
pix2pix_discriminator
Creates the Image2Image Translation Discriminator.
[ "Creates", "the", "Image2Image", "Translation", "Discriminator." ]
def pix2pix_discriminator(net, num_filters, padding=2, is_training=False): del is_training end_points = {} num_layers = len(num_filters) def padded(net, scope): if padding: with tf.variable_scope(scope): spatial_pad = tf.constant([[0, 0], [padding, padding], [padding...
['def', 'pix2pix_discriminator(net,', 'num_filters,', 'padding=2,', 'is_training=False):', 'del', 'is_training', 'end_points', '=', '{}', 'num_layers', '=', 'len(num_filters)', 'def', 'padded(net,', 'scope):', 'if', 'padding:', 'with', 'tf.variable_scope(scope):', 'spatial_pad', '=', 'tf.constant([[0,', '0],', '[paddin...
521,325
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
requires
requires
Raise ResourceDenied if the specified resource is not available.
[ "Raise", "ResourceDenied", "if", "the", "specified", "resource", "is", "not", "available." ]
def requires(resource, msg=None): if not is_resource_enabled(resource): if msg is None: msg = 'Use of the %r resource not enabled' % resource raise ResourceDenied(msg) if resource == 'gui' and (not _is_gui_available()): raise ResourceDenied(_is_gui_available.reason)
['def', 'requires(resource,', 'msg=None):', 'if', 'not', 'is_resource_enabled(resource):', 'if', 'msg', 'is', 'None:', 'msg', '=', "'Use", 'of', 'the', '%r', 'resource', 'not', "enabled'", '%', 'resource', 'raise', 'ResourceDenied(msg)', 'if', 'resource', '==', "'gui'", 'and', '(not', '_is_gui_available()):', 'raise', ...
376,526
samxuxiang/SkexGen
transformer.py
TransformerEncoder.forward
forward
Pass the input through the encoder layers in turn.
[ "Pass", "the", "input", "through", "the", "encoder", "layers", "in", "turn." ]
def forward(self, src, memory2=None, mask=None, src_key_padding_mask=None): output = src for mod in self.layers: output = mod(output, memory2=memory2, src_mask=mask, src_key_padding_mask=src_key_padding_mask) if self.norm is not None: output = self.norm(output) return output
['def', 'forward(self,', 'src,', 'memory2=None,', 'mask=None,', 'src_key_padding_mask=None):', 'output', '=', 'src', 'for', 'mod', 'in', 'self.layers:', 'output', '=', 'mod(output,', 'memory2=memory2,', 'src_mask=mask,', 'src_key_padding_mask=src_key_padding_mask)', 'if', 'self.norm', 'is', 'not', 'None:', 'output', '=...
884,673
43Carrig/recurrent_neural_networks_practice
rnn_cell.py
IndyLSTMCell.call
call
Independent Long short-term memory cell (IndyLSTM).
[ "Independent", "Long", "short-term", "memory", "cell", "(IndyLSTM)." ]
def call(self, inputs, state): sigmoid = math_ops.sigmoid one = constant_op.constant(1, dtype=dtypes.int32) (c, h) = state gate_inputs = math_ops.matmul(inputs, self._kernel_w) gate_inputs += gen_array_ops.tile(h, [1, 4]) * self._kernel_u gate_inputs = nn_ops.bias_add(gate_inputs, self._bias) ...
['def', 'call(self,', 'inputs,', 'state):', 'sigmoid', '=', 'math_ops.sigmoid', 'one', '=', 'constant_op.constant(1,', 'dtype=dtypes.int32)', '(c,', 'h)', '=', 'state', 'gate_inputs', '=', 'math_ops.matmul(inputs,', 'self._kernel_w)', 'gate_inputs', '+=', 'gen_array_ops.tile(h,', '[1,', '4])', '*', 'self._kernel_u', 'g...
335,124
MycroftAI/mycroft-core
listener.py
RecognizerLoop.unmute
unmute
Unmute mic if as many unmute calls as mute calls have been received.
[ "Unmute", "mic", "if", "as", "many", "unmute", "calls", "as", "mute", "calls", "have", "been", "received." ]
def unmute(self): if self.mute_calls > 0: self.mute_calls -= 1 if self.mute_calls <= 0 and self.microphone: self.microphone.unmute() self.mute_calls = 0
['def', 'unmute(self):', 'if', 'self.mute_calls', '>', '0:', 'self.mute_calls', '-=', '1', 'if', 'self.mute_calls', '<=', '0', 'and', 'self.microphone:', 'self.microphone.unmute()', 'self.mute_calls', '=', '0']
290,289
CEA-LIST/SCE
linear_classifier.py
LinearClassifierEvaluation.training_steps_per_epoch
training_steps_per_epoch
Total training steps inferred from datamodule and devices.
[ "Total", "training", "steps", "inferred", "from", "datamodule", "and", "devices." ]
def training_steps_per_epoch(self) -> Optional[int]: if self.trainer.datamodule is not None: return self.trainer.datamodule.train_num_samples // self.trainer.datamodule.train_global_batch_size else: return None
['def', 'training_steps_per_epoch(self)', '->', 'Optional[int]:', 'if', 'self.trainer.datamodule', 'is', 'not', 'None:', 'return', 'self.trainer.datamodule.train_num_samples', '//', 'self.trainer.datamodule.train_global_batch_size', 'else:', 'return', 'None']
329,459
ioflo/ioflo
serialing.py
ConsoleNb.put
put
Writes data string to console.
[ "Writes", "data", "string", "to", "console." ]
def put(self, data='\n'): return os.write(self.fd, data)
['def', 'put(self,', "data='\\n'):", 'return', 'os.write(self.fd,', 'data)']
246,369
UWARG/computer-vision-python
test_add_or_multiply.py
TestSwap.test_swap_add_to_multiply
test_swap_add_to_multiply
Add and then multiply.
[ "Add", "and", "then", "multiply." ]
def test_swap_add_to_multiply(self, adder: add_or_multiply.AddOrMultiply): expected = add_or_multiply.MathOperation.MULTIPLY adder.swap_state() actual = adder._AddOrMultiply__operator assert actual == expected
['def', 'test_swap_add_to_multiply(self,', 'adder:', 'add_or_multiply.AddOrMultiply):', 'expected', '=', 'add_or_multiply.MathOperation.MULTIPLY', 'adder.swap_state()', 'actual', '=', 'adder._AddOrMultiply__operator', 'assert', 'actual', '==', 'expected']
470,442
tensorflow/privacy
losses.py
StrongConvexMixin.gamma
gamma
Returns strongly convex parameter, gamma.
[ "Returns", "strongly", "convex", "parameter,", "gamma." ]
def gamma(self): raise NotImplementedError('Gamma not implemented for StrongConvex Lossfunction: %s' % str(self.__class__.__name__))
['def', 'gamma(self):', 'raise', "NotImplementedError('Gamma", 'not', 'implemented', 'for', 'StrongConvex', 'Lossfunction:', "%s'", '%', 'str(self.__class__.__name__))']
824,613
Kvatsx/Artificial-Intelligence-Assignments
scale.py
LinearScale.set_default_locators_and_formatters
set_default_locators_and_formatters
Set the locators and formatters to reasonable defaults for linear scaling.
[ "Set", "the", "locators", "and", "formatters", "to", "reasonable", "defaults", "for", "linear", "scaling." ]
def set_default_locators_and_formatters(self, axis): axis.set_major_locator(AutoLocator()) axis.set_major_formatter(ScalarFormatter()) axis.set_minor_formatter(NullFormatter()) if rcParams['xtick.minor.visible']: axis.set_minor_locator(AutoMinorLocator()) else: axis.set_minor_locator...
['def', 'set_default_locators_and_formatters(self,', 'axis):', 'axis.set_major_locator(AutoLocator())', 'axis.set_major_formatter(ScalarFormatter())', 'axis.set_minor_formatter(NullFormatter())', 'if', "rcParams['xtick.minor.visible']:", 'axis.set_minor_locator(AutoMinorLocator())', 'else:', 'axis.set_minor_locator(Nul...
848
for-ai/rl
test_cost.py
TestPPO.test_ppo_tensordict_keys_run
test_ppo_tensordict_keys_run
Test PPO loss module with non-default tensordict keys.
[ "Test", "PPO", "loss", "module", "with", "non-default", "tensordict", "keys." ]
def test_ppo_tensordict_keys_run(self, loss_class, advantage, td_est): torch.manual_seed(self.seed) gradient_mode = True tensor_keys = {'advantage': 'advantage_test', 'value_target': 'value_target_test', 'value': 'state_value_test', 'sample_log_prob': 'sample_log_prob_test', 'action': 'action_test'} td ...
['def', 'test_ppo_tensordict_keys_run(self,', 'loss_class,', 'advantage,', 'td_est):', 'torch.manual_seed(self.seed)', 'gradient_mode', '=', 'True', 'tensor_keys', '=', "{'advantage':", "'advantage_test',", "'value_target':", "'value_target_test',", "'value':", "'state_value_test',", "'sample_log_prob':", "'sample_log_...
858,366
JihongJu/keras-fcn
test_models.py
test_fcn_vgg16_correctness
test_fcn_vgg16_correctness
Test output not NaN.
[ "Test", "output", "not", "NaN." ]
def test_fcn_vgg16_correctness(): if K.image_data_format() == 'channels_first': input_shape = (3, 500, 500) x = np.random.rand(1, 3, 500, 500) y = np.random.randint(21, size=(1, 500, 500)) y = np.eye(21)[y] y = np.transpose(y, (0, 3, 1, 2)) else: input_shape = (50...
['def', 'test_fcn_vgg16_correctness():', 'if', 'K.image_data_format()', '==', "'channels_first':", 'input_shape', '=', '(3,', '500,', '500)', 'x', '=', 'np.random.rand(1,', '3,', '500,', '500)', 'y', '=', 'np.random.randint(21,', 'size=(1,', '500,', '500))', 'y', '=', 'np.eye(21)[y]', 'y', '=', 'np.transpose(y,', '(0,'...
247,693
open-mmlab/mmsegmentation
sep_aspp_contrast_head.py
DepthwiseSeparableASPPContrastHead.predict_by_feat
predict_by_feat
Transform a batch of output seg_logits to the input shape.
[ "Transform", "a", "batch", "of", "output", "seg_logits", "to", "the", "input", "shape." ]
def predict_by_feat(self, seg_logits: Tuple[Tensor], batch_img_metas: List[dict]) -> Tensor: if isinstance(seg_logits, tuple): seg_logit = seg_logits[0] if seg_logit.size(1) == 26: hiera_num_classes = 7 seg_logit[:, 0:2] += seg_logit[:, -7] seg_logit[:, 2:5] += seg_logit[:, -6] ...
['def', 'predict_by_feat(self,', 'seg_logits:', 'Tuple[Tensor],', 'batch_img_metas:', 'List[dict])', '->', 'Tensor:', 'if', 'isinstance(seg_logits,', 'tuple):', 'seg_logit', '=', 'seg_logits[0]', 'if', 'seg_logit.size(1)', '==', '26:', 'hiera_num_classes', '=', '7', 'seg_logit[:,', '0:2]', '+=', 'seg_logit[:,', '-7]', ...
625,553
Ikomia-dev/IkomiaApi
pyqtutils.py
add_combo
add_combo
Add a combo box and its label in the layout at the given row.
[ "Add", "a", "combo", "box", "and", "its", "label", "in", "the", "layout", "at", "the", "given", "row." ]
def add_combo(grid_layout, row, label): qlabel = QLabel(label) qcombo = QComboBox() grid_layout.addWidget(qlabel, row, 0) grid_layout.addWidget(qcombo, row, 1) return qcombo
['def', 'add_combo(grid_layout,', 'row,', 'label):', 'qlabel', '=', 'QLabel(label)', 'qcombo', '=', 'QComboBox()', 'grid_layout.addWidget(qlabel,', 'row,', '0)', 'grid_layout.addWidget(qcombo,', 'row,', '1)', 'return', 'qcombo']
598,728
rudranil723/mini-main
axis.py
YTick.update_position
update_position
Set the location of tick in data coords with scalar *loc*.
[ "Set", "the", "location", "of", "tick", "in", "data", "coords", "with", "scalar", "*loc*." ]
def update_position(self, loc): self.tick1line.set_ydata((loc,)) self.tick2line.set_ydata((loc,)) self.gridline.set_ydata((loc,)) self.label1.set_y(loc) self.label2.set_y(loc) self._loc = loc self.stale = True
['def', 'update_position(self,', 'loc):', 'self.tick1line.set_ydata((loc,))', 'self.tick2line.set_ydata((loc,))', 'self.gridline.set_ydata((loc,))', 'self.label1.set_y(loc)', 'self.label2.set_y(loc)', 'self._loc', '=', 'loc', 'self.stale', '=', 'True']
318,998
robustness-gym/robustness-gym
operation.py
Operation.process
process
Apply the Operation to a DataPanel.
[ "Apply", "the", "Operation", "to", "a", "DataPanel." ]
def process(self, dp: DataPanel, columns: List[str], batch_size: int=32, *args, **kwargs) -> DataPanel: return dp.update(tuple_to_dict(keys=[str(ident(columns=columns)) for ident in self.output_identifiers])(partial(self.process_batch, *args, columns=columns, **kwargs)), *args, batch_size=batch_size, is_batched_fn=...
['def', 'process(self,', 'dp:', 'DataPanel,', 'columns:', 'List[str],', 'batch_size:', 'int=32,', '*args,', '**kwargs)', '->', 'DataPanel:', 'return', 'dp.update(tuple_to_dict(keys=[str(ident(columns=columns))', 'for', 'ident', 'in', 'self.output_identifiers])(partial(self.process_batch,', '*args,', 'columns=columns,',...
826,277
jeromewang-github/computer_vision
dataset.py
visualization
visualization
Visualize groundtruth label to image.
[ "Visualize", "groundtruth", "label", "to", "image." ]
def visualization(image_path, points, label, vis_color=(255, 255, 255)): points = np.asarray(points, dtype=np.int32) points = np.reshape(points, [-1, 2]) image = cv2.imread(image_path) cv2.polylines(image, [points], 1, (0, 255, 0), 2) image = Image.fromarray(image) FONT = ImageFont.truetype(font...
['def', 'visualization(image_path,', 'points,', 'label,', 'vis_color=(255,', '255,', '255)):', 'points', '=', 'np.asarray(points,', 'dtype=np.int32)', 'points', '=', 'np.reshape(points,', '[-1,', '2])', 'image', '=', 'cv2.imread(image_path)', 'cv2.polylines(image,', '[points],', '1,', '(0,', '255,', '0),', '2)', 'image...
501,370
befelix/safe_learning
test_functions.py
TestTriangulation.test_projected_evaluate
test_projected_evaluate
Test evaluations with enabled projection.
[ "Test", "evaluations", "with", "enabled", "projection." ]
def test_projected_evaluate(self, setup): (sess, tri, trinp, test_points) = setup trinp.project = True tri.project = True res = sess.run(tri(test_points)) assert_allclose(res, trinp(test_points))
['def', 'test_projected_evaluate(self,', 'setup):', '(sess,', 'tri,', 'trinp,', 'test_points)', '=', 'setup', 'trinp.project', '=', 'True', 'tri.project', '=', 'True', 'res', '=', 'sess.run(tri(test_points))', 'assert_allclose(res,', 'trinp(test_points))']
328,248
zackmcnulty/CSE_446-Machine_Learning
axis_artist.py
AxisArtist.get_helper
get_helper
Return axis artist helper instance.
[ "Return", "axis", "artist", "helper", "instance." ]
def get_helper(self): return self._axis_artist_helper
['def', 'get_helper(self):', 'return', 'self._axis_artist_helper']
195,469
jbwang1997/CrossKD
test_standard_roi_head.py
TestStandardRoIHead.test_init
test_init
Test init standard RoI head.
[ "Test", "init", "standard", "RoI", "head." ]
def test_init(self): roi_head_cfg = _fake_roi_head() roi_head = MODELS.build(roi_head_cfg) self.assertTrue(roi_head.with_bbox) self.assertTrue(roi_head.with_mask) roi_head_cfg = _fake_roi_head(with_shared_head=True) roi_head = MODELS.build(roi_head_cfg) self.assertTrue(roi_head.with_bbox) ...
['def', 'test_init(self):', 'roi_head_cfg', '=', '_fake_roi_head()', 'roi_head', '=', 'MODELS.build(roi_head_cfg)', 'self.assertTrue(roi_head.with_bbox)', 'self.assertTrue(roi_head.with_mask)', 'roi_head_cfg', '=', '_fake_roi_head(with_shared_head=True)', 'roi_head', '=', 'MODELS.build(roi_head_cfg)', 'self.assertTrue(...
491,949
marysia/thesis
composition.py
DataComposition.preprocess
preprocess
Preprocess the data by reshaping it to the target shape, normalizing it between values of [-1, 1], subtracting the train mean and dividing by the std, and reshaping it to contain the channel.
[ "Preprocess", "the", "data", "by", "reshaping", "it", "to", "the", "target", "shape,", "normalizing", "it", "between", "values", "of", "[-1,", "1],", "subtracting", "the", "train", "mean", "and", "dividing", "by", "the", "std,", "and", "reshaping", "it", "to...
def preprocess(self, data, scope): data[data < 0] = 0.0 data[data > 1.0] = 1.0 if scope != 'train': data = self._data_reshape(data) if scope == 'train': self.mean = np.mean(data) data -= self.mean self.std = np.std(data) data /= self.std else: data -= ...
['def', 'preprocess(self,', 'data,', 'scope):', 'data[data', '<', '0]', '=', '0.0', 'data[data', '>', '1.0]', '=', '1.0', 'if', 'scope', '!=', "'train':", 'data', '=', 'self._data_reshape(data)', 'if', 'scope', '==', "'train':", 'self.mean', '=', 'np.mean(data)', 'data', '-=', 'self.mean', 'self.std', '=', 'np.std(data...
354,727
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
test_finalization.py
NonGCSimpleBase.test
test
A context manager to use around all finalization tests.
[ "A", "context", "manager", "to", "use", "around", "all", "finalization", "tests." ]
def test(cls): with support.disable_gc(): cls.del_calls.clear() cls.tp_del_calls.clear() NonGCSimpleBase._cleaning = False try: yield if cls.errors: raise cls.errors[0] finally: NonGCSimpleBase._cleaning = True c...
['def', 'test(cls):', 'with', 'support.disable_gc():', 'cls.del_calls.clear()', 'cls.tp_del_calls.clear()', 'NonGCSimpleBase._cleaning', '=', 'False', 'try:', 'yield', 'if', 'cls.errors:', 'raise', 'cls.errors[0]', 'finally:', 'NonGCSimpleBase._cleaning', '=', 'True', 'cls._cleanup()']
376,114
copenlu/X-MAML
pipelines.py
QuestionAnsweringPipeline.span_to_answer
span_to_answer
When decoding from token probalities, this method maps token indexes to actual word in the initial context.
[ "When", "decoding", "from", "token", "probalities,", "this", "method", "maps", "token", "indexes", "to", "actual", "word", "in", "the", "initial", "context." ]
def span_to_answer(self, text: str, start: int, end: int): words = [] token_idx = char_start_idx = char_end_idx = chars_idx = 0 for (i, word) in enumerate(text.split(' ')): token = self.tokenizer.tokenize(word) if start <= token_idx <= end: if token_idx == start: ...
['def', 'span_to_answer(self,', 'text:', 'str,', 'start:', 'int,', 'end:', 'int):', 'words', '=', '[]', 'token_idx', '=', 'char_start_idx', '=', 'char_end_idx', '=', 'chars_idx', '=', '0', 'for', '(i,', 'word)', 'in', "enumerate(text.split('", "')):", 'token', '=', 'self.tokenizer.tokenize(word)', 'if', 'start', '<=', ...
961,685
mdsunivie/deeperwin
local_features.py
align_with_reference_vectors
align_with_reference_vectors
Adjust the sign of an input vector v, such that it has positive overlap with a given reference vector.
[ "Adjust", "the", "sign", "of", "an", "input", "vector", "v,", "such", "that", "it", "has", "positive", "overlap", "with", "a", "given", "reference", "vector." ]
def align_with_reference_vectors(v, ref_vectors, tol=1e-06): for v_ref in ref_vectors: overlap = v @ v_ref if np.abs(overlap) >= tol: return v * np.sign(overlap) raise ValueError('Could not determine sign of coordinate axis')
['def', 'align_with_reference_vectors(v,', 'ref_vectors,', 'tol=1e-06):', 'for', 'v_ref', 'in', 'ref_vectors:', 'overlap', '=', 'v', '@', 'v_ref', 'if', 'np.abs(overlap)', '>=', 'tol:', 'return', 'v', '*', 'np.sign(overlap)', 'raise', "ValueError('Could", 'not', 'determine', 'sign', 'of', 'coordinate', "axis')"]
520,407
Eric3911/OpenAGI
megatron_init.py
set_jit_fusion_options
set_jit_fusion_options
Set PyTorch JIT layer fusion options.
[ "Set", "PyTorch", "JIT", "layer", "fusion", "options." ]
def set_jit_fusion_options(): if torch.__version__ == '1.10.0a0+0aef44c': torch._C._jit_set_profiling_executor(True) torch._C._jit_set_profiling_mode(True) torch._C._jit_override_can_fuse_on_cpu(False) torch._C._jit_override_can_fuse_on_gpu(False) torch._C._jit_set_texpr_fuse...
['def', 'set_jit_fusion_options():', 'if', 'torch.__version__', '==', "'1.10.0a0+0aef44c':", 'torch._C._jit_set_profiling_executor(True)', 'torch._C._jit_set_profiling_mode(True)', 'torch._C._jit_override_can_fuse_on_cpu(False)', 'torch._C._jit_override_can_fuse_on_gpu(False)', 'torch._C._jit_set_texpr_fuser_enabled(Fa...
273,759
thaines/helit
params.py
Params.getLag
getLag
Returns the lag length.
[ "Returns", "the", "lag", "length." ]
def getLag(self): return self.lag
['def', 'getLag(self):', 'return', 'self.lag']
592,403
gunthercox/ChatterBot
collections.py
MappedCollection.remove
remove
Remove an item by value, consulting the keyfunc for the key.
[ "Remove", "an", "item", "by", "value,", "consulting", "the", "keyfunc", "for", "the", "key." ]
def remove(self, value, _sa_initiator=None): key = self.keyfunc(value) if self[key] != value: raise sa_exc.InvalidRequestError("Can not remove '%s': collection holds '%s' for key '%s'. Possible cause: is the MappedCollection key function based on mutable properties or properties that only obtain values ...
['def', 'remove(self,', 'value,', '_sa_initiator=None):', 'key', '=', 'self.keyfunc(value)', 'if', 'self[key]', '!=', 'value:', 'raise', 'sa_exc.InvalidRequestError("Can', 'not', 'remove', "'%s':", 'collection', 'holds', "'%s'", 'for', 'key', "'%s'.", 'Possible', 'cause:', 'is', 'the', 'MappedCollection', 'key', 'funct...
534,490
Kvatsx/Artificial-Intelligence-Assignments
arraydatatype.py
ArrayDatatype.arrayToGLType
arrayToGLType
Given a data-value, guess the OpenGL type of the corresponding pointer Note: this is not currently used in PyOpenGL and may be removed eventually.
[ "Given", "a", "data-value,", "guess", "the", "OpenGL", "type", "of", "the", "corresponding", "pointer", "Note:", "this", "is", "not", "currently", "used", "in", "PyOpenGL", "and", "may", "be", "removed", "eventually." ]
def arrayToGLType(cls, value): return cls.getHandler(value).arrayToGLType(value)
['def', 'arrayToGLType(cls,', 'value):', 'return', 'cls.getHandler(value).arrayToGLType(value)']
3,085
openvinotoolkit/training_extensions
time_monitor_callback.py
TimeMonitorCallback.on_epoch_end
on_epoch_end
Computes the average time taken to complete an epoch based on a running average of `epoch_history` epochs.
[ "Computes", "the", "average", "time", "taken", "to", "complete", "an", "epoch", "based", "on", "a", "running", "average", "of", "`epoch_history`", "epochs." ]
def on_epoch_end(self, epoch, logs=None): self.past_epoch_duration.append(time.time() - self.start_epoch_time) self._calculate_average_epoch() self.update_progress_callback(self.get_progress())
['def', 'on_epoch_end(self,', 'epoch,', 'logs=None):', 'self.past_epoch_duration.append(time.time()', '-', 'self.start_epoch_time)', 'self._calculate_average_epoch()', 'self.update_progress_callback(self.get_progress())']
918,827
tobegit3hub/deep_image_model
control_flow_ops.py
CondContext.from_proto
from_proto
Returns a `CondContext` object created from `context_def`.
[ "Returns", "a", "`CondContext`", "object", "created", "from", "`context_def`." ]
def from_proto(context_def, import_scope=None): return CondContext(context_def=context_def, import_scope=import_scope)
['def', 'from_proto(context_def,', 'import_scope=None):', 'return', 'CondContext(context_def=context_def,', 'import_scope=import_scope)']
182,837
devashish-patel/webcam-motion-detector
pygments_highlighter.py
PygmentsHighlighter.highlightBlock
highlightBlock
Highlight a block of text.
[ "Highlight", "a", "block", "of", "text." ]
def highlightBlock(self, string): prev_data = self.currentBlock().previous().userData() if prev_data is not None: self._lexer._saved_state_stack = prev_data.syntax_stack elif hasattr(self._lexer, '_saved_state_stack'): del self._lexer._saved_state_stack index = 0 for (token, text) in...
['def', 'highlightBlock(self,', 'string):', 'prev_data', '=', 'self.currentBlock().previous().userData()', 'if', 'prev_data', 'is', 'not', 'None:', 'self._lexer._saved_state_stack', '=', 'prev_data.syntax_stack', 'elif', 'hasattr(self._lexer,', "'_saved_state_stack'):", 'del', 'self._lexer._saved_state_stack', 'index',...
984,466
mcao516/Autoregressive-VAE
autoencoder_en_attn.py
Decoder.forward
forward
Forward through N identical layers.
[ "Forward", "through", "N", "identical", "layers." ]
def forward(self, x, mask=None): for (i, layer) in enumerate(self.expand_layers): mask = torch.ones(x.shape[0], 1, x.shape[1], device=x.device) x = layer(x, mask) for (i, layer) in enumerate(self.layers): mask = torch.ones(x.shape[0], 1, x.shape[1], device=x.device) x = layer(x, ...
['def', 'forward(self,', 'x,', 'mask=None):', 'for', '(i,', 'layer)', 'in', 'enumerate(self.expand_layers):', 'mask', '=', 'torch.ones(x.shape[0],', '1,', 'x.shape[1],', 'device=x.device)', 'x', '=', 'layer(x,', 'mask)', 'for', '(i,', 'layer)', 'in', 'enumerate(self.layers):', 'mask', '=', 'torch.ones(x.shape[0],', '1,...
420,333
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
SearchDialogBase.py
SearchDialogBase.close
close
Put dialog away for later use.
[ "Put", "dialog", "away", "for", "later", "use." ]
def close(self, event=None): if self.top: self.top.grab_release() self.top.withdraw()
['def', 'close(self,', 'event=None):', 'if', 'self.top:', 'self.top.grab_release()', 'self.top.withdraw()']
430,943
TrellixVulnTeam/Unsupervised_Learning_HFI7
info.py
DataFrameInfo.col_count
col_count
Number of columns to be summarized.
[ "Number", "of", "columns", "to", "be", "summarized." ]
def col_count(self) -> int: return len(self.ids)
['def', 'col_count(self)', '->', 'int:', 'return', 'len(self.ids)']
453,533
matsu0228/nlp-jp
storage_uri.py
BucketStorageUri.names_provider
names_provider
Returns True if this URI names a provider.
[ "Returns", "True", "if", "this", "URI", "names", "a", "provider." ]
def names_provider(self): return bool(not self.bucket_name)
['def', 'names_provider(self):', 'return', 'bool(not', 'self.bucket_name)']
783,883
dmcnamee/FlexModEHC
utils.py
softmax
softmax
Apply softmax to vector vec.
[ "Apply", "softmax", "to", "vector", "vec." ]
def softmax(vec, beta): check.beta_softmax(beta) if beta == np.inf: vec_sftmx = np.zeros(vec.shape) vec_sftmx[vec == np.max(vec)] = 1.0 else: vec_sftmx = softmax_scipy(vec * beta) return vec_sftmx
['def', 'softmax(vec,', 'beta):', 'check.beta_softmax(beta)', 'if', 'beta', '==', 'np.inf:', 'vec_sftmx', '=', 'np.zeros(vec.shape)', 'vec_sftmx[vec', '==', 'np.max(vec)]', '=', '1.0', 'else:', 'vec_sftmx', '=', 'softmax_scipy(vec', '*', 'beta)', 'return', 'vec_sftmx']
585,260
Shuijing725/CrowdNav_DSRNN
social_force.py
SOCIAL_FORCE.predict
predict
Produce action for agent with circular specification of social force model.
[ "Produce", "action", "for", "agent", "with", "circular", "specification", "of", "social", "force", "model." ]
def predict(self, state): delta_x = state.self_state.gx - state.self_state.px delta_y = state.self_state.gy - state.self_state.py dist_to_goal = np.sqrt(delta_x ** 2 + delta_y ** 2) desired_vx = delta_x / dist_to_goal * state.self_state.v_pref desired_vy = delta_y / dist_to_goal * state.self_state.v...
['def', 'predict(self,', 'state):', 'delta_x', '=', 'state.self_state.gx', '-', 'state.self_state.px', 'delta_y', '=', 'state.self_state.gy', '-', 'state.self_state.py', 'dist_to_goal', '=', 'np.sqrt(delta_x', '**', '2', '+', 'delta_y', '**', '2)', 'desired_vx', '=', 'delta_x', '/', 'dist_to_goal', '*', 'state.self_sta...
492,088