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 |
|---|---|---|---|---|---|---|---|---|
xiaoaleiBLUE/computer_vision | sast_postprocess.py | SASTPostProcess.quad_area | quad_area | compute area of a quad. | [
"compute",
"area",
"of",
"a",
"quad."
] | def quad_area(self, quad):
edge = [(quad[1][0] - quad[0][0]) * (quad[1][1] + quad[0][1]), (quad[2][0] - quad[1][0]) * (quad[2][1] + quad[1][1]), (quad[3][0] - quad[2][0]) * (quad[3][1] + quad[2][1]), (quad[0][0] - quad[3][0]) * (quad[0][1] + quad[3][1])]
return np.sum(edge) / 2.0 | ['def', 'quad_area(self,', 'quad):', 'edge', '=', '[(quad[1][0]', '-', 'quad[0][0])', '*', '(quad[1][1]', '+', 'quad[0][1]),', '(quad[2][0]', '-', 'quad[1][0])', '*', '(quad[2][1]', '+', 'quad[1][1]),', '(quad[3][0]', '-', 'quad[2][0])', '*', '(quad[3][1]', '+', 'quad[2][1]),', '(quad[0][0]', '-', 'quad[3][0])', '*', '... | 474,468 |
ClimbsRocks/auto_ml | utils.py | delete_rows_csr | delete_rows_csr | Remove the rows denoted by ``indices`` form the CSR sparse matrix ``mat``. | [
"Remove",
"the",
"rows",
"denoted",
"by",
"``indices``",
"form",
"the",
"CSR",
"sparse",
"matrix",
"``mat``."
] | def delete_rows_csr(mat, indices):
if not isinstance(mat, scipy.sparse.csr_matrix):
raise ValueError('works only for CSR format -- use .tocsr() first')
indices = list(indices)
mask = np.ones(mat.shape[0], dtype=bool)
mask[indices] = False
return mat[mask] | ['def', 'delete_rows_csr(mat,', 'indices):', 'if', 'not', 'isinstance(mat,', 'scipy.sparse.csr_matrix):', 'raise', "ValueError('works", 'only', 'for', 'CSR', 'format', '--', 'use', '.tocsr()', "first')", 'indices', '=', 'list(indices)', 'mask', '=', 'np.ones(mat.shape[0],', 'dtype=bool)', 'mask[indices]', '=', 'False',... | 420,512 |
sony/nnabla-rl | serializers.py | save_snapshot | save_snapshot | Save training snapshot to file. | [
"Save",
"training",
"snapshot",
"to",
"file."
] | def save_snapshot(path, algorithm):
assert isinstance(algorithm, Algorithm)
if isinstance(path, str):
path = pathlib.Path(path)
dirname = 'iteration-' + str(algorithm.iteration_num)
outdir = path / dirname
files.create_dir_if_not_exist(outdir=outdir)
training_info = _create_training_info... | ['def', 'save_snapshot(path,', 'algorithm):', 'assert', 'isinstance(algorithm,', 'Algorithm)', 'if', 'isinstance(path,', 'str):', 'path', '=', 'pathlib.Path(path)', 'dirname', '=', "'iteration-'", '+', 'str(algorithm.iteration_num)', 'outdir', '=', 'path', '/', 'dirname', 'files.create_dir_if_not_exist(outdir=outdir)',... | 734,452 |
enuguru/artificial_intelligence_and_machine_ | html.py | pair | pair | Format a pair of numbers so JavaScript can read them in an attribute. | [
"Format",
"a",
"pair",
"of",
"numbers",
"so",
"JavaScript",
"can",
"read",
"them",
"in",
"an",
"attribute."
] | def pair(ratio):
return '%s %s' % ratio | ['def', 'pair(ratio):', 'return', "'%s", "%s'", '%', 'ratio'] | 147,776 |
myothida/Supervised-Machine-Learning | xmlWriter.py | XMLWriter.write_noindent | write_noindent | Writes text without indentation. | [
"Writes",
"text",
"without",
"indentation."
] | def write_noindent(self, string):
self._writeraw(escape(string), indent=False) | ['def', 'write_noindent(self,', 'string):', 'self._writeraw(escape(string),', 'indent=False)'] | 361,043 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_preprocess_data.py | test_function_call_without_data | test_function_call_without_data | Test without data -> no replacements. | [
"Test",
"without",
"data",
"->",
"no",
"replacements."
] | def test_function_call_without_data(func):
assert func(None, 'x', 'y') == "x: ['x'], y: ['y'], ls: x, w: xyz, label: None"
assert func(None, x='x', y='y') == "x: ['x'], y: ['y'], ls: x, w: xyz, label: None"
assert func(None, 'x', 'y', label='') == "x: ['x'], y: ['y'], ls: x, w: xyz, label: "
assert func... | ['def', 'test_function_call_without_data(func):', 'assert', 'func(None,', "'x',", "'y')", '==', '"x:', "['x'],", 'y:', "['y'],", 'ls:', 'x,', 'w:', 'xyz,', 'label:', 'None"', 'assert', 'func(None,', "x='x',", "y='y')", '==', '"x:', "['x'],", 'y:', "['y'],", 'ls:', 'x,', 'w:', 'xyz,', 'label:', 'None"', 'assert', 'func(... | 97,389 |
lium-lst/nmtpy | bitext.py | BiTextIterator.mask_seqs | mask_seqs | Prepares a list of padded tensors with their masks for the given sample idxs. | [
"Prepares",
"a",
"list",
"of",
"padded",
"tensors",
"with",
"their",
"masks",
"for",
"the",
"given",
"sample",
"idxs."
] | def mask_seqs(self, idxs):
(src, src_mask) = Iterator.mask_data([self._seqs[i][0] for i in idxs])
(trg, trg_mask) = Iterator.mask_data([self._seqs[i][1] for i in idxs])
return (src, src_mask, trg, trg_mask) | ['def', 'mask_seqs(self,', 'idxs):', '(src,', 'src_mask)', '=', 'Iterator.mask_data([self._seqs[i][0]', 'for', 'i', 'in', 'idxs])', '(trg,', 'trg_mask)', '=', 'Iterator.mask_data([self._seqs[i][1]', 'for', 'i', 'in', 'idxs])', 'return', '(src,', 'src_mask,', 'trg,', 'trg_mask)'] | 294,452 |
greydanus/mr_london | lexer.py | TokenStream.look | look | Look at the next token. | [
"Look",
"at",
"the",
"next",
"token."
] | def look(self):
old_token = next(self)
result = self.current
self.push(result)
self.current = old_token
return result | ['def', 'look(self):', 'old_token', '=', 'next(self)', 'result', '=', 'self.current', 'self.push(result)', 'self.current', '=', 'old_token', 'return', 'result'] | 262,388 |
calico/basenji | blocks.py | transformer_dense | transformer_dense | Transformer block dense portion. | [
"Transformer",
"block",
"dense",
"portion."
] | def transformer_dense(inputs, out_size, dense_expansion, l2_scale, dropout, kernel_initializer):
current = tf.keras.layers.LayerNormalization()(inputs)
expansion_filters = int(dense_expansion * out_size)
current = tf.keras.layers.Dense(units=expansion_filters, kernel_regularizer=tf.keras.regularizers.l2(l2_... | ['def', 'transformer_dense(inputs,', 'out_size,', 'dense_expansion,', 'l2_scale,', 'dropout,', 'kernel_initializer):', 'current', '=', 'tf.keras.layers.LayerNormalization()(inputs)', 'expansion_filters', '=', 'int(dense_expansion', '*', 'out_size)', 'current', '=', 'tf.keras.layers.Dense(units=expansion_filters,', 'ker... | 94,541 |
georghess/voxel-mae | vote_head.py | VoteHead.multiclass_nms_single | multiclass_nms_single | Multi-class nms in single batch. | [
"Multi-class",
"nms",
"in",
"single",
"batch."
] | def multiclass_nms_single(self, obj_scores, sem_scores, bbox, points, input_meta):
bbox = input_meta['box_type_3d'](bbox, box_dim=bbox.shape[-1], with_yaw=self.bbox_coder.with_rot, origin=(0.5, 0.5, 0.5))
box_indices = bbox.points_in_boxes(points)
corner3d = bbox.corners
minmax_box3d = corner3d.new(torc... | ['def', 'multiclass_nms_single(self,', 'obj_scores,', 'sem_scores,', 'bbox,', 'points,', 'input_meta):', 'bbox', '=', "input_meta['box_type_3d'](bbox,", 'box_dim=bbox.shape[-1],', 'with_yaw=self.bbox_coder.with_rot,', 'origin=(0.5,', '0.5,', '0.5))', 'box_indices', '=', 'bbox.points_in_boxes(points)', 'corner3d', '=', ... | 380,675 |
mj-will/nessai | test_rescale_to_bounds.py | test_set_bounds | test_set_bounds | Test the set bounds method. | [
"Test",
"the",
"set",
"bounds",
"method."
] | def test_set_bounds(reparam):
reparam.parameters = ['x']
reparam.rescale_bounds = {'x': np.array([-1, 1])}
reparam.pre_rescaling = lambda x: (x / 2, np.zeros_like(x))
reparam.offsets = {'x': 1}
RescaleToBounds.set_bounds(reparam, {'x': np.array([-10, 10])})
np.testing.assert_array_equal(reparam.... | ['def', 'test_set_bounds(reparam):', 'reparam.parameters', '=', "['x']", 'reparam.rescale_bounds', '=', "{'x':", 'np.array([-1,', '1])}', 'reparam.pre_rescaling', '=', 'lambda', 'x:', '(x', '/', '2,', 'np.zeros_like(x))', 'reparam.offsets', '=', "{'x':", '1}', 'RescaleToBounds.set_bounds(reparam,', "{'x':", 'np.array([... | 292,859 |
PacktPublishing/Hands-On-Artificial--for-Banking | __init__.py | DebuggedApplication.pin_auth | pin_auth | Authenticates with the pin. | [
"Authenticates",
"with",
"the",
"pin."
] | def pin_auth(self, request):
exhausted = False
auth = False
trust = self.check_pin_trust(request.environ)
bad_cookie = False
if trust is None:
self._fail_pin_auth()
bad_cookie = True
elif trust:
auth = True
elif self._failed_pin_auth > 10:
exhausted = True
... | ['def', 'pin_auth(self,', 'request):', 'exhausted', '=', 'False', 'auth', '=', 'False', 'trust', '=', 'self.check_pin_trust(request.environ)', 'bad_cookie', '=', 'False', 'if', 'trust', 'is', 'None:', 'self._fail_pin_auth()', 'bad_cookie', '=', 'True', 'elif', 'trust:', 'auth', '=', 'True', 'elif', 'self._failed_pin_au... | 205,041 |
intel/neural-compressor | nas.py | NASBase.search_space | search_space | Setter of the search space. | [
"Setter",
"of",
"the",
"search",
"space."
] | def search_space(self, search_space):
self._search_space = search_space | ['def', 'search_space(self,', 'search_space):', 'self._search_space', '=', 'search_space'] | 738,606 |
xiongfengyan/gcnn | graph.py | replace_random_edges | replace_random_edges | Replace randomly chosen edges by random edges. | [
"Replace",
"randomly",
"chosen",
"edges",
"by",
"random",
"edges."
] | def replace_random_edges(A, noise_level):
(M, M) = A.shape
n = int(noise_level * A.nnz // 2)
indices = np.random.permutation(A.nnz // 2)[:n]
rows = np.random.randint(0, M, n)
cols = np.random.randint(0, M, n)
vals = np.random.uniform(0, 1, n)
assert len(indices) == len(rows) == len(cols) == ... | ['def', 'replace_random_edges(A,', 'noise_level):', '(M,', 'M)', '=', 'A.shape', 'n', '=', 'int(noise_level', '*', 'A.nnz', '//', '2)', 'indices', '=', 'np.random.permutation(A.nnz', '//', '2)[:n]', 'rows', '=', 'np.random.randint(0,', 'M,', 'n)', 'cols', '=', 'np.random.randint(0,', 'M,', 'n)', 'vals', '=', 'np.random... | 201,348 |
wannature/BoostMIS | custom_writer.py | CustomWriter.matplotlib_plot | matplotlib_plot | Plot stats using Matplotlib and save images. | [
"Plot",
"stats",
"using",
"Matplotlib",
"and",
"save",
"images."
] | def matplotlib_plot(self, output_dir: Union[str, Path]):
keys2 = set.union(*[set(self.get_keys2(k)) for k in self.get_keys()])
for key2 in keys2:
keys = [k for k in self.get_keys() if key2 in self.get_keys2(k)]
plt = self._plot_stats(keys, key2)
p = Path(output_dir) / f'{key2}.png'
... | ['def', 'matplotlib_plot(self,', 'output_dir:', 'Union[str,', 'Path]):', 'keys2', '=', 'set.union(*[set(self.get_keys2(k))', 'for', 'k', 'in', 'self.get_keys()])', 'for', 'key2', 'in', 'keys2:', 'keys', '=', '[k', 'for', 'k', 'in', 'self.get_keys()', 'if', 'key2', 'in', 'self.get_keys2(k)]', 'plt', '=', 'self._plot_sta... | 107,882 |
Ruturaj123/Flowchart-Detection | function.py | _DefinedFunction.grad_func_name | grad_func_name | Its gradient function's name. | [
"Its",
"gradient",
"function's",
"name."
] | def grad_func_name(self):
return self._grad_func.name if self._grad_func else None | ['def', 'grad_func_name(self):', 'return', 'self._grad_func.name', 'if', 'self._grad_func', 'else', 'None'] | 605,349 |
scikit-learn/scikit-learn | test_kernel_approximation.py | test_rbf_sampler_gamma_scale | test_rbf_sampler_gamma_scale | Check the inner value computed when `gamma='scale'`. | [
"Check",
"the",
"inner",
"value",
"computed",
"when",
"`gamma='scale'`."
] | def test_rbf_sampler_gamma_scale():
(X, y) = ([[0.0], [1.0]], [0, 1])
rbf = RBFSampler(gamma='scale')
rbf.fit(X, y)
assert rbf._gamma == pytest.approx(4) | ['def', 'test_rbf_sampler_gamma_scale():', '(X,', 'y)', '=', '([[0.0],', '[1.0]],', '[0,', '1])', 'rbf', '=', "RBFSampler(gamma='scale')", 'rbf.fit(X,', 'y)', 'assert', 'rbf._gamma', '==', 'pytest.approx(4)'] | 854,163 |
ryu-ed/SpaceInvaders_Ros | states.py | Body.parse_field_marker | parse_field_marker | Extract & return field name from a field marker match. | [
"Extract",
"&",
"return",
"field",
"name",
"from",
"a",
"field",
"marker",
"match."
] | def parse_field_marker(self, match):
field = match.group()[1:]
field = field[:field.rfind(':')]
return field | ['def', 'parse_field_marker(self,', 'match):', 'field', '=', 'match.group()[1:]', 'field', '=', "field[:field.rfind(':')]", 'return', 'field'] | 394,886 |
KalleHallden/InstaAutomator | _tifffile.py | TiffPageSeries.offset | offset | Return offset to memory-mappable data in page series. | [
"Return",
"offset",
"to",
"memory-mappable",
"data",
"in",
"page",
"series."
] | def offset(self):
if len(self.pages) == 0:
return
rgbonly = False
colormapped = self.pages[0].is_indexed
pos = 0
for page in self.pages:
if page is None:
return
if not page._is_memmappable(rgbonly, colormapped):
return
if not pos:
p... | ['def', 'offset(self):', 'if', 'len(self.pages)', '==', '0:', 'return', 'rgbonly', '=', 'False', 'colormapped', '=', 'self.pages[0].is_indexed', 'pos', '=', '0', 'for', 'page', 'in', 'self.pages:', 'if', 'page', 'is', 'None:', 'return', 'if', 'not', 'page._is_memmappable(rgbonly,', 'colormapped):', 'return', 'if', 'not... | 230,085 |
sunishsheth2009/ChatterBot | test_core.py | TestMaskedArrayMathMethodsComplex.test_varstd | test_varstd | Tests var & std on MaskedArrays. | [
"Tests",
"var",
"&",
"std",
"on",
"MaskedArrays."
] | def test_varstd(self):
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
assert_almost_equal(mX.var(axis=None), mX.compressed().var())
assert_almost_equal(mX.std(axis=None), mX.compressed().std())
assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape)
assert_equal(mX.var().shape, X.var().shape)... | ['def', 'test_varstd(self):', '(x,', 'X,', 'XX,', 'm,', 'mx,', 'mX,', 'mXX,', 'm2x,', 'm2X,', 'm2XX)', '=', 'self.d', 'assert_almost_equal(mX.var(axis=None),', 'mX.compressed().var())', 'assert_almost_equal(mX.std(axis=None),', 'mX.compressed().std())', 'assert_equal(mXX.var(axis=3).shape,', 'XX.var(axis=3).shape)', 'a... | 531,950 |
tinazhouhui/computer_vision | cpp_lint.py | UpdateIncludeState | UpdateIncludeState | Fill up the include_state with new includes found from the file. | [
"Fill",
"up",
"the",
"include_state",
"with",
"new",
"includes",
"found",
"from",
"the",
"file."
] | def UpdateIncludeState(filename, include_state, io=codecs):
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _... | ['def', 'UpdateIncludeState(filename,', 'include_state,', 'io=codecs):', 'headerfile', '=', 'None', 'try:', 'headerfile', '=', 'io.open(filename,', "'r',", "'utf8',", "'replace')", 'except', 'IOError:', 'return', 'False', 'linenum', '=', '0', 'for', 'line', 'in', 'headerfile:', 'linenum', '+=', '1', 'clean_line', '=', ... | 473,074 |
bnpy/bnpy | BernObsModel.py | BernObsModel.setPostFromEstParams | setPostFromEstParams | Set attribute Post based on values in EstParams. | [
"Set",
"attribute",
"Post",
"based",
"on",
"values",
"in",
"EstParams."
] | def setPostFromEstParams(self, EstParams, Data=None, nTotalTokens=1, **kwargs):
K = EstParams.K
D = EstParams.D
WordCounts = EstParams.phi * nTotalTokens
lam1 = WordCounts + self.Prior.lam1
lam0 = 1 - WordCounts + self.Prior.lam0
self.Post = ParamBag(K=K, D=D)
self.Post.setField('lam1', lam1... | ['def', 'setPostFromEstParams(self,', 'EstParams,', 'Data=None,', 'nTotalTokens=1,', '**kwargs):', 'K', '=', 'EstParams.K', 'D', '=', 'EstParams.D', 'WordCounts', '=', 'EstParams.phi', '*', 'nTotalTokens', 'lam1', '=', 'WordCounts', '+', 'self.Prior.lam1', 'lam0', '=', '1', '-', 'WordCounts', '+', 'self.Prior.lam0', 's... | 464,925 |
chribsen/simple-machine-learning-examples | generic.py | NDFrame.dtypes | dtypes | Return the dtypes in this object. | [
"Return",
"the",
"dtypes",
"in",
"this",
"object."
] | def dtypes(self):
from pandas import Series
return Series(self._data.get_dtypes(), index=self._info_axis, dtype=np.object_) | ['def', 'dtypes(self):', 'from', 'pandas', 'import', 'Series', 'return', 'Series(self._data.get_dtypes(),', 'index=self._info_axis,', 'dtype=np.object_)'] | 935,931 |
blokbot-io/OpenBlok | upload.py | stream_upload | stream_upload | Uploads images to cloud bucket storage. | [
"Uploads",
"images",
"to",
"cloud",
"bucket",
"storage."
] | def stream_upload(bucket, key, body, content_type, permissions=None):
config.boto_client.put_object(Bucket=str(bucket), Key=str(key), Body=body, ContentType=str(content_type))
if permissions is not None:
config.boto_client.put_object_acl(ACL=str(permissions), Bucket=str(bucket), Key=str(key)) | ['def', 'stream_upload(bucket,', 'key,', 'body,', 'content_type,', 'permissions=None):', 'config.boto_client.put_object(Bucket=str(bucket),', 'Key=str(key),', 'Body=body,', 'ContentType=str(content_type))', 'if', 'permissions', 'is', 'not', 'None:', 'config.boto_client.put_object_acl(ACL=str(permissions),', 'Bucket=str... | 274,928 |
facebookresearch/deepcluster | clustering.py | cluster_assign | cluster_assign | Creates a dataset from clustering, with clusters as labels. | [
"Creates",
"a",
"dataset",
"from",
"clustering,",
"with",
"clusters",
"as",
"labels."
] | def cluster_assign(images_lists, dataset):
assert images_lists is not None
pseudolabels = []
image_indexes = []
for (cluster, images) in enumerate(images_lists):
image_indexes.extend(images)
pseudolabels.extend([cluster] * len(images))
normalize = transforms.Normalize(mean=[0.485, 0.... | ['def', 'cluster_assign(images_lists,', 'dataset):', 'assert', 'images_lists', 'is', 'not', 'None', 'pseudolabels', '=', '[]', 'image_indexes', '=', '[]', 'for', '(cluster,', 'images)', 'in', 'enumerate(images_lists):', 'image_indexes.extend(images)', 'pseudolabels.extend([cluster]', '*', 'len(images))', 'normalize', '... | 128,322 |
intel/neural-compressor | smooth_quant.py | ORTSmoothQuant.recover | recover | Recover the model weights. | [
"Recover",
"the",
"model",
"weights."
] | def recover(self):
for (tensor_name, nodes) in self.tensors_to_node.items():
for node_info in nodes:
key = node_info[0] if self.scales_per_op else tensor_name
if key not in self.tensor_scales_info:
continue
input = node_info[1][1]
weight = nump... | ['def', 'recover(self):', 'for', '(tensor_name,', 'nodes)', 'in', 'self.tensors_to_node.items():', 'for', 'node_info', 'in', 'nodes:', 'key', '=', 'node_info[0]', 'if', 'self.scales_per_op', 'else', 'tensor_name', 'if', 'key', 'not', 'in', 'self.tensor_scales_info:', 'continue', 'input', '=', 'node_info[1][1]', 'weight... | 737,474 |
ryu-ed/SpaceInvaders_Ros | message_definition_store.py | MessageDefinitionStore.messages | messages | The list of all active messages. | [
"The",
"list",
"of",
"all",
"active",
"messages."
] | def messages(self) -> list:
return self._messages_definitions.values() | ['def', 'messages(self)', '->', 'list:', 'return', 'self._messages_definitions.values()'] | 370,121 |
nicknochnack/RealTimeSignLanguageTFJS | utils.py | get_contextual_env_base | get_contextual_env_base | Wrap env_base with additional tf ops. | [
"Wrap",
"env_base",
"with",
"additional",
"tf",
"ops."
] | def get_contextual_env_base(env_base, begin_ops=None, end_ops=None):
def init(self_, env_base):
self_._env_base = env_base
attribute_list = ['_render_mode', '_gym_env']
for attribute in attribute_list:
if hasattr(env_base, attribute):
setattr(self_, attribute, ge... | ['def', 'get_contextual_env_base(env_base,', 'begin_ops=None,', 'end_ops=None):', 'def', 'init(self_,', 'env_base):', 'self_._env_base', '=', 'env_base', 'attribute_list', '=', "['_render_mode',", "'_gym_env']", 'for', 'attribute', 'in', 'attribute_list:', 'if', 'hasattr(env_base,', 'attribute):', 'setattr(self_,', 'at... | 851,796 |
apeterswu/RL4NMT | text_encoder.py | ImageEncoder.encode | encode | Transform a string with a filename into a list of RGB integers. | [
"Transform",
"a",
"string",
"with",
"a",
"filename",
"into",
"a",
"list",
"of",
"RGB",
"integers."
] | def encode(self, s):
raise NotImplementedError | ['def', 'encode(self,', 's):', 'raise', 'NotImplementedError'] | 330,926 |
omarmhaimdat/twitter_nlp_native_swift | response.py | ResponseStreamMixin.stream | stream | The response iterable as write-only stream. | [
"The",
"response",
"iterable",
"as",
"write-only",
"stream."
] | def stream(self):
return ResponseStream(self) | ['def', 'stream(self):', 'return', 'ResponseStream(self)'] | 955,610 |
PKU-Alignment/Safe-Policy-Optimization | lagrange.py | Lagrange.compute_lambda_loss | compute_lambda_loss | Compute the loss of the lagrangian multiplier. | [
"Compute",
"the",
"loss",
"of",
"the",
"lagrangian",
"multiplier."
] | def compute_lambda_loss(self, mean_ep_cost: float) -> torch.Tensor:
return -self._lagrangian_multiplier * (mean_ep_cost - self.cost_limit) | ['def', 'compute_lambda_loss(self,', 'mean_ep_cost:', 'float)', '->', 'torch.Tensor:', 'return', '-self._lagrangian_multiplier', '*', '(mean_ep_cost', '-', 'self.cost_limit)'] | 829,075 |
openvinotoolkit/training_extensions | test_custom_max_iou_assigner.py | TestCustomMaxIoUAssigner.setup | setup | Initial setup for unit tests. | [
"Initial",
"setup",
"for",
"unit",
"tests."
] | def setup(self):
self.assigner = CustomMaxIoUAssigner(pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=True, ignore_iof_thr=-1, gpu_assign_thr=300)
self.assigner.cpu_assign_thr = 400 | ['def', 'setup(self):', 'self.assigner', '=', 'CustomMaxIoUAssigner(pos_iou_thr=0.5,', 'neg_iou_thr=0.5,', 'min_pos_iou=0.5,', 'match_low_quality=True,', 'ignore_iof_thr=-1,', 'gpu_assign_thr=300)', 'self.assigner.cpu_assign_thr', '=', '400'] | 919,327 |
MycroftAI/mycroft-core | api.py | EnclosureAPI.eyes_reset | eyes_reset | Restore the eyes to their default (ready) state. | [
"Restore",
"the",
"eyes",
"to",
"their",
"default",
"(ready)",
"state."
] | def eyes_reset(self):
self.bus.emit(Message('enclosure.eyes.reset', context={'destination': ['enclosure']})) | ['def', 'eyes_reset(self):', "self.bus.emit(Message('enclosure.eyes.reset',", "context={'destination':", "['enclosure']}))"] | 290,359 |
zhang614/MicroGrid | support.py | get_attribute | get_attribute | Get an attribute, raising SkipTest if AttributeError is raised. | [
"Get",
"an",
"attribute,",
"raising",
"SkipTest",
"if",
"AttributeError",
"is",
"raised."
] | def get_attribute(obj, name):
try:
attribute = getattr(obj, name)
except AttributeError:
raise unittest.SkipTest('object %r has no attribute %r' % (obj, name))
else:
return attribute | ['def', 'get_attribute(obj,', 'name):', 'try:', 'attribute', '=', 'getattr(obj,', 'name)', 'except', 'AttributeError:', 'raise', "unittest.SkipTest('object", '%r', 'has', 'no', 'attribute', "%r'", '%', '(obj,', 'name))', 'else:', 'return', 'attribute'] | 636,339 |
liuyuemaicha/Deep-Reinforcement-Learning-for-Dialogue-Generation-in-tensorflow | gst_seq2seq.py | sequence_loss_by_example | sequence_loss_by_example | Weighted cross-entropy loss for a sequence of logits (per example). | [
"Weighted",
"cross-entropy",
"loss",
"for",
"a",
"sequence",
"of",
"logits",
"(per",
"example)."
] | def sequence_loss_by_example(logits, targets, weights, average_across_timesteps=True, softmax_loss_function=None, name=None):
if len(targets) != len(logits) or len(weights) != len(logits):
raise ValueError('Lengths of logits, weights, and targets must be the same %d, %d, %d.' % (len(logits), len(weights), l... | ['def', 'sequence_loss_by_example(logits,', 'targets,', 'weights,', 'average_across_timesteps=True,', 'softmax_loss_function=None,', 'name=None):', 'if', 'len(targets)', '!=', 'len(logits)', 'or', 'len(weights)', '!=', 'len(logits):', 'raise', "ValueError('Lengths", 'of', 'logits,', 'weights,', 'and', 'targets', 'must'... | 128,085 |
IndicoDataSolutions/Enso | __init__.py | Experimentation.run_experiments | run_experiments | Responsible for actually running experiments. | [
"Responsible",
"for",
"actually",
"running",
"experiments."
] | def run_experiments(self):
futures = {}
experiment_validator = ValidateExperiments()
for dataset_name in DATA:
logging.info('Experimenting on %s dataset' % dataset_name)
for featurizer in self.featurizers:
logging.info('Currently using featurizer: %s' % featurizer.name())
... | ['def', 'run_experiments(self):', 'futures', '=', '{}', 'experiment_validator', '=', 'ValidateExperiments()', 'for', 'dataset_name', 'in', 'DATA:', "logging.info('Experimenting", 'on', '%s', "dataset'", '%', 'dataset_name)', 'for', 'featurizer', 'in', 'self.featurizers:', "logging.info('Currently", 'using', 'featurizer... | 562,256 |
rudranil723/mini-main | decorators.py | staff_member_required | staff_member_required | Decorator for views that checks that the user is logged in and is a staff member, redirecting to the login page if necessary. | [
"Decorator",
"for",
"views",
"that",
"checks",
"that",
"the",
"user",
"is",
"logged",
"in",
"and",
"is",
"a",
"staff",
"member,",
"redirecting",
"to",
"the",
"login",
"page",
"if",
"necessary."
] | def staff_member_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url='admin:login'):
actual_decorator = user_passes_test(lambda u: u.is_active and u.is_staff, login_url=login_url, redirect_field_name=redirect_field_name)
if view_func:
return actual_decorator(view_func)
return... | ['def', 'staff_member_required(view_func=None,', 'redirect_field_name=REDIRECT_FIELD_NAME,', "login_url='admin:login'):", 'actual_decorator', '=', 'user_passes_test(lambda', 'u:', 'u.is_active', 'and', 'u.is_staff,', 'login_url=login_url,', 'redirect_field_name=redirect_field_name)', 'if', 'view_func:', 'return', 'actu... | 314,861 |
fudan-zvg/SeaFormer | res2net.py | res2net101_26w_4s | res2net101_26w_4s | Constructs a Res2Net-101 26w4s model. | [
"Constructs",
"a",
"Res2Net-101",
"26w4s",
"model."
] | def res2net101_26w_4s(pretrained=False, **kwargs):
model_args = dict(block=Bottle2neck, layers=[3, 4, 23, 3], base_width=26, block_args=dict(scale=4), **kwargs)
return _create_res2net('res2net101_26w_4s', pretrained, **model_args) | ['def', 'res2net101_26w_4s(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottle2neck,', 'layers=[3,', '4,', '23,', '3],', 'base_width=26,', 'block_args=dict(scale=4),', '**kwargs)', 'return', "_create_res2net('res2net101_26w_4s',", 'pretrained,', '**model_args)'] | 855,580 |
Kvatsx/Artificial-Intelligence-Assignments | server.py | BaseHTTPRequestHandler.handle | handle | Handle multiple requests if necessary. | [
"Handle",
"multiple",
"requests",
"if",
"necessary."
] | def handle(self):
self.close_connection = 1
self.handle_one_request()
while not self.close_connection:
self.handle_one_request() | ['def', 'handle(self):', 'self.close_connection', '=', '1', 'self.handle_one_request()', 'while', 'not', 'self.close_connection:', 'self.handle_one_request()'] | 36,965 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | manager.py | ConfigManager.set | set | Set the config only to the user's config. | [
"Set",
"the",
"config",
"only",
"to",
"the",
"user's",
"config."
] | def set(self, section_name, data):
return self.write_config_manager.set(section_name, data) | ['def', 'set(self,', 'section_name,', 'data):', 'return', 'self.write_config_manager.set(section_name,', 'data)'] | 452,213 |
google-research/scenic | evaluator.py | get_embed_queries_fn | get_embed_queries_fn | Get query embedding function. | [
"Get",
"query",
"embedding",
"function."
] | def get_embed_queries_fn(module: nn.Module, variables: Variables) -> Callable[[jnp.ndarray], jnp.ndarray]:
@jax.jit
def embed(queries):
return module.apply(variables, text_queries=queries, train=False, method=module.text_embedder)
return embed | ['def', 'get_embed_queries_fn(module:', 'nn.Module,', 'variables:', 'Variables)', '->', 'Callable[[jnp.ndarray],', 'jnp.ndarray]:', '@jax.jit', 'def', 'embed(queries):', 'return', 'module.apply(variables,', 'text_queries=queries,', 'train=False,', 'method=module.text_embedder)', 'return', 'embed'] | 847,156 |
luisespino/artificial_intelligence | tarfile.py | nti | nti | Convert a number field to a python number. | [
"Convert",
"a",
"number",
"field",
"to",
"a",
"python",
"number."
] | def nti(s):
if s[0] != chr(128):
try:
n = int(nts(s, 'ascii', 'strict') or '0', 8)
except ValueError:
raise InvalidHeaderError('invalid header')
else:
n = 0
for i in range(len(s) - 1):
n <<= 8
n += ord(s[i + 1])
return n | ['def', 'nti(s):', 'if', 's[0]', '!=', 'chr(128):', 'try:', 'n', '=', 'int(nts(s,', "'ascii',", "'strict')", 'or', "'0',", '8)', 'except', 'ValueError:', 'raise', "InvalidHeaderError('invalid", "header')", 'else:', 'n', '=', '0', 'for', 'i', 'in', 'range(len(s)', '-', '1):', 'n', '<<=', '8', 'n', '+=', 'ord(s[i', '+', ... | 144,194 |
schulter/crbm | testcrbm.py | TestCRBM.bottomup | bottomup | Tests bottomup activities on toy example. | [
"Tests",
"bottomup",
"activities",
"on",
"toy",
"example."
] | def bottomup(self, flip):
data = self.data[:11]
nmot = 10
mlen = 5
model = CRBM(num_motifs=nmot, motif_length=mlen)
input = T.tensor4()
activ = theano.function([input], model._bottomUpActivity(input, flip))
prob = theano.function([input], model._bottomUpProbability(model._bottomUpActivity(in... | ['def', 'bottomup(self,', 'flip):', 'data', '=', 'self.data[:11]', 'nmot', '=', '10', 'mlen', '=', '5', 'model', '=', 'CRBM(num_motifs=nmot,', 'motif_length=mlen)', 'input', '=', 'T.tensor4()', 'activ', '=', 'theano.function([input],', 'model._bottomUpActivity(input,', 'flip))', 'prob', '=', 'theano.function([input],',... | 138,459 |
voxel51/fiftyone | utils_tests.py | SerializationTests.test_sample_in_dataset | test_sample_in_dataset | This test only works if the samples do not have Classification or Detection fields because of the autogenerated ObjectIDs. | [
"This",
"test",
"only",
"works",
"if",
"the",
"samples",
"do",
"not",
"have",
"Classification",
"or",
"Detection",
"fields",
"because",
"of",
"the",
"autogenerated",
"ObjectIDs."
] | def test_sample_in_dataset(self):
dataset1 = fo.Dataset()
dataset2 = fo.Dataset()
sample1 = fo.Sample(filepath='~/Desktop/test.png', tags=['test'], vector=np.arange(5), array=np.ones((2, 3)), float=5.1, bool=True, int=51)
sample2 = fo.Sample(filepath='~/Desktop/test.png', tags=['test'], vector=np.arange... | ['def', 'test_sample_in_dataset(self):', 'dataset1', '=', 'fo.Dataset()', 'dataset2', '=', 'fo.Dataset()', 'sample1', '=', "fo.Sample(filepath='~/Desktop/test.png',", "tags=['test'],", 'vector=np.arange(5),', 'array=np.ones((2,', '3)),', 'float=5.1,', 'bool=True,', 'int=51)', 'sample2', '=', "fo.Sample(filepath='~/Desk... | 584,425 |
triaquae/triaquae | coordseq.py | GEOSCoordSeq.getX | getX | Get the X value at the index. | [
"Get",
"the",
"X",
"value",
"at",
"the",
"index."
] | def getX(self, index):
return self.getOrdinate(0, index) | ['def', 'getX(self,', 'index):', 'return', 'self.getOrdinate(0,', 'index)'] | 357,745 |
Kvatsx/Artificial-Intelligence-Assignments | named_commands.py | end_of_line | end_of_line | Move to the end of the line. | [
"Move",
"to",
"the",
"end",
"of",
"the",
"line."
] | def end_of_line(event):
buff = event.current_buffer
buff.cursor_position += buff.document.get_end_of_line_position() | ['def', 'end_of_line(event):', 'buff', '=', 'event.current_buffer', 'buff.cursor_position', '+=', 'buff.document.get_end_of_line_position()'] | 75,899 |
microsoft/muzic | fairseq_task.py | FairseqTask.build_tokenizer | build_tokenizer | Build the pre-tokenizer for this task. | [
"Build",
"the",
"pre-tokenizer",
"for",
"this",
"task."
] | def build_tokenizer(self, args):
return encoders.build_tokenizer(args) | ['def', 'build_tokenizer(self,', 'args):', 'return', 'encoders.build_tokenizer(args)'] | 266,735 |
secretflow/secretflow | log_utils.py | add_log | add_log | Add two numbers in the log space. | [
"Add",
"two",
"numbers",
"in",
"the",
"log",
"space."
] | def add_log(logx, logy):
(x, y) = (min(logx, logy), max(logx, logy))
if x == -np.inf:
return y
return math.log1p(math.exp(x - y)) + y | ['def', 'add_log(logx,', 'logy):', '(x,', 'y)', '=', '(min(logx,', 'logy),', 'max(logx,', 'logy))', 'if', 'x', '==', '-np.inf:', 'return', 'y', 'return', 'math.log1p(math.exp(x', '-', 'y))', '+', 'y'] | 856,646 |
triaquae/triaquae | admin_list.py | search_form | search_form | Displays a search form for searching the list. | [
"Displays",
"a",
"search",
"form",
"for",
"searching",
"the",
"list."
] | def search_form(cl):
return {'cl': cl, 'show_result_count': cl.result_count != cl.full_result_count, 'search_var': SEARCH_VAR} | ['def', 'search_form(cl):', 'return', "{'cl':", 'cl,', "'show_result_count':", 'cl.result_count', '!=', 'cl.full_result_count,', "'search_var':", 'SEARCH_VAR}'] | 357,039 |
YannDubs/Invariant-Self-Supervised-Learning | helpers.py | cfg_save | cfg_save | Save a config as a yaml file. | [
"Save",
"a",
"config",
"as",
"a",
"yaml",
"file."
] | def cfg_save(cfg: Union[NamespaceMap, dict, Container], filename: Union[str, Path]) -> None:
if isinstance(cfg, NamespaceMap):
cfg = OmegaConf.create(namespace2dict(cfg))
elif isinstance(cfg, dict):
cfg = OmegaConf.create(cfg)
elif OmegaConf.is_config(cfg):
pass
else:
rai... | ['def', 'cfg_save(cfg:', 'Union[NamespaceMap,', 'dict,', 'Container],', 'filename:', 'Union[str,', 'Path])', '->', 'None:', 'if', 'isinstance(cfg,', 'NamespaceMap):', 'cfg', '=', 'OmegaConf.create(namespace2dict(cfg))', 'elif', 'isinstance(cfg,', 'dict):', 'cfg', '=', 'OmegaConf.create(cfg)', 'elif', 'OmegaConf.is_conf... | 245,940 |
devashish-patel/webcam-motion-detector | mistune.py | Renderer.linebreak | linebreak | Rendering line break like ``<br>``. | [
"Rendering",
"line",
"break",
"like",
"``<br>``."
] | def linebreak(self):
if self.options.get('use_xhtml'):
return '<br />\n'
return '<br>\n' | ['def', 'linebreak(self):', 'if', "self.options.get('use_xhtml'):", 'return', "'<br", "/>\\n'", 'return', "'<br>\\n'"] | 976,655 |
googleapis/python-aiplatform | test_model_monitoring.py | TestModelMonitoringConfigs.test_valid_configs | test_valid_configs | Test config creation validity. | [
"Test",
"config",
"creation",
"validity."
] | def test_valid_configs(self, data_source, data_format, skew_thresholds, attribute_skew_thresholds):
random_sample_config = model_monitoring.RandomSampleConfig(sample_rate=_TEST_SAMPLING_RATE)
schedule_config = model_monitoring.ScheduleConfig(monitor_interval=_TEST_MONITORING_INTERVAL)
alert_config = model_m... | ['def', 'test_valid_configs(self,', 'data_source,', 'data_format,', 'skew_thresholds,', 'attribute_skew_thresholds):', 'random_sample_config', '=', 'model_monitoring.RandomSampleConfig(sample_rate=_TEST_SAMPLING_RATE)', 'schedule_config', '=', 'model_monitoring.ScheduleConfig(monitor_interval=_TEST_MONITORING_INTERVAL)... | 863,051 |
myothida/Supervised-Machine-Learning | backend_managers.py | ToolManager.tools | tools | A dict mapping tool name -> controlled tool. | [
"A",
"dict",
"mapping",
"tool",
"name",
"->",
"controlled",
"tool."
] | def tools(self):
return self._tools | ['def', 'tools(self):', 'return', 'self._tools'] | 361,813 |
TheCurryMan/MedicAI | _compat.py | is_ascii_encoding | is_ascii_encoding | Checks if a given encoding is ascii. | [
"Checks",
"if",
"a",
"given",
"encoding",
"is",
"ascii."
] | def is_ascii_encoding(encoding):
try:
return codecs.lookup(encoding).name == 'ascii'
except LookupError:
return False | ['def', 'is_ascii_encoding(encoding):', 'try:', 'return', 'codecs.lookup(encoding).name', '==', "'ascii'", 'except', 'LookupError:', 'return', 'False'] | 648,122 |
ArtificialIntelligenceToolkit/aitk.robots | lightsensors.py | LightSensor.draw | draw | Draw the device on the backend. | [
"Draw",
"the",
"device",
"on",
"the",
"backend."
] | def draw(self, backend):
backend.lineWidth(1)
backend.set_stroke_style(BLACK)
if self.color_sensitivity is not None:
backend.set_fill_style(self.color_sensitivity)
else:
backend.set_fill_style(YELLOW)
backend.draw_circle(self.position[0], self.position[1], 2) | ['def', 'draw(self,', 'backend):', 'backend.lineWidth(1)', 'backend.set_stroke_style(BLACK)', 'if', 'self.color_sensitivity', 'is', 'not', 'None:', 'backend.set_fill_style(self.color_sensitivity)', 'else:', 'backend.set_fill_style(YELLOW)', 'backend.draw_circle(self.position[0],', 'self.position[1],', '2)'] | 86,755 |
zihuitang/medical_AI_platform | calendar.py | TextCalendar.prweek | prweek | Print a single week (no newline). | [
"Print",
"a",
"single",
"week",
"(no",
"newline)."
] | def prweek(self, theweek, width):
print(self.formatweek(theweek, width), end=' ') | ['def', 'prweek(self,', 'theweek,', 'width):', 'print(self.formatweek(theweek,', 'width),', "end='", "')"] | 280,141 |
muhanzhang/D-VAE | type.py | TensorType.clone | clone | Return a copy of the type optionally with a new dtype or broadcastable pattern. | [
"Return",
"a",
"copy",
"of",
"the",
"type",
"optionally",
"with",
"a",
"new",
"dtype",
"or",
"broadcastable",
"pattern."
] | def clone(self, dtype=None, broadcastable=None):
if dtype is None:
dtype = self.dtype
if broadcastable is None:
broadcastable = self.broadcastable
return self.__class__(dtype, broadcastable, name=self.name, sparse_grad=self.sparse_grad) | ['def', 'clone(self,', 'dtype=None,', 'broadcastable=None):', 'if', 'dtype', 'is', 'None:', 'dtype', '=', 'self.dtype', 'if', 'broadcastable', 'is', 'None:', 'broadcastable', '=', 'self.broadcastable', 'return', 'self.__class__(dtype,', 'broadcastable,', 'name=self.name,', 'sparse_grad=self.sparse_grad)'] | 525,651 |
intel/neural-compressor | weight_only.py | qdq_tensor | qdq_tensor | Quant dequant tensor per group. | [
"Quant",
"dequant",
"tensor",
"per",
"group."
] | def qdq_tensor(data, num_bits=4, group_size=32, scheme='asym', dtype='int', ratio=1.0):
org_shape = data.shape
(weight, scale, zp) = quant_tensor(data, num_bits, group_size, scheme, dtype, ratio)
return np.reshape(scale * (weight - zp), org_shape) | ['def', 'qdq_tensor(data,', 'num_bits=4,', 'group_size=32,', "scheme='asym',", "dtype='int',", 'ratio=1.0):', 'org_shape', '=', 'data.shape', '(weight,', 'scale,', 'zp)', '=', 'quant_tensor(data,', 'num_bits,', 'group_size,', 'scheme,', 'dtype,', 'ratio)', 'return', 'np.reshape(scale', '*', '(weight', '-', 'zp),', 'org... | 737,494 |
ZumoLabs/zpy | versioneer.py | git_versions_from_keywords | git_versions_from_keywords | Get version information from git keywords. | [
"Get",
"version",
"information",
"from",
"git",
"keywords."
] | def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:
raise NotThisMethod('no keywords at all, weird')
date = keywords.get('date')
if date is not None:
date = date.strip().replace(' ', 'T', 1).replace(' ', '', 1)
refnames = keywords['refnames'].strip()
if re... | ['def', 'git_versions_from_keywords(keywords,', 'tag_prefix,', 'verbose):', 'if', 'not', 'keywords:', 'raise', "NotThisMethod('no", 'keywords', 'at', 'all,', "weird')", 'date', '=', "keywords.get('date')", 'if', 'date', 'is', 'not', 'None:', 'date', '=', "date.strip().replace('", "',", "'T',", "1).replace('", "',", "''... | 971,872 |
arshpreetsingh/quantopian-machinelearning | __init__.py | defuse_stdlib | defuse_stdlib | Monkey patch and defuse all stdlib packages :warning: The monkey patch is an EXPERIMETNAL feature. | [
"Monkey",
"patch",
"and",
"defuse",
"all",
"stdlib",
"packages",
":warning:",
"The",
"monkey",
"patch",
"is",
"an",
"EXPERIMETNAL",
"feature."
] | def defuse_stdlib():
defused = {}
from . import cElementTree
from . import ElementTree
from . import minidom
from . import pulldom
from . import sax
from . import expatbuilder
from . import expatreader
from . import xmlrpc
xmlrpc.monkey_patch()
defused[xmlrpc] = None
for ... | ['def', 'defuse_stdlib():', 'defused', '=', '{}', 'from', '.', 'import', 'cElementTree', 'from', '.', 'import', 'ElementTree', 'from', '.', 'import', 'minidom', 'from', '.', 'import', 'pulldom', 'from', '.', 'import', 'sax', 'from', '.', 'import', 'expatbuilder', 'from', '.', 'import', 'expatreader', 'from', '.', 'impo... | 816,767 |
rlworkgroup/garage | trainer.py | Trainer.restore | restore | Restore experiment from snapshot. | [
"Restore",
"experiment",
"from",
"snapshot."
] | def restore(self, from_dir, from_epoch='last'):
saved = self._snapshotter.load(from_dir, from_epoch)
self._seed = saved['seed']
self._train_args = saved['train_args']
self._stats = saved['stats']
set_seed(self._seed)
self.setup(env=saved['env'], algo=saved['algo'])
n_epochs = self._train_arg... | ['def', 'restore(self,', 'from_dir,', "from_epoch='last'):", 'saved', '=', 'self._snapshotter.load(from_dir,', 'from_epoch)', 'self._seed', '=', "saved['seed']", 'self._train_args', '=', "saved['train_args']", 'self._stats', '=', "saved['stats']", 'set_seed(self._seed)', "self.setup(env=saved['env'],", "algo=saved['alg... | 200,120 |
tobegit3hub/deep_image_model | sparse_feature_cross_op_test.py | SparseCrossOpTest.test_hashed_output_v2 | test_hashed_output_v2 | Tests a simple scenario. | [
"Tests",
"a",
"simple",
"scenario."
] | def test_hashed_output_v2(self):
op = tf.contrib.layers.sparse_feature_cross([self._sparse_tensor([['batch1-FC1-F1']]), self._sparse_tensor([['batch1-FC2-F1']]), self._sparse_tensor([['batch1-FC3-F1']])], hashed_output=True, num_buckets=100, hash_key=tf.contrib.layers.SPARSE_FEATURE_CROSS_DEFAULT_HASH_KEY)
expe... | ['def', 'test_hashed_output_v2(self):', 'op', '=', "tf.contrib.layers.sparse_feature_cross([self._sparse_tensor([['batch1-FC1-F1']]),", "self._sparse_tensor([['batch1-FC2-F1']]),", "self._sparse_tensor([['batch1-FC3-F1']])],", 'hashed_output=True,', 'num_buckets=100,', 'hash_key=tf.contrib.layers.SPARSE_FEATURE_CROSS_D... | 181,434 |
TonghanWang/ROMA | starcraft2.py | StarCraft2Env.can_move | can_move | Whether a unit can move in a given direction. | [
"Whether",
"a",
"unit",
"can",
"move",
"in",
"a",
"given",
"direction."
] | def can_move(self, unit, direction):
m = self._move_amount / 2
if direction == Direction.NORTH:
(x, y) = (int(unit.pos.x), int(unit.pos.y + m))
elif direction == Direction.SOUTH:
(x, y) = (int(unit.pos.x), int(unit.pos.y - m))
elif direction == Direction.EAST:
(x, y) = (int(unit.... | ['def', 'can_move(self,', 'unit,', 'direction):', 'm', '=', 'self._move_amount', '/', '2', 'if', 'direction', '==', 'Direction.NORTH:', '(x,', 'y)', '=', '(int(unit.pos.x),', 'int(unit.pos.y', '+', 'm))', 'elif', 'direction', '==', 'Direction.SOUTH:', '(x,', 'y)', '=', '(int(unit.pos.x),', 'int(unit.pos.y', '-', 'm))',... | 827,229 |
alinlab/ifseg | em.py | EM.initialize_centroids | initialize_centroids | Initializes the centroids by sampling random columns from W. | [
"Initializes",
"the",
"centroids",
"by",
"sampling",
"random",
"columns",
"from",
"W."
] | def initialize_centroids(self):
(in_features, out_features) = self.W.size()
indices = torch.randint(low=0, high=out_features, size=(self.n_centroids,)).long()
self.centroids = self.W[:, indices].t() | ['def', 'initialize_centroids(self):', '(in_features,', 'out_features)', '=', 'self.W.size()', 'indices', '=', 'torch.randint(low=0,', 'high=out_features,', 'size=(self.n_centroids,)).long()', 'self.centroids', '=', 'self.W[:,', 'indices].t()'] | 598,354 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_savitzky_golay.py | test_sg_filter_trivial | test_sg_filter_trivial | Test some trivial edge cases for savgol_filter(). | [
"Test",
"some",
"trivial",
"edge",
"cases",
"for",
"savgol_filter()."
] | def test_sg_filter_trivial():
x = np.array([1.0])
y = savgol_filter(x, 1, 0)
assert_equal(y, [1.0])
x = np.array([3.0])
y = savgol_filter(x, 3, 1, mode='constant')
assert_almost_equal(y, [1.0], decimal=15)
x = np.array([3.0])
y = savgol_filter(x, 3, 1, mode='nearest')
assert_almost_e... | ['def', 'test_sg_filter_trivial():', 'x', '=', 'np.array([1.0])', 'y', '=', 'savgol_filter(x,', '1,', '0)', 'assert_equal(y,', '[1.0])', 'x', '=', 'np.array([3.0])', 'y', '=', 'savgol_filter(x,', '3,', '1,', "mode='constant')", 'assert_almost_equal(y,', '[1.0],', 'decimal=15)', 'x', '=', 'np.array([3.0])', 'y', '=', 's... | 100,076 |
AIChallenger/AI_Challenger_2018 | config_util.py | get_image_resizer_config | get_image_resizer_config | Returns the image resizer config from a model config. | [
"Returns",
"the",
"image",
"resizer",
"config",
"from",
"a",
"model",
"config."
] | def get_image_resizer_config(model_config):
meta_architecture = model_config.WhichOneof('model')
if meta_architecture == 'faster_rcnn':
return model_config.faster_rcnn.image_resizer
if meta_architecture == 'ssd':
return model_config.ssd.image_resizer
raise ValueError('Unknown model type:... | ['def', 'get_image_resizer_config(model_config):', 'meta_architecture', '=', "model_config.WhichOneof('model')", 'if', 'meta_architecture', '==', "'faster_rcnn':", 'return', 'model_config.faster_rcnn.image_resizer', 'if', 'meta_architecture', '==', "'ssd':", 'return', 'model_config.ssd.image_resizer', 'raise', "ValueEr... | 86,886 |
huaweicloud/trace_generation_rnn | file_utils.py | yield_trace_lines | yield_trace_lines | Read and yield data from the trace line-by-line: for either flavors, or durations. | [
"Read",
"and",
"yield",
"data",
"from",
"the",
"trace",
"line-by-line:",
"for",
"either",
"flavors,",
"or",
"durations."
] | def yield_trace_lines(trace_fn):
with open(trace_fn) as trace_file:
for line in trace_file:
line = line.rstrip('\n')
(timestamp, itemstr) = line.split(TRACE_DATA_SEP)
items = itemstr.split(ITEM_DATA_SEP)
yield (timestamp, items) | ['def', 'yield_trace_lines(trace_fn):', 'with', 'open(trace_fn)', 'as', 'trace_file:', 'for', 'line', 'in', 'trace_file:', 'line', '=', "line.rstrip('\\n')", '(timestamp,', 'itemstr)', '=', 'line.split(TRACE_DATA_SEP)', 'items', '=', 'itemstr.split(ITEM_DATA_SEP)', 'yield', '(timestamp,', 'items)'] | 355,977 |
floriankark/cs224n-win2223 | utils.py | normalizeRows | normalizeRows | Row normalization function Implement a function that normalizes each row of a matrix to have unit length. | [
"Row",
"normalization",
"function",
"Implement",
"a",
"function",
"that",
"normalizes",
"each",
"row",
"of",
"a",
"matrix",
"to",
"have",
"unit",
"length."
] | def normalizeRows(x):
N = x.shape[0]
x /= np.sqrt(np.sum(x ** 2, axis=1)).reshape((N, 1)) + 1e-30
return x | ['def', 'normalizeRows(x):', 'N', '=', 'x.shape[0]', 'x', '/=', 'np.sqrt(np.sum(x', '**', '2,', 'axis=1)).reshape((N,', '1))', '+', '1e-30', 'return', 'x'] | 507,718 |
rifqind/Agent-Programs-3KS1 | oinspect.py | Inspector.psource | psource | Print the source code for an object. | [
"Print",
"the",
"source",
"code",
"for",
"an",
"object."
] | def psource(self, obj, oname=''):
linecache.checkcache()
try:
src = getsource(obj, oname=oname)
except Exception:
src = None
if src is None:
self.noinfo('source', oname)
else:
page.page(self.format(src)) | ['def', 'psource(self,', 'obj,', "oname=''):", 'linecache.checkcache()', 'try:', 'src', '=', 'getsource(obj,', 'oname=oname)', 'except', 'Exception:', 'src', '=', 'None', 'if', 'src', 'is', 'None:', "self.noinfo('source',", 'oname)', 'else:', 'page.page(self.format(src))'] | 41,193 |
Ruturaj123/Flowchart-Detection | quantize_graph.py | GraphRewriter.create_nodes_map | create_nodes_map | Builds a mapping of node names to their defs from the graph. | [
"Builds",
"a",
"mapping",
"of",
"node",
"names",
"to",
"their",
"defs",
"from",
"the",
"graph."
] | def create_nodes_map(self, graph):
nodes_map = {}
for node in graph.node:
if node.name not in nodes_map.keys():
nodes_map[node.name] = node
else:
raise ValueError('Duplicate node names detected.')
return nodes_map | ['def', 'create_nodes_map(self,', 'graph):', 'nodes_map', '=', '{}', 'for', 'node', 'in', 'graph.node:', 'if', 'node.name', 'not', 'in', 'nodes_map.keys():', 'nodes_map[node.name]', '=', 'node', 'else:', 'raise', "ValueError('Duplicate", 'node', 'names', "detected.')", 'return', 'nodes_map'] | 606,791 |
omonimus1/super-computer- | xmlrunner.py | _XMLTestResult.generate_reports | generate_reports | Generates the XML reports to a given XMLTestRunner object. | [
"Generates",
"the",
"XML",
"reports",
"to",
"a",
"given",
"XMLTestRunner",
"object."
] | def generate_reports(self, test_runner):
all_results = self._get_info_by_testcase()
if type(test_runner.output) == str and (not os.path.exists(test_runner.output)):
os.makedirs(test_runner.output)
for (suite, tests) in all_results.items():
doc = XMLDocument()
testsuite = _XMLTestResu... | ['def', 'generate_reports(self,', 'test_runner):', 'all_results', '=', 'self._get_info_by_testcase()', 'if', 'type(test_runner.output)', '==', 'str', 'and', '(not', 'os.path.exists(test_runner.output)):', 'os.makedirs(test_runner.output)', 'for', '(suite,', 'tests)', 'in', 'all_results.items():', 'doc', '=', 'XMLDocume... | 913,011 |
liuzuxin/MPC_template-model_predictive_control_for__ | base_class.py | BaseRLModel.save | save | Save the current parameters to file :param save_path: (str or file-like) The save location :param cloudpickle: (bool) Use older cloudpickle format instead of zip-archives. | [
"Save",
"the",
"current",
"parameters",
"to",
"file",
":param",
"save_path:",
"(str",
"or",
"file-like)",
"The",
"save",
"location",
":param",
"cloudpickle:",
"(bool)",
"Use",
"older",
"cloudpickle",
"format",
"instead",
"of",
"zip-archives."
] | def save(self, save_path, cloudpickle=False):
raise NotImplementedError() | ['def', 'save(self,', 'save_path,', 'cloudpickle=False):', 'raise', 'NotImplementedError()'] | 656,576 |
mkusner/grammarVAE | cmodule.py | KeyData.get_entry | get_entry | Return path to the module file. | [
"Return",
"path",
"to",
"the",
"module",
"file."
] | def get_entry(self):
if not hasattr(self, 'entry'):
self.entry = module_name_from_dir(os.path.dirname(self.key_pkl))
return self.entry | ['def', 'get_entry(self):', 'if', 'not', 'hasattr(self,', "'entry'):", 'self.entry', '=', 'module_name_from_dir(os.path.dirname(self.key_pkl))', 'return', 'self.entry'] | 579,234 |
NoGameNoLife00/mybolg | compiler.py | Frame.inner | inner | Return an inner frame. | [
"Return",
"an",
"inner",
"frame."
] | def inner(self):
return Frame(self.eval_ctx, self) | ['def', 'inner(self):', 'return', 'Frame(self.eval_ctx,', 'self)'] | 289,412 |
rudranil723/mini-main | operations.py | PostGISOperations.postgis_version_tuple | postgis_version_tuple | Return the PostGIS version as a tuple (version string, major, minor, subminor). | [
"Return",
"the",
"PostGIS",
"version",
"as",
"a",
"tuple",
"(version",
"string,",
"major,",
"minor,",
"subminor)."
] | def postgis_version_tuple(self):
version = self.postgis_lib_version()
return (version,) + get_version_tuple(version) | ['def', 'postgis_version_tuple(self):', 'version', '=', 'self.postgis_lib_version()', 'return', '(version,)', '+', 'get_version_tuple(version)'] | 315,024 |
Speedwagon13/CS-3600-Introduction-to-- | test_io.py | SignalsTest.check_interrupted_write | check_interrupted_write | Check that a partial write, when it gets interrupted, properly invokes the signal handler, and bubbles up the exception raised in the latter. | [
"Check",
"that",
"a",
"partial",
"write,",
"when",
"it",
"gets",
"interrupted,",
"properly",
"invokes",
"the",
"signal",
"handler,",
"and",
"bubbles",
"up",
"the",
"exception",
"raised",
"in",
"the",
"latter."
] | def check_interrupted_write(self, item, bytes, **fdopen_kwargs):
support.gc_collect()
read_results = []
def _read():
s = os.read(r, 1)
read_results.append(s)
t = threading.Thread(target=_read)
t.daemon = True
(r, w) = os.pipe()
try:
wio = self.io.open(w, **fdopen_kwa... | ['def', 'check_interrupted_write(self,', 'item,', 'bytes,', '**fdopen_kwargs):', 'support.gc_collect()', 'read_results', '=', '[]', 'def', '_read():', 's', '=', 'os.read(r,', '1)', 'read_results.append(s)', 't', '=', 'threading.Thread(target=_read)', 't.daemon', '=', 'True', '(r,', 'w)', '=', 'os.pipe()', 'try:', 'wio'... | 219,615 |
brightmart/albert_zh | modeling_google.py | dense_layer_3d | dense_layer_3d | A dense layer with 3D kernel. | [
"A",
"dense",
"layer",
"with",
"3D",
"kernel."
] | def dense_layer_3d(input_tensor, num_attention_heads, head_size, initializer, activation, name=None):
input_shape = get_shape_list(input_tensor)
hidden_size = input_shape[2]
with tf.variable_scope(name):
w = tf.get_variable(name='kernel', shape=[hidden_size, num_attention_heads * head_size], initial... | ['def', 'dense_layer_3d(input_tensor,', 'num_attention_heads,', 'head_size,', 'initializer,', 'activation,', 'name=None):', 'input_shape', '=', 'get_shape_list(input_tensor)', 'hidden_size', '=', 'input_shape[2]', 'with', 'tf.variable_scope(name):', 'w', '=', "tf.get_variable(name='kernel',", 'shape=[hidden_size,', 'nu... | 87,505 |
isl-org/vision-for-action | pyhookv_utils.py | toggle_controls | toggle_controls | Must be called every frame(?). | [
"Must",
"be",
"called",
"every",
"frame(?)."
] | def toggle_controls(should_enable):
if should_enable:
control_func = getattr(h.Controls, 'enable_control_action')
else:
control_func = getattr(h.Controls, 'disable_control_action')
for prefix in ['look', 'move']:
for direction in ['left_right', 'up_down', 'up_only', 'down_only', 'rig... | ['def', 'toggle_controls(should_enable):', 'if', 'should_enable:', 'control_func', '=', 'getattr(h.Controls,', "'enable_control_action')", 'else:', 'control_func', '=', 'getattr(h.Controls,', "'disable_control_action')", 'for', 'prefix', 'in', "['look',", "'move']:", 'for', 'direction', 'in', "['left_right',", "'up_dow... | 955,745 |
deepmind/dm_env | catch.py | Catch.reset | reset | Returns the first `TimeStep` of a new episode. | [
"Returns",
"the",
"first",
"`TimeStep`",
"of",
"a",
"new",
"episode."
] | def reset(self) -> dm_env.TimeStep:
self._reset_next_step = False
self._ball_x = self._rng.randint(self._columns)
self._ball_y = 0
self._paddle_x = self._columns // 2
return dm_env.restart(self._observation()) | ['def', 'reset(self)', '->', 'dm_env.TimeStep:', 'self._reset_next_step', '=', 'False', 'self._ball_x', '=', 'self._rng.randint(self._columns)', 'self._ball_y', '=', '0', 'self._paddle_x', '=', 'self._columns', '//', '2', 'return', 'dm_env.restart(self._observation())'] | 166,740 |
alex-petrenko/sample-factory | shared_buffers.py | policy_device | policy_device | Inference/Learning device for the given policy. | [
"Inference/Learning",
"device",
"for",
"the",
"given",
"policy."
] | def policy_device(cfg: AttrDict, policy_id: PolicyID) -> torch.device:
if cfg.device == 'cpu':
return torch.device('cpu')
else:
return torch.device('cuda', index=gpus_for_process(policy_id, 1)[0]) | ['def', 'policy_device(cfg:', 'AttrDict,', 'policy_id:', 'PolicyID)', '->', 'torch.device:', 'if', 'cfg.device', '==', "'cpu':", 'return', "torch.device('cpu')", 'else:', 'return', "torch.device('cuda',", 'index=gpus_for_process(policy_id,', '1)[0])'] | 329,006 |
AgnostiqHQ/covalent | test_qiskit_plugin.py | test_default_return_type | test_default_return_type | Test that a QElectron with the default QNode interface returns the correct type. | [
"Test",
"that",
"a",
"QElectron",
"with",
"the",
"default",
"QNode",
"interface",
"returns",
"the",
"correct",
"type."
] | def test_default_return_type():
executor = ct.executor.QiskitExecutor(device='local_sampler', shots=1024)
dev = qml.device('default.qubit', wires=2)
@ct.qelectron(executors=executor)
@qml.qnode(device=dev)
def qelectron_circuit(param):
qml.RX(param, wires=0)
qml.Hadamard(wires=1)
... | ['def', 'test_default_return_type():', 'executor', '=', "ct.executor.QiskitExecutor(device='local_sampler',", 'shots=1024)', 'dev', '=', "qml.device('default.qubit',", 'wires=2)', '@ct.qelectron(executors=executor)', '@qml.qnode(device=dev)', 'def', 'qelectron_circuit(param):', 'qml.RX(param,', 'wires=0)', 'qml.Hadamar... | 490,097 |
neurospin/pylearn-parsimony | grad.py | NesterovFunction.alpha | alpha | Dual variable of the Nesterov function. | [
"Dual",
"variable",
"of",
"the",
"Nesterov",
"function."
] | def alpha(self, x):
alpha = [0] * len(self.A)
for i in range(len(self.A)):
alpha[i] = self.A[i].dot(x) * (1.0 / self.mu)
alpha = self.project(alpha)
return alpha | ['def', 'alpha(self,', 'x):', 'alpha', '=', '[0]', '*', 'len(self.A)', 'for', 'i', 'in', 'range(len(self.A)):', 'alpha[i]', '=', 'self.A[i].dot(x)', '*', '(1.0', '/', 'self.mu)', 'alpha', '=', 'self.project(alpha)', 'return', 'alpha'] | 820,013 |
jbwang1997/CrossKD | merge_augs.py | merge_aug_results | merge_aug_results | Merge augmented detection results, only bboxes corresponding score under flipping and multi-scale resizing can be processed now. | [
"Merge",
"augmented",
"detection",
"results,",
"only",
"bboxes",
"corresponding",
"score",
"under",
"flipping",
"and",
"multi-scale",
"resizing",
"can",
"be",
"processed",
"now."
] | def merge_aug_results(aug_batch_results, aug_batch_img_metas):
num_augs = len(aug_batch_results)
num_imgs = len(aug_batch_results[0])
batch_results = []
aug_batch_results = copy.deepcopy(aug_batch_results)
for img_id in range(num_imgs):
aug_results = []
for aug_id in range(num_augs):... | ['def', 'merge_aug_results(aug_batch_results,', 'aug_batch_img_metas):', 'num_augs', '=', 'len(aug_batch_results)', 'num_imgs', '=', 'len(aug_batch_results[0])', 'batch_results', '=', '[]', 'aug_batch_results', '=', 'copy.deepcopy(aug_batch_results)', 'for', 'img_id', 'in', 'range(num_imgs):', 'aug_results', '=', '[]',... | 491,604 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | test_ssl.py | ThreadedTests.test_socketserver | test_socketserver | Using socketserver to create and manage SSL connections. | [
"Using",
"socketserver",
"to",
"create",
"and",
"manage",
"SSL",
"connections."
] | def test_socketserver(self):
server = make_https_server(self, certfile=CERTFILE)
if support.verbose:
sys.stdout.write('\n')
with open(CERTFILE, 'rb') as f:
d1 = f.read()
d2 = ''
url = 'https://localhost:%d/%s' % (server.port, os.path.split(CERTFILE)[1])
context = ssl.create_defau... | ['def', 'test_socketserver(self):', 'server', '=', 'make_https_server(self,', 'certfile=CERTFILE)', 'if', 'support.verbose:', "sys.stdout.write('\\n')", 'with', 'open(CERTFILE,', "'rb')", 'as', 'f:', 'd1', '=', 'f.read()', 'd2', '=', "''", 'url', '=', "'https://localhost:%d/%s'", '%', '(server.port,', 'os.path.split(CE... | 376,378 |
suarez12138/AI-Reversi_IMP_TextDichotomy | test_axes.py | test_indicate_inset_inverted | test_indicate_inset_inverted | Test that the inset lines are correctly located with inverted data axes. | [
"Test",
"that",
"the",
"inset",
"lines",
"are",
"correctly",
"located",
"with",
"inverted",
"data",
"axes."
] | def test_indicate_inset_inverted(x_inverted, y_inverted):
(fig, (ax1, ax2)) = plt.subplots(1, 2)
x = np.arange(10)
ax1.plot(x, x, 'o')
if x_inverted:
ax1.invert_xaxis()
if y_inverted:
ax1.invert_yaxis()
(rect, bounds) = ax1.indicate_inset([2, 2, 5, 4], ax2)
(lower_left, upper... | ['def', 'test_indicate_inset_inverted(x_inverted,', 'y_inverted):', '(fig,', '(ax1,', 'ax2))', '=', 'plt.subplots(1,', '2)', 'x', '=', 'np.arange(10)', 'ax1.plot(x,', 'x,', "'o')", 'if', 'x_inverted:', 'ax1.invert_xaxis()', 'if', 'y_inverted:', 'ax1.invert_yaxis()', '(rect,', 'bounds)', '=', 'ax1.indicate_inset([2,', '... | 97,282 |
tensorflow/hub | saved_model_lib.py | SavedModelHandler.export | export | Exports to SavedModel directory. | [
"Exports",
"to",
"SavedModel",
"directory."
] | def export(self, path, variables_saver=None):
proto = saved_model_pb2.SavedModel()
proto.CopyFrom(self._proto)
assets_map = _make_assets_key_collection(proto, path)
self._save_all_assets(path, assets_map)
self._save_variables(path, variables_saver)
self._save_proto(path, proto) | ['def', 'export(self,', 'path,', 'variables_saver=None):', 'proto', '=', 'saved_model_pb2.SavedModel()', 'proto.CopyFrom(self._proto)', 'assets_map', '=', '_make_assets_key_collection(proto,', 'path)', 'self._save_all_assets(path,', 'assets_map)', 'self._save_variables(path,', 'variables_saver)', 'self._save_proto(path... | 571,028 |
myothida/Supervised-Machine-Learning | __init__.py | dumps | dumps | Write a Python object to a string in plist format. | [
"Write",
"a",
"Python",
"object",
"to",
"a",
"string",
"in",
"plist",
"format."
] | def dumps(value: PlistEncodable, sort_keys: bool=True, skipkeys: bool=False, use_builtin_types: Optional[bool]=None, pretty_print: bool=True) -> bytes:
fp = BytesIO()
dump(value, fp, sort_keys=sort_keys, skipkeys=skipkeys, use_builtin_types=use_builtin_types, pretty_print=pretty_print)
return fp.getvalue() | ['def', 'dumps(value:', 'PlistEncodable,', 'sort_keys:', 'bool=True,', 'skipkeys:', 'bool=False,', 'use_builtin_types:', 'Optional[bool]=None,', 'pretty_print:', 'bool=True)', '->', 'bytes:', 'fp', '=', 'BytesIO()', 'dump(value,', 'fp,', 'sort_keys=sort_keys,', 'skipkeys=skipkeys,', 'use_builtin_types=use_builtin_types... | 361,049 |
OpenMDAO/OpenMDAO-Framework | hasobjective.py | HasObjectives.get_referenced_compnames | get_referenced_compnames | Returns the names of components referenced by the objectives. | [
"Returns",
"the",
"names",
"of",
"components",
"referenced",
"by",
"the",
"objectives."
] | def get_referenced_compnames(self):
lst = []
for obj in self._objectives.values():
lst.extend(obj.get_referenced_compnames())
return lst | ['def', 'get_referenced_compnames(self):', 'lst', '=', '[]', 'for', 'obj', 'in', 'self._objectives.values():', 'lst.extend(obj.get_referenced_compnames())', 'return', 'lst'] | 275,766 |
thaines/helit | solve_weave.py | fitModel | fitModel | Given a state object generates samples. | [
"Given",
"a",
"state",
"object",
"generates",
"samples."
] | def fitModel(state, params, next):
iniGibbs(state)
next()
if params.burnIn > params.lag:
gibbs(state, params.burnIn - params.lag, params.iterT, params.iterR, next)
for i in xrange(params.samples):
gibbs(state, params.lag, params.iterT, params.iterR, next)
state.sample()
n... | ['def', 'fitModel(state,', 'params,', 'next):', 'iniGibbs(state)', 'next()', 'if', 'params.burnIn', '>', 'params.lag:', 'gibbs(state,', 'params.burnIn', '-', 'params.lag,', 'params.iterT,', 'params.iterR,', 'next)', 'for', 'i', 'in', 'xrange(params.samples):', 'gibbs(state,', 'params.lag,', 'params.iterT,', 'params.ite... | 592,431 |
zcrwind/tgg-pytorch | tsne.py | pca | pca | Runs PCA on the NxD array X in order to reduce its dimensionality to no_dims dimensions. | [
"Runs",
"PCA",
"on",
"the",
"NxD",
"array",
"X",
"in",
"order",
"to",
"reduce",
"its",
"dimensionality",
"to",
"no_dims",
"dimensions."
] | def pca(X=np.array([]), no_dims=50):
print('Preprocessing the data using PCA...')
(n, d) = X.shape
X = X - np.tile(np.mean(X, 0), (n, 1))
(l, M) = np.linalg.eig(np.dot(X.T, X))
Y = np.dot(X, M[:, 0:no_dims])
return Y | ['def', 'pca(X=np.array([]),', 'no_dims=50):', "print('Preprocessing", 'the', 'data', 'using', "PCA...')", '(n,', 'd)', '=', 'X.shape', 'X', '=', 'X', '-', 'np.tile(np.mean(X,', '0),', '(n,', '1))', '(l,', 'M)', '=', 'np.linalg.eig(np.dot(X.T,', 'X))', 'Y', '=', 'np.dot(X,', 'M[:,', '0:no_dims])', 'return', 'Y'] | 916,017 |
deepmind/meltingpot | fruit_market.py | create_avatar_object | create_avatar_object | Create an avatar object. | [
"Create",
"an",
"avatar",
"object."
] | def create_avatar_object(player_idx: int, specialty: str, max_stamina_bar_states: int) -> Dict[str, Any]:
lua_index = player_idx + 1
source_sprite_self = 'Avatar' + str(lua_index)
grappling_sprite = 'AvatarGrappling' + str(lua_index)
grappled_sprite = 'AvatarGrappled' + str(lua_index)
live_state_nam... | ['def', 'create_avatar_object(player_idx:', 'int,', 'specialty:', 'str,', 'max_stamina_bar_states:', 'int)', '->', 'Dict[str,', 'Any]:', 'lua_index', '=', 'player_idx', '+', '1', 'source_sprite_self', '=', "'Avatar'", '+', 'str(lua_index)', 'grappling_sprite', '=', "'AvatarGrappling'", '+', 'str(lua_index)', 'grappled_... | 285,371 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | loading.py | augment_and_normalize_image | augment_and_normalize_image | Applies augmentation window with random noise in location and size and return normalized cropped image. | [
"Applies",
"augmentation",
"window",
"with",
"random",
"noise",
"in",
"location",
"and",
"size",
"and",
"return",
"normalized",
"cropped",
"image."
] | def augment_and_normalize_image(image, auxiliary_image, view, best_center, random_number_generator, augmentation, max_crop_noise, max_crop_size_noise):
view_input_size = INPUT_SIZE_DICT[view]
if augmentation:
(cropped_image, cropped_auxiliary_image) = augmentations.random_augmentation_best_center(image=... | ['def', 'augment_and_normalize_image(image,', 'auxiliary_image,', 'view,', 'best_center,', 'random_number_generator,', 'augmentation,', 'max_crop_noise,', 'max_crop_size_noise):', 'view_input_size', '=', 'INPUT_SIZE_DICT[view]', 'if', 'augmentation:', '(cropped_image,', 'cropped_auxiliary_image)', '=', 'augmentations.r... | 11,717 |
intel/neural-compressor | response_generator.py | ResponseGenerator.get_status_code_for_exception | get_status_code_for_exception | Get HTTP status code for Exception. | [
"Get",
"HTTP",
"status",
"code",
"for",
"Exception."
] | def get_status_code_for_exception(exception: Exception) -> int:
if isinstance(exception, ClientErrorException):
return 400
if isinstance(exception, AccessDeniedException):
return 403
if isinstance(exception, NotFoundException):
return 404
if isinstance(exception, InternalExceptio... | ['def', 'get_status_code_for_exception(exception:', 'Exception)', '->', 'int:', 'if', 'isinstance(exception,', 'ClientErrorException):', 'return', '400', 'if', 'isinstance(exception,', 'AccessDeniedException):', 'return', '403', 'if', 'isinstance(exception,', 'NotFoundException):', 'return', '404', 'if', 'isinstance(ex... | 721,768 |
lishunyao97/Pun-GAN | train.py | init_stats | init_stats | Initialize statistics that we want to accumulate. | [
"Initialize",
"statistics",
"that",
"we",
"want",
"to",
"accumulate."
] | def init_stats():
return {'step_time': 0.0, 'loss': 0.0, 'predict_count': 0.0, 'total_count': 0.0, 'grad_norm': 0.0} | ['def', 'init_stats():', 'return', "{'step_time':", '0.0,', "'loss':", '0.0,', "'predict_count':", '0.0,', "'total_count':", '0.0,', "'grad_norm':", '0.0}'] | 818,803 |
danaugrs/huskarl | memory.py | OnPolicy.put | put | Stores transition into the appropriate buffer. | [
"Stores",
"transition",
"into",
"the",
"appropriate",
"buffer."
] | def put(self, transition, instance=0):
self.buffers[instance].append(transition) | ['def', 'put(self,', 'transition,', 'instance=0):', 'self.buffers[instance].append(transition)'] | 206,791 |
edwardlib/observations | budget_italy.py | budget_italy | budget_italy | Budget Shares for Italian Households a cross-section from 1973 to 1992 *number of observations* : 1729 *observation* : households *country* : Italy A dataframe containing : wfood food share whouse housing and fuels share wmisc miscellaneous share pfood food price phouse housing and fuels price pmisc miscellaneous price... | [
"Budget",
"Shares",
"for",
"Italian",
"Households",
"a",
"cross-section",
"from",
"1973",
"to",
"1992",
"*number",
"of",
"observations*",
":",
"1729",
"*observation*",
":",
"households",
"*country*",
":",
"Italy",
"A",
"dataframe",
"containing",
":",
"wfood",
"f... | def budget_italy(path):
import pandas as pd
path = os.path.expanduser(path)
filename = 'budget_italy.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/Ecdat/BudgetItaly.csv'
maybe_download_and_extract(path, url, save_file_name='budget_italy.csv... | ['def', 'budget_italy(path):', 'import', 'pandas', 'as', 'pd', 'path', '=', 'os.path.expanduser(path)', 'filename', '=', "'budget_italy.csv'", 'if', 'not', 'os.path.exists(os.path.join(path,', 'filename)):', 'url', '=', "'http://dustintran.com/data/r/Ecdat/BudgetItaly.csv'", 'maybe_download_and_extract(path,', 'url,', ... | 740,125 |
scikit-learn/scikit-learn | test_isomap.py | test_get_feature_names_out | test_get_feature_names_out | Check get_feature_names_out for Isomap. | [
"Check",
"get_feature_names_out",
"for",
"Isomap."
] | def test_get_feature_names_out():
(X, y) = make_blobs(random_state=0, n_features=4)
n_components = 2
iso = manifold.Isomap(n_components=n_components)
iso.fit_transform(X)
names = iso.get_feature_names_out()
assert_array_equal([f'isomap{i}' for i in range(n_components)], names) | ['def', 'test_get_feature_names_out():', '(X,', 'y)', '=', 'make_blobs(random_state=0,', 'n_features=4)', 'n_components', '=', '2', 'iso', '=', 'manifold.Isomap(n_components=n_components)', 'iso.fit_transform(X)', 'names', '=', 'iso.get_feature_names_out()', "assert_array_equal([f'isomap{i}'", 'for', 'i', 'in', 'range(... | 853,652 |
treigerm/WaterNet | model.py | compile_model | compile_model | Compile the keras model with the given hyperparameters. | [
"Compile",
"the",
"keras",
"model",
"with",
"the",
"given",
"hyperparameters."
] | def compile_model(model, learning_rate, momentum, decay):
optimizer = SGD(lr=learning_rate, momentum=momentum, decay=decay)
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
return model | ['def', 'compile_model(model,', 'learning_rate,', 'momentum,', 'decay):', 'optimizer', '=', 'SGD(lr=learning_rate,', 'momentum=momentum,', 'decay=decay)', "model.compile(loss='categorical_crossentropy',", 'optimizer=optimizer,', "metrics=['accuracy'])", 'return', 'model'] | 372,928 |
hongliangduan/Transformer-model-for-prediction-in-low-chemical-data-regimes | modality.py | Modality.bottom | bottom | Transform one shard of input. | [
"Transform",
"one",
"shard",
"of",
"input."
] | def bottom(self, x):
raise NotImplementedError('Abstract Method') | ['def', 'bottom(self,', 'x):', 'raise', "NotImplementedError('Abstract", "Method')"] | 966,155 |
divelab/AIRS | QHNet.py | prod | prod | Compute the product of a sequence. | [
"Compute",
"the",
"product",
"of",
"a",
"sequence."
] | def prod(x):
out = 1
for a in x:
out *= a
return out | ['def', 'prod(x):', 'out', '=', '1', 'for', 'a', 'in', 'x:', 'out', '*=', 'a', 'return', 'out'] | 86,507 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.