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
enuguru/artificial_intelligence_and_machine_learning
columns.py
Column.default_value
default_value
Returns the default value for this column type.
[ "Returns", "the", "default", "value", "for", "this", "column", "type." ]
def default_value(self, reverse=False): return self._default
['def', 'default_value(self,', 'reverse=False):', 'return', 'self._default']
161,943
dvlab-research/FocalsConv
focal_sparse_conv.py
FocalSparseConv.construct_multimodal_features
construct_multimodal_features
Construct the multimodal features with both lidar sparse features and image features.
[ "Construct", "the", "multimodal", "features", "with", "both", "lidar", "sparse", "features", "and", "image", "features." ]
def construct_multimodal_features(self, x, x_rgb, batch_dict, fuse_sum=False): batch_index = x.indices[:, 0] spatial_indices = x.indices[:, 1:] * self.voxel_stride voxels_3d = spatial_indices * self.voxel_size + self.point_cloud_range[:3] calibs = batch_dict['calib'] batch_size = batch_dict['batch_s...
['def', 'construct_multimodal_features(self,', 'x,', 'x_rgb,', 'batch_dict,', 'fuse_sum=False):', 'batch_index', '=', 'x.indices[:,', '0]', 'spatial_indices', '=', 'x.indices[:,', '1:]', '*', 'self.voxel_stride', 'voxels_3d', '=', 'spatial_indices', '*', 'self.voxel_size', '+', 'self.point_cloud_range[:3]', 'calibs', '...
608,271
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
template.py
Base.className
className
Returns the name of the class of this item.
[ "Returns", "the", "name", "of", "the", "class", "of", "this", "item." ]
def className(self): return self.__class__.__name__
['def', 'className(self):', 'return', 'self.__class__.__name__']
10,860
Picsart-AI-Research/SeMask-Segmentation
class_names.py
cityscapes_palette
cityscapes_palette
Cityscapes palette for external use.
[ "Cityscapes", "palette", "for", "external", "use." ]
def cityscapes_palette(): return [[128, 64, 128], [244, 35, 232], [70, 70, 70], [102, 102, 156], [190, 153, 153], [153, 153, 153], [250, 170, 30], [220, 220, 0], [107, 142, 35], [152, 251, 152], [70, 130, 180], [220, 20, 60], [255, 0, 0], [0, 0, 142], [0, 0, 70], [0, 60, 100], [0, 80, 100], [0, 0, 230], [119, 11, 3...
['def', 'cityscapes_palette():', 'return', '[[128,', '64,', '128],', '[244,', '35,', '232],', '[70,', '70,', '70],', '[102,', '102,', '156],', '[190,', '153,', '153],', '[153,', '153,', '153],', '[250,', '170,', '30],', '[220,', '220,', '0],', '[107,', '142,', '35],', '[152,', '251,', '152],', '[70,', '130,', '180],', ...
874,218
rudranil723/mini-main
client.py
RequestFactory.request
request
Construct a generic request object.
[ "Construct", "a", "generic", "request", "object." ]
def request(self, **request): return WSGIRequest(self._base_environ(**request))
['def', 'request(self,', '**request):', 'return', 'WSGIRequest(self._base_environ(**request))']
316,525
caiiiac/Machine-Learning-with-Python
test_rank.py
TestTieCorrect.test_basic
test_basic
Check a few basic examples of the tie correction factor.
[ "Check", "a", "few", "basic", "examples", "of", "the", "tie", "correction", "factor." ]
def test_basic(self): ranks = np.array([1.0, 2.5, 2.5]) c = tiecorrect(ranks) T = 2.0 N = ranks.size expected = 1.0 - (T ** 3 - T) / (N ** 3 - N) assert_equal(c, expected) ranks = np.array([1.5, 1.5, 3.0]) c = tiecorrect(ranks) T = 2.0 N = ranks.size expected = 1.0 - (T ** 3 ...
['def', 'test_basic(self):', 'ranks', '=', 'np.array([1.0,', '2.5,', '2.5])', 'c', '=', 'tiecorrect(ranks)', 'T', '=', '2.0', 'N', '=', 'ranks.size', 'expected', '=', '1.0', '-', '(T', '**', '3', '-', 'T)', '/', '(N', '**', '3', '-', 'N)', 'assert_equal(c,', 'expected)', 'ranks', '=', 'np.array([1.5,', '1.5,', '3.0])',...
720,105
enuguru/artificial_intelligence_and_machine_learning
sorting.py
Facets.add_field
add_field
Adds a :class:`FieldFacet` for the given field name (the field name is automatically used as the facet name).
[ "Adds", "a", ":class:`FieldFacet`", "for", "the", "given", "field", "name", "(the", "field", "name", "is", "automatically", "used", "as", "the", "facet", "name)." ]
def add_field(self, fieldname, **kwargs): self.facets[fieldname] = FieldFacet(fieldname, **kwargs) return self
['def', 'add_field(self,', 'fieldname,', '**kwargs):', 'self.facets[fieldname]', '=', 'FieldFacet(fieldname,', '**kwargs)', 'return', 'self']
162,288
AbhinandanVellanki/Pacman-Artificial-
utils.py
rounder
rounder
Round a single number, or sequence of numbers, to d decimal places.
[ "Round", "a", "single", "number,", "or", "sequence", "of", "numbers,", "to", "d", "decimal", "places." ]
def rounder(numbers, d=4): if isinstance(numbers, (int, float)): return round(numbers, d) else: constructor = type(numbers) return constructor((rounder(n, d) for n in numbers))
['def', 'rounder(numbers,', 'd=4):', 'if', 'isinstance(numbers,', '(int,', 'float)):', 'return', 'round(numbers,', 'd)', 'else:', 'constructor', '=', 'type(numbers)', 'return', 'constructor((rounder(n,', 'd)', 'for', 'n', 'in', 'numbers))']
254,527
udacity/artificial-intelligence
_inspect.py
strseq
strseq
Recursively walk a sequence, stringifying each element.
[ "Recursively", "walk", "a", "sequence,", "stringifying", "each", "element." ]
def strseq(object, convert, join=joinseq): if type(object) in [list, tuple]: return join([strseq(_o, convert, join) for _o in object]) else: return convert(object)
['def', 'strseq(object,', 'convert,', 'join=joinseq):', 'if', 'type(object)', 'in', '[list,', 'tuple]:', 'return', 'join([strseq(_o,', 'convert,', 'join)', 'for', '_o', 'in', 'object])', 'else:', 'return', 'convert(object)']
59,260
victorchen96/ReNode
sparsegraph.py
SparseGraph.to_undirected
to_undirected
Convert to an undirected graph (make adjacency matrix symmetric).
[ "Convert", "to", "an", "undirected", "graph", "(make", "adjacency", "matrix", "symmetric)." ]
def to_undirected(self) -> 'SparseGraph': idx = self.get_edgeid_to_idx_array().T ridx = np.ravel_multi_index(idx, self.adj_matrix.shape) ridx_rev = np.ravel_multi_index(idx[::-1], self.adj_matrix.shape) dup_ridx = ridx[np.isin(ridx, ridx_rev)] dup_idx = np.unravel_index(dup_ridx, self.adj_matrix.sha...
['def', 'to_undirected(self)', '->', "'SparseGraph':", 'idx', '=', 'self.get_edgeid_to_idx_array().T', 'ridx', '=', 'np.ravel_multi_index(idx,', 'self.adj_matrix.shape)', 'ridx_rev', '=', 'np.ravel_multi_index(idx[::-1],', 'self.adj_matrix.shape)', 'dup_ridx', '=', 'ridx[np.isin(ridx,', 'ridx_rev)]', 'dup_idx', '=', 'n...
346,068
voxel51/fiftyone
synchronization_tests.py
SingleProcessSynchronizationTests.test_dataset_delete_samples
test_dataset_delete_samples
Tests that when a sample is deleted from a dataset, the sample is disconnected from the dataset.
[ "Tests", "that", "when", "a", "sample", "is", "deleted", "from", "a", "dataset,", "the", "sample", "is", "disconnected", "from", "the", "dataset." ]
def test_dataset_delete_samples(self): dataset = fo.Dataset() sample = fo.Sample(filepath='test1.png') dataset.add_sample(sample) self.assertTrue(sample.in_dataset) self.assertIsNotNone(sample.id) self.assertIs(sample.dataset, dataset) dataset.delete_samples(sample) self.assertFalse(samp...
['def', 'test_dataset_delete_samples(self):', 'dataset', '=', 'fo.Dataset()', 'sample', '=', "fo.Sample(filepath='test1.png')", 'dataset.add_sample(sample)', 'self.assertTrue(sample.in_dataset)', 'self.assertIsNotNone(sample.id)', 'self.assertIs(sample.dataset,', 'dataset)', 'dataset.delete_samples(sample)', 'self.asse...
584,422
enlite-ai/maze
trajectory_record.py
SpacesTrajectoryRecord.is_done
is_done
Convenience method for checking whether the end of this trajectory represents also the end of an episode.
[ "Convenience", "method", "for", "checking", "whether", "the", "end", "of", "this", "trajectory", "represents", "also", "the", "end", "of", "an", "episode." ]
def is_done(self) -> bool: if len(self) == 0: return False assert not self.step_records[-1].is_batched(), 'cannot determine done state for batched trajectory.' return self.step_records[-1].is_done()
['def', 'is_done(self)', '->', 'bool:', 'if', 'len(self)', '==', '0:', 'return', 'False', 'assert', 'not', 'self.step_records[-1].is_batched(),', "'cannot", 'determine', 'done', 'state', 'for', 'batched', "trajectory.'", 'return', 'self.step_records[-1].is_done()']
646,812
tencent-ailab/TriNet
hubert.py
HubertModel.upgrade_state_dict_named
upgrade_state_dict_named
Upgrade a (possibly old) state dict for new versions of fairseq.
[ "Upgrade", "a", "(possibly", "old)", "state", "dict", "for", "new", "versions", "of", "fairseq." ]
def upgrade_state_dict_named(self, state_dict, name): super().upgrade_state_dict_named(state_dict, name) return state_dict
['def', 'upgrade_state_dict_named(self,', 'state_dict,', 'name):', 'super().upgrade_state_dict_named(state_dict,', 'name)', 'return', 'state_dict']
425,391
instadeepai/jumanji
utils.py
add_edge
add_edge
Add the provided edge to the graph.
[ "Add", "the", "provided", "edge", "to", "the", "graph." ]
def add_edge(graph: Graph, edge: chex.Array) -> Tuple[Graph, bool]: def _add_edge(edge: chex.Array, edge_arr: chex.Array, edge_code: jnp.float32, graph: Graph) -> Tuple[Graph, bool]: edges = graph.edges.at[graph.edge_index, :].set(edge_arr) edge_codes = graph.edge_codes.at[graph.edge_index].set(edg...
['def', 'add_edge(graph:', 'Graph,', 'edge:', 'chex.Array)', '->', 'Tuple[Graph,', 'bool]:', 'def', '_add_edge(edge:', 'chex.Array,', 'edge_arr:', 'chex.Array,', 'edge_code:', 'jnp.float32,', 'graph:', 'Graph)', '->', 'Tuple[Graph,', 'bool]:', 'edges', '=', 'graph.edges.at[graph.edge_index,', ':].set(edge_arr)', 'edge_...
594,413
soumenca/ComputerVision
homography.py
make_homog
make_homog
Convert a set of points (dim*n array) to homogeneous coordinates.
[ "Convert", "a", "set", "of", "points", "(dim*n", "array)", "to", "homogeneous", "coordinates." ]
def make_homog(points): return vstack((points, ones((1, points.shape[1]))))
['def', 'make_homog(points):', 'return', 'vstack((points,', 'ones((1,', 'points.shape[1]))))']
471,296
arshpreetsingh/quantopian-machinelearning
data.py
YamlLexer.parse_block_scalar_indent
parse_block_scalar_indent
Process indentation spaces in a block scalar.
[ "Process", "indentation", "spaces", "in", "a", "block", "scalar." ]
def parse_block_scalar_indent(token_class): def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() context.stack.pop() return ...
['def', 'parse_block_scalar_indent(token_class):', 'def', 'callback(lexer,', 'match,', 'context):', 'text', '=', 'match.group()', 'if', 'context.block_scalar_indent', 'is', 'None:', 'if', 'len(text)', '<=', 'max(context.indent,', '0):', 'context.stack.pop()', 'context.stack.pop()', 'return', 'context.block_scalar_inden...
892,669
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
train_model.py
create_estimator_and_specs
create_estimator_and_specs
Creates an Experiment configuration based on the estimator and input fn.
[ "Creates", "an", "Experiment", "configuration", "based", "on", "the", "estimator", "and", "input", "fn." ]
def create_estimator_and_specs(run_config): model_params = tf.contrib.training.HParams(num_layers=FLAGS.num_layers, num_nodes=FLAGS.num_nodes, batch_size=FLAGS.batch_size, num_conv=ast.literal_eval(FLAGS.num_conv), conv_len=ast.literal_eval(FLAGS.conv_len), num_classes=get_num_classes(), learning_rate=FLAGS.learnin...
['def', 'create_estimator_and_specs(run_config):', 'model_params', '=', 'tf.contrib.training.HParams(num_layers=FLAGS.num_layers,', 'num_nodes=FLAGS.num_nodes,', 'batch_size=FLAGS.batch_size,', 'num_conv=ast.literal_eval(FLAGS.num_conv),', 'conv_len=ast.literal_eval(FLAGS.conv_len),', 'num_classes=get_num_classes(),', ...
113,312
TengXiaoDai/DistributedCrawling
_bootstrap_external.py
ExtensionFileLoader.get_filename
get_filename
Return the path to the source file as found by the finder.
[ "Return", "the", "path", "to", "the", "source", "file", "as", "found", "by", "the", "finder." ]
def get_filename(self, fullname): return self.path
['def', 'get_filename(self,', 'fullname):', 'return', 'self.path']
188,232
google-research/batch-ppo
batch_env.py
BatchEnv.step
step
Forward a batch of actions to the wrapped environments.
[ "Forward", "a", "batch", "of", "actions", "to", "the", "wrapped", "environments." ]
def step(self, actions): for (index, (env, action)) in enumerate(zip(self._envs, actions)): if not env.action_space.contains(action): message = 'Invalid action at index {}: {}' raise ValueError(message.format(index, action)) if self._blocking: transitions = [env.step(acti...
['def', 'step(self,', 'actions):', 'for', '(index,', '(env,', 'action))', 'in', 'enumerate(zip(self._envs,', 'actions)):', 'if', 'not', 'env.action_space.contains(action):', 'message', '=', "'Invalid", 'action', 'at', 'index', '{}:', "{}'", 'raise', 'ValueError(message.format(index,', 'action))', 'if', 'self._blocking:...
94,956
zihuitang/medical_AI_platform
__init__.py
Menu.invoke
invoke
Invoke a menu item identified by INDEX and execute the associated command.
[ "Invoke", "a", "menu", "item", "identified", "by", "INDEX", "and", "execute", "the", "associated", "command." ]
def invoke(self, index): return self.tk.call(self._w, 'invoke', index)
['def', 'invoke(self,', 'index):', 'return', 'self.tk.call(self._w,', "'invoke',", 'index)']
284,300
gunthercox/ChatterBot
collections.py
CollectionAdapter.link_to_self
link_to_self
Link a collection to this adapter, and fire a link event.
[ "Link", "a", "collection", "to", "this", "adapter,", "and", "fire", "a", "link", "event." ]
def link_to_self(self, data): setattr(data, '_sa_adapter', self) if hasattr(data, '_sa_on_link'): getattr(data, '_sa_on_link')(self)
['def', 'link_to_self(self,', 'data):', 'setattr(data,', "'_sa_adapter',", 'self)', 'if', 'hasattr(data,', "'_sa_on_link'):", 'getattr(data,', "'_sa_on_link')(self)"]
534,476
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
streams.py
TokenStream.getTokenSource
getTokenSource
Where is this stream pulling tokens from? This is not the name, but the object that provides Token objects.
[ "Where", "is", "this", "stream", "pulling", "tokens", "from?", "This", "is", "not", "the", "name,", "but", "the", "object", "that", "provides", "Token", "objects." ]
def getTokenSource(self): raise NotImplementedError
['def', 'getTokenSource(self):', 'raise', 'NotImplementedError']
9,962
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
logic.py
PropKB.ask_if_true
ask_if_true
Return True if the KB entails query, else return False.
[ "Return", "True", "if", "the", "KB", "entails", "query,", "else", "return", "False." ]
def ask_if_true(self, query): for _ in self.ask_generator(query): return True return False
['def', 'ask_if_true(self,', 'query):', 'for', '_', 'in', 'self.ask_generator(query):', 'return', 'True', 'return', 'False']
428,078
jxhe/unify-parameter-efficient-tuning
convert_marian_to_pytorch.py
find_pretrained_model
find_pretrained_model
Find models that can accept src_lang as input and return tgt_lang as output.
[ "Find", "models", "that", "can", "accept", "src_lang", "as", "input", "and", "return", "tgt_lang", "as", "output." ]
def find_pretrained_model(src_lang: str, tgt_lang: str) -> List[str]: prefix = 'Helsinki-NLP/opus-mt-' api = HfApi() model_list = api.model_list() model_ids = [x.modelId for x in model_list if x.modelId.startswith('Helsinki-NLP')] src_and_targ = [remove_prefix(m, prefix).lower().split('-') for m in ...
['def', 'find_pretrained_model(src_lang:', 'str,', 'tgt_lang:', 'str)', '->', 'List[str]:', 'prefix', '=', "'Helsinki-NLP/opus-mt-'", 'api', '=', 'HfApi()', 'model_list', '=', 'api.model_list()', 'model_ids', '=', '[x.modelId', 'for', 'x', 'in', 'model_list', 'if', "x.modelId.startswith('Helsinki-NLP')]", 'src_and_targ...
949,007
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
real_nvp_multiscale_dataset.py
conv_ch_aff_coupling
conv_ch_aff_coupling
Affine coupling with channel-wise splitting.
[ "Affine", "coupling", "with", "channel-wise", "splitting." ]
def conv_ch_aff_coupling(input_, dim, name, use_batch_norm=True, train=True, weight_norm=True, reverse=False, residual_blocks=5, bottleneck=False, change_bottom=True, skip=True): with tf.variable_scope(name) as scope: if reverse or not train: scope.reuse_variables() if change_bottom: ...
['def', 'conv_ch_aff_coupling(input_,', 'dim,', 'name,', 'use_batch_norm=True,', 'train=True,', 'weight_norm=True,', 'reverse=False,', 'residual_blocks=5,', 'bottleneck=False,', 'change_bottom=True,', 'skip=True):', 'with', 'tf.variable_scope(name)', 'as', 'scope:', 'if', 'reverse', 'or', 'not', 'train:', 'scope.reuse_...
109,403
neuroailab/unsup_vvs
data_util.py
preprocess_for_train
preprocess_for_train
Preprocesses the given image for training.
[ "Preprocesses", "the", "given", "image", "for", "training." ]
def preprocess_for_train(image, height, width, color_distort=True, crop=True, flip=True): if crop: image = random_crop_with_resize(image, height, width) if flip: image = tf.image.random_flip_left_right(image) if color_distort: image = random_color_jitter(image) image = tf.reshape...
['def', 'preprocess_for_train(image,', 'height,', 'width,', 'color_distort=True,', 'crop=True,', 'flip=True):', 'if', 'crop:', 'image', '=', 'random_crop_with_resize(image,', 'height,', 'width)', 'if', 'flip:', 'image', '=', 'tf.image.random_flip_left_right(image)', 'if', 'color_distort:', 'image', '=', 'random_color_j...
438,448
lektor/lektor-archive
pagination.py
Pagination.prev_num
prev_num
Number of the previous page.
[ "Number", "of", "the", "previous", "page." ]
def prev_num(self): return self.page - 1
['def', 'prev_num(self):', 'return', 'self.page', '-', '1']
216,485
intel/neural-compressor
weight_only.py
apply_awq_clip
apply_awq_clip
Apply clip for weight by checking mse.
[ "Apply", "clip", "for", "weight", "by", "checking", "mse." ]
def apply_awq_clip(model, weight_config, absorb_pairs, output_dicts, num_bits, group_size, scheme): ratios = {} for (parent, nodes) in absorb_pairs.items(): if any([node.input[0] not in output_dicts for node in nodes]): logger.warning('Miss input tensors of nodes {} during AWQ, skip it!'.for...
['def', 'apply_awq_clip(model,', 'weight_config,', 'absorb_pairs,', 'output_dicts,', 'num_bits,', 'group_size,', 'scheme):', 'ratios', '=', '{}', 'for', '(parent,', 'nodes)', 'in', 'absorb_pairs.items():', 'if', 'any([node.input[0]', 'not', 'in', 'output_dicts', 'for', 'node', 'in', 'nodes]):', "logger.warning('Miss", ...
737,499
louisthai/cpsc5910-su20
ipythonblocks.py
BlockGrid.show
show
Display colored grid as an HTML table.
[ "Display", "colored", "grid", "as", "an", "HTML", "table." ]
def show(self): display(HTML(self._repr_html_()))
['def', 'show(self):', 'display(HTML(self._repr_html_()))']
138,123
renfredxh/compilebot
reply.py
TestProcessUnread.test_recompile_edit
test_recompile_edit
Ensure that if there is an existing reply from a bot on a comment that is being recompiled, the existing reply is editing instead of making a new comment.
[ "Ensure", "that", "if", "there", "is", "an", "existing", "reply", "from", "a", "bot", "on", "a", "comment", "that", "is", "being", "recompiled,", "the", "existing", "reply", "is", "editing", "instead", "of", "making", "a", "new", "comment." ]
def test_recompile_edit(self): body = '+/u/{user} python 3\n\n print("test")\n\n\n\n'.format(user=self.user) existing_reply = self.Comment(author=self.Author(self.user)) replies = [self.Comment(author=self.Author('OneCommenter')), existing_reply, self.Comment(author=self.Author('AnotherCommenter'))] ...
['def', 'test_recompile_edit(self):', 'body', '=', "'+/u/{user}", 'python', '3\\n\\n', 'print("test")\\n\\n\\n\\n\'.format(user=self.user)', 'existing_reply', '=', 'self.Comment(author=self.Author(self.user))', 'replies', '=', "[self.Comment(author=self.Author('OneCommenter')),", 'existing_reply,', "self.Comment(author...
125,321
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
check.py
Ne
Ne
Raises an error if |lhs| equals |rhs|.
[ "Raises", "an", "error", "if", "|lhs|", "equals", "|rhs|." ]
def Ne(lhs, rhs, message='', error=ValueError): if lhs == rhs: raise error('Expected (%s) != (%s): %s' % (lhs, rhs, message))
['def', 'Ne(lhs,', 'rhs,', "message='',", 'error=ValueError):', 'if', 'lhs', '==', 'rhs:', 'raise', "error('Expected", '(%s)', '!=', '(%s):', "%s'", '%', '(lhs,', 'rhs,', 'message))']
111,795
kubeflow/pipelines
test_visualization.py
test_confusion_matrix_invalid_types
test_confusion_matrix_invalid_types
Test for invalid type keys for confusion matrix.
[ "Test", "for", "invalid", "type", "keys", "for", "confusion", "matrix." ]
def test_confusion_matrix_invalid_types(viz_params, confusion_matrix_params, cm_key): confusion_matrix_params[cm_key] = {'test': 'dummy'} viz_params['confusion_matrix_dict'] = confusion_matrix_params with pytest.raises(TypeError): generate_visualization(viz_params)
['def', 'test_confusion_matrix_invalid_types(viz_params,', 'confusion_matrix_params,', 'cm_key):', 'confusion_matrix_params[cm_key]', '=', "{'test':", "'dummy'}", "viz_params['confusion_matrix_dict']", '=', 'confusion_matrix_params', 'with', 'pytest.raises(TypeError):', 'generate_visualization(viz_params)']
779,687
Kvatsx/Artificial-Intelligence-Assignments
Traditional.py
REParser.parse_alt
parse_alt
Parse a set of alternative regexps.
[ "Parse", "a", "set", "of", "alternative", "regexps." ]
def parse_alt(self): re = self.parse_seq() if self.c == '|': re_list = [re] while self.c == '|': self.next() re_list.append(self.parse_seq()) re = Alt(*re_list) return re
['def', 'parse_alt(self):', 're', '=', 'self.parse_seq()', 'if', 'self.c', '==', "'|':", 're_list', '=', '[re]', 'while', 'self.c', '==', "'|':", 'self.next()', 're_list.append(self.parse_seq())', 're', '=', 'Alt(*re_list)', 'return', 're']
36,534
farazBhatti/Human-Body-Measurements-using--
common.py
float_feature
float_feature
Wrapper for inserting float features into Example proto.
[ "Wrapper", "for", "inserting", "float", "features", "into", "Example", "proto." ]
def float_feature(value): if not isinstance(value, list) and (not isinstance(value, np.ndarray)): value = [value] return tf.train.Feature(float_list=tf.train.FloatList(value=value))
['def', 'float_feature(value):', 'if', 'not', 'isinstance(value,', 'list)', 'and', '(not', 'isinstance(value,', 'np.ndarray)):', 'value', '=', '[value]', 'return', 'tf.train.Feature(float_list=tf.train.FloatList(value=value))']
571,094
googleapis/python-aiplatform
client.py
FeatureOnlineStoreServiceClient.list_operations
list_operations
Lists operations that match the specified filter in the request.
[ "Lists", "operations", "that", "match", "the", "specified", "filter", "in", "the", "request." ]
def list_operations(self, request: Optional[operations_pb2.ListOperationsRequest]=None, *, retry: OptionalRetry=gapic_v1.method.DEFAULT, timeout: Union[float, object]=gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]]=()) -> operations_pb2.ListOperationsResponse: if isinstance(request, dict): requ...
['def', 'list_operations(self,', 'request:', 'Optional[operations_pb2.ListOperationsRequest]=None,', '*,', 'retry:', 'OptionalRetry=gapic_v1.method.DEFAULT,', 'timeout:', 'Union[float,', 'object]=gapic_v1.method.DEFAULT,', 'metadata:', 'Sequence[Tuple[str,', 'str]]=())', '->', 'operations_pb2.ListOperationsResponse:', ...
812,735
Farama-Foundation/Gymnasium
jax_to_torch.py
JaxToTorchV0.reset
reset
Resets the environment returning PyTorch-based observation and info.
[ "Resets", "the", "environment", "returning", "PyTorch-based", "observation", "and", "info." ]
def reset(self, *, seed: int | list[int] | None=None, options: dict[str, Any] | None=None) -> tuple[ObsType, dict[str, Any]]: if options: options = torch_to_jax(options) return jax_to_torch(self.env.reset(seed=seed, options=options), self.device)
['def', 'reset(self,', '*,', 'seed:', 'int', '|', 'list[int]', '|', 'None=None,', 'options:', 'dict[str,', 'Any]', '|', 'None=None)', '->', 'tuple[ObsType,', 'dict[str,', 'Any]]:', 'if', 'options:', 'options', '=', 'torch_to_jax(options)', 'return', 'jax_to_torch(self.env.reset(seed=seed,', 'options=options),', 'self.d...
573,216
matsu0228/nlp-jp
endpoints.py
_CompatEndpointResolver.get_all_available_regions
get_all_available_regions
Retrieve every region across partitions for a service.
[ "Retrieve", "every", "region", "across", "partitions", "for", "a", "service." ]
def get_all_available_regions(self, service_name): regions = set() endpoint_prefix = self._endpoint_prefix(service_name) for partition_name in self.get_available_partitions(): if self._is_global_service(service_name, partition_name): partition = self._get_partition_data(partition_name) ...
['def', 'get_all_available_regions(self,', 'service_name):', 'regions', '=', 'set()', 'endpoint_prefix', '=', 'self._endpoint_prefix(service_name)', 'for', 'partition_name', 'in', 'self.get_available_partitions():', 'if', 'self._is_global_service(service_name,', 'partition_name):', 'partition', '=', 'self._get_partitio...
783,853
wanggrun/Kalman-Normalization
tower.py
TowerTensorHandle.get_collection
get_collection
Get items from a collection that are added in this tower.
[ "Get", "items", "from", "a", "collection", "that", "are", "added", "in", "this", "tower." ]
def get_collection(self, name): return self._ctx.get_collection_in_tower(name)
['def', 'get_collection(self,', 'name):', 'return', 'self._ctx.get_collection_in_tower(name)']
594,848
ruhyadi/yolo3d-lightning
rich_utils.py
print_config_tree
print_config_tree
Prints content of DictConfig using Rich library and its tree structure.
[ "Prints", "content", "of", "DictConfig", "using", "Rich", "library", "and", "its", "tree", "structure." ]
def print_config_tree(cfg: DictConfig, print_order: Sequence[str]=('datamodule', 'model', 'callbacks', 'logger', 'trainer', 'paths', 'extras'), resolve: bool=False, save_to_file: bool=False) -> None: style = 'dim' tree = rich.tree.Tree('CONFIG', style=style, guide_style=style) queue = [] for field in pr...
['def', 'print_config_tree(cfg:', 'DictConfig,', 'print_order:', "Sequence[str]=('datamodule',", "'model',", "'callbacks',", "'logger',", "'trainer',", "'paths',", "'extras'),", 'resolve:', 'bool=False,', 'save_to_file:', 'bool=False)', '->', 'None:', 'style', '=', "'dim'", 'tree', '=', "rich.tree.Tree('CONFIG',", 'sty...
969,206
JohannesAck/tf2multiagentrl
test_masac.py
test_save_load
test_save_load
Tests saving and loading for two agents.
[ "Tests", "saving", "and", "loading", "for", "two", "agents." ]
def test_save_load(): fp = '/tmp/unittestmaddpg' env = IdentityEnv(5, 2) agents = [MASACAgent(env.observation_space, env.action_space, idx, batch_size=32, buff_size=10000, lr=0.01, num_layer=2, num_units=32, gamma=0.9, tau=0.01, prioritized_replay=True, max_step=5000) for idx in range(2)] for (idx, agen...
['def', 'test_save_load():', 'fp', '=', "'/tmp/unittestmaddpg'", 'env', '=', 'IdentityEnv(5,', '2)', 'agents', '=', '[MASACAgent(env.observation_space,', 'env.action_space,', 'idx,', 'batch_size=32,', 'buff_size=10000,', 'lr=0.01,', 'num_layer=2,', 'num_units=32,', 'gamma=0.9,', 'tau=0.01,', 'prioritized_replay=True,',...
915,677
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
handlers.py
RotatingFileHandler.doRollover
doRollover
Do a rollover, as described in __init__().
[ "Do", "a", "rollover,", "as", "described", "in", "__init__()." ]
def doRollover(self): if self.stream: self.stream.close() self.stream = None if self.backupCount > 0: for i in range(self.backupCount - 1, 0, -1): sfn = self.rotation_filename('%s.%d' % (self.baseFilename, i)) dfn = self.rotation_filename('%s.%d' % (self.baseFilen...
['def', 'doRollover(self):', 'if', 'self.stream:', 'self.stream.close()', 'self.stream', '=', 'None', 'if', 'self.backupCount', '>', '0:', 'for', 'i', 'in', 'range(self.backupCount', '-', '1,', '0,', '-1):', 'sfn', '=', "self.rotation_filename('%s.%d'", '%', '(self.baseFilename,', 'i))', 'dfn', '=', "self.rotation_file...
431,113
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
matcher.py
Match.num_matched_columns
num_matched_columns
Returns number (int32 scalar tensor) of matched columns.
[ "Returns", "number", "(int32", "scalar", "tensor)", "of", "matched", "columns." ]
def num_matched_columns(self): return tf.size(self.matched_column_indices())
['def', 'num_matched_columns(self):', 'return', 'tf.size(self.matched_column_indices())']
57,213
Katja-M/Python_NaturalLanguageProcessing
grammar.py
CFG.max_len
max_len
Return the right-hand side length of the longest grammar production.
[ "Return", "the", "right-hand", "side", "length", "of", "the", "longest", "grammar", "production." ]
def max_len(self): return self._max_len
['def', 'max_len(self):', 'return', 'self._max_len']
865,803
Ruturaj123/Flowchart-Detection
feature_column.py
_RealValuedColumn.insert_transformed_feature
insert_transformed_feature
Apply transformation and inserts it into columns_to_tensors.
[ "Apply", "transformation", "and", "inserts", "it", "into", "columns_to_tensors." ]
def insert_transformed_feature(self, columns_to_tensors): input_tensor = self._normalized_input_tensor(columns_to_tensors[self.name]) columns_to_tensors[self] = math_ops.to_float(input_tensor)
['def', 'insert_transformed_feature(self,', 'columns_to_tensors):', 'input_tensor', '=', 'self._normalized_input_tensor(columns_to_tensors[self.name])', 'columns_to_tensors[self]', '=', 'math_ops.to_float(input_tensor)']
603,666
fptudsc/artificial-intelligence
serialize.py
Serializer.prepare_response
prepare_response
Verify our vary headers match and construct a real urllib3 HTTPResponse object.
[ "Verify", "our", "vary", "headers", "match", "and", "construct", "a", "real", "urllib3", "HTTPResponse", "object." ]
def prepare_response(self, request, cached): if '*' in cached.get('vary', {}): return for (header, value) in cached.get('vary', {}).items(): if request.headers.get(header, None) != value: return body_raw = cached['response'].pop('body') headers = CaseInsensitiveDict(data=cach...
['def', 'prepare_response(self,', 'request,', 'cached):', 'if', "'*'", 'in', "cached.get('vary',", '{}):', 'return', 'for', '(header,', 'value)', 'in', "cached.get('vary',", '{}).items():', 'if', 'request.headers.get(header,', 'None)', '!=', 'value:', 'return', 'body_raw', '=', "cached['response'].pop('body')", 'header...
90,278
rudranil723/mini-main
test_from_template.py
normalize_whitespace
normalize_whitespace
Remove leading and trailing whitespace, and convert internal stretches of whitespace to a single space.
[ "Remove", "leading", "and", "trailing", "whitespace,", "and", "convert", "internal", "stretches", "of", "whitespace", "to", "a", "single", "space." ]
def normalize_whitespace(s): return ' '.join(s.split())
['def', 'normalize_whitespace(s):', 'return', "'", "'.join(s.split())"]
322,665
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
nb_004b.py
MixedPrecision.on_loss_begin
on_loss_begin
Converts half precision output to FP32 to avoid reduction overflow.
[ "Converts", "half", "precision", "output", "to", "FP32", "to", "avoid", "reduction", "overflow." ]
def on_loss_begin(self, last_output: Tensor, **kwargs: Any) -> Tensor: return last_output.float()
['def', 'on_loss_begin(self,', 'last_output:', 'Tensor,', '**kwargs:', 'Any)', '->', 'Tensor:', 'return', 'last_output.float()']
81,291
nddbk/tf-object-detection
preprocessor_cache.py
PreprocessorCache.get
get
Gets stored value given a function id and key.
[ "Gets", "stored", "value", "given", "a", "function", "id", "and", "key." ]
def get(self, function_id, key): if function_id not in self._VALID_FNS: raise ValueError('Function id not recognized: %s.' % str(function_id)) return self._history[function_id].get(key)
['def', 'get(self,', 'function_id,', 'key):', 'if', 'function_id', 'not', 'in', 'self._VALID_FNS:', 'raise', "ValueError('Function", 'id', 'not', 'recognized:', "%s.'", '%', 'str(function_id))', 'return', 'self._history[function_id].get(key)']
914,751
grayhong/self-diagnosing-gan
scheduler.py
DRS_LRScheduler.step
step
Takes a step for updating learning rate and updates the input log_data with the current status.
[ "Takes", "a", "step", "for", "updating", "learning", "rate", "and", "updates", "the", "input", "log_data", "with", "the", "current", "status." ]
def step(self, log_data, global_step): for (idx, (opt, init_lr)) in enumerate(zip(self.optimizers, self.lrs)): if self.lr_decay == 'linear': lr = self.linear_decay(optimizer=opt, global_step=global_step, lr_value_range=(init_lr, 0.0), lr_step_range=(self.start_step, self.num_steps)) elif...
['def', 'step(self,', 'log_data,', 'global_step):', 'for', '(idx,', '(opt,', 'init_lr))', 'in', 'enumerate(zip(self.optimizers,', 'self.lrs)):', 'if', 'self.lr_decay', '==', "'linear':", 'lr', '=', 'self.linear_decay(optimizer=opt,', 'global_step=global_step,', 'lr_value_range=(init_lr,', '0.0),', 'lr_step_range=(self....
843,219
open-mmlab/mmsegmentation
remote_sense_inferencer.py
RSInferencer.from_model
from_model
Initialize a segmentor from model.
[ "Initialize", "a", "segmentor", "from", "model." ]
def from_model(cls, model: BaseModel, checkpoint_path: Optional[str]=None, batch_size: int=1, thread: int=1, device: Optional[str]='cpu'): if checkpoint_path is not None: load_checkpoint(model, checkpoint_path, map_location='cpu') model.to(device) return cls(model, batch_size, thread)
['def', 'from_model(cls,', 'model:', 'BaseModel,', 'checkpoint_path:', 'Optional[str]=None,', 'batch_size:', 'int=1,', 'thread:', 'int=1,', 'device:', "Optional[str]='cpu'):", 'if', 'checkpoint_path', 'is', 'not', 'None:', 'load_checkpoint(model,', 'checkpoint_path,', "map_location='cpu')", 'model.to(device)', 'return'...
625,294
RLE-Foundation/rllte
wrappers.py
FlatObsWrapper.reset
reset
Reset the environment and flatten the observation.
[ "Reset", "the", "environment", "and", "flatten", "the", "observation." ]
def reset(self) -> dm_env.TimeStep: time_step = self._env.reset() return time_step._replace(observation=self._flatten_obs(time_step.observation))
['def', 'reset(self)', '->', 'dm_env.TimeStep:', 'time_step', '=', 'self._env.reset()', 'return', 'time_step._replace(observation=self._flatten_obs(time_step.observation))']
333,282
jingjingli01/TGLS
configuration_utils.py
PretrainedConfig.to_dict
to_dict
Serializes this instance to a Python dictionary.
[ "Serializes", "this", "instance", "to", "a", "Python", "dictionary." ]
def to_dict(self): output = copy.deepcopy(self.__dict__) return output
['def', 'to_dict(self):', 'output', '=', 'copy.deepcopy(self.__dict__)', 'return', 'output']
367,300
jimtin/Stock_Comparison
pretty.py
RepresentationPrinter.pretty
pretty
Pretty print the given object.
[ "Pretty", "print", "the", "given", "object." ]
def pretty(self, obj): obj_id = id(obj) cycle = obj_id in self.stack self.stack.append(obj_id) self.begin_group() try: obj_class = _safe_getattr(obj, '__class__', None) or type(obj) try: printer = self.singleton_pprinters[obj_id] except (TypeError, KeyError): ...
['def', 'pretty(self,', 'obj):', 'obj_id', '=', 'id(obj)', 'cycle', '=', 'obj_id', 'in', 'self.stack', 'self.stack.append(obj_id)', 'self.begin_group()', 'try:', 'obj_class', '=', '_safe_getattr(obj,', "'__class__',", 'None)', 'or', 'type(obj)', 'try:', 'printer', '=', 'self.singleton_pprinters[obj_id]', 'except', '(Ty...
385,282
Farama-Foundation/Minigrid
utils.py
assert_equals
assert_equals
Assert equality of data structures `a` and `b`.
[ "Assert", "equality", "of", "data", "structures", "`a`", "and", "`b`." ]
def assert_equals(a, b, prefix=None): assert type(a) == type(b), f'{prefix}Differing types: {a} and {b}' if isinstance(a, dict): assert list(a.keys()) == list(b.keys()), f'{prefix}Key sets differ: {a} and {b}' for k in a.keys(): v_a = a[k] v_b = b[k] assert_eq...
['def', 'assert_equals(a,', 'b,', 'prefix=None):', 'assert', 'type(a)', '==', 'type(b),', "f'{prefix}Differing", 'types:', '{a}', 'and', "{b}'", 'if', 'isinstance(a,', 'dict):', 'assert', 'list(a.keys())', '==', 'list(b.keys()),', "f'{prefix}Key", 'sets', 'differ:', '{a}', 'and', "{b}'", 'for', 'k', 'in', 'a.keys():', ...
271,638
enuguru/artificial_intelligence_and_machine_
wrappers.py
BaseRequest.access_route
access_route
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.
[ "If", "a", "forwarded", "header", "exists", "this", "is", "a", "list", "of", "all", "ip", "addresses", "from", "the", "client", "ip", "to", "the", "last", "proxy", "server." ]
def access_route(self): if 'HTTP_X_FORWARDED_FOR' in self.environ: addr = self.environ['HTTP_X_FORWARDED_FOR'].split(',') return self.list_storage_class([x.strip() for x in addr]) elif 'REMOTE_ADDR' in self.environ: return self.list_storage_class([self.environ['REMOTE_ADDR']]) return...
['def', 'access_route(self):', 'if', "'HTTP_X_FORWARDED_FOR'", 'in', 'self.environ:', 'addr', '=', "self.environ['HTTP_X_FORWARDED_FOR'].split(',')", 'return', 'self.list_storage_class([x.strip()', 'for', 'x', 'in', 'addr])', 'elif', "'REMOTE_ADDR'", 'in', 'self.environ:', 'return', "self.list_storage_class([self.envir...
132,551
matsu0228/nlp-jp
test_word2vec.py
TestWord2VecModel.testRNG
testRNG
Test word2vec results identical with identical RNG seed.
[ "Test", "word2vec", "results", "identical", "with", "identical", "RNG", "seed." ]
def testRNG(self): model = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1) model2 = word2vec.Word2Vec(sentences, min_count=2, seed=42, workers=1) self.models_equal(model, model2)
['def', 'testRNG(self):', 'model', '=', 'word2vec.Word2Vec(sentences,', 'min_count=2,', 'seed=42,', 'workers=1)', 'model2', '=', 'word2vec.Word2Vec(sentences,', 'min_count=2,', 'seed=42,', 'workers=1)', 'self.models_equal(model,', 'model2)']
786,223
neuroailab/tnn
convrnn.py
tnn_ConvBasicCell.output_size
output_size
Integer or TensorShape: size of outputs produced by this cell.
[ "Integer", "or", "TensorShape:", "size", "of", "outputs", "produced", "by", "this", "cell." ]
def output_size(self): return self.output_tmp_shape
['def', 'output_size(self):', 'return', 'self.output_tmp_shape']
355,468
Katja-M/Python_NaturalLanguageProcessing
paice.py
demo
demo
Demonstration of the module.
[ "Demonstration", "of", "the", "module." ]
def demo(): lemmas = {'kneel': ['kneel', 'knelt'], 'range': ['range', 'ranged'], 'ring': ['ring', 'rang', 'rung']} stems = {'kneel': ['kneel'], 'knelt': ['knelt'], 'rang': ['rang', 'range', 'ranged'], 'ring': ['ring'], 'rung': ['rung']} print('Words grouped by their lemmas:') for lemma in sorted(lemmas)...
['def', 'demo():', 'lemmas', '=', "{'kneel':", "['kneel',", "'knelt'],", "'range':", "['range',", "'ranged'],", "'ring':", "['ring',", "'rang',", "'rung']}", 'stems', '=', "{'kneel':", "['kneel'],", "'knelt':", "['knelt'],", "'rang':", "['rang',", "'range',", "'ranged'],", "'ring':", "['ring'],", "'rung':", "['rung']}"...
866,591
shervinea/enzynet
keras_utils.py
Voting.predict
predict
Predicts classes of testing enzymes.
[ "Predicts", "classes", "of", "testing", "enzymes." ]
def predict(self, model: models.Sequential) -> None: self.y_pred = np.empty((len(self.list_enzymes), len(self.augmentation)), dtype=int) self.y_true = np.array([self.labels[enzyme] for enzyme in self.list_enzymes], dtype=int) self.y_id = np.array(self.list_enzymes) for (j, augmentation) in enumerate(sel...
['def', 'predict(self,', 'model:', 'models.Sequential)', '->', 'None:', 'self.y_pred', '=', 'np.empty((len(self.list_enzymes),', 'len(self.augmentation)),', 'dtype=int)', 'self.y_true', '=', 'np.array([self.labels[enzyme]', 'for', 'enzyme', 'in', 'self.list_enzymes],', 'dtype=int)', 'self.y_id', '=', 'np.array(self.lis...
178,211
yashchandak/LSTM
gnumpy.py
memory_in_use
memory_in_use
returns the number of bytes (or megabytes if you asked for that) of GPU memory that are in use.
[ "returns", "the", "number", "of", "bytes", "(or", "megabytes", "if", "you", "asked", "for", "that)", "of", "GPU", "memory", "that", "are", "in", "use." ]
def memory_in_use(in_megabytes=False): return __memoryInUse // (2 ** 20 if in_megabytes else 1)
['def', 'memory_in_use(in_megabytes=False):', 'return', '__memoryInUse', '//', '(2', '**', '20', 'if', 'in_megabytes', 'else', '1)']
217,134
k7922n/Seq2seq-Chatbot-With-Deep-Reinforcement-
seq2seq.py
rnn_decoder
rnn_decoder
RNN decoder for the sequence-to-sequence model.
[ "RNN", "decoder", "for", "the", "sequence-to-sequence", "model." ]
def rnn_decoder(decoder_inputs, initial_state, cell, loop_function=None, scope=None): with variable_scope.variable_scope(scope or 'rnn_decoder'): state = initial_state outputs = [] prev = None for (i, inp) in enumerate(decoder_inputs): if loop_function is not None and pre...
['def', 'rnn_decoder(decoder_inputs,', 'initial_state,', 'cell,', 'loop_function=None,', 'scope=None):', 'with', 'variable_scope.variable_scope(scope', 'or', "'rnn_decoder'):", 'state', '=', 'initial_state', 'outputs', '=', '[]', 'prev', '=', 'None', 'for', '(i,', 'inp)', 'in', 'enumerate(decoder_inputs):', 'if', 'loop...
876,427
quantumiracle/Benchmark-Efficient-Reinforcement--with-Demonstrations
cmd_util.py
make_vec_env
make_vec_env
Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.
[ "Create", "a", "wrapped,", "monitored", "SubprocVecEnv", "for", "Atari", "and", "MuJoCo." ]
def make_vec_env(env_id, env_type, num_env, seed, wrapper_kwargs=None, start_index=0, reward_scale=1.0): if wrapper_kwargs is None: wrapper_kwargs = {} mpi_rank = MPI.COMM_WORLD.Get_rank() if MPI else 0 def make_env(rank): def _thunk(): env = make_atari(env_id) if env_type == '...
['def', 'make_vec_env(env_id,', 'env_type,', 'num_env,', 'seed,', 'wrapper_kwargs=None,', 'start_index=0,', 'reward_scale=1.0):', 'if', 'wrapper_kwargs', 'is', 'None:', 'wrapper_kwargs', '=', '{}', 'mpi_rank', '=', 'MPI.COMM_WORLD.Get_rank()', 'if', 'MPI', 'else', '0', 'def', 'make_env(rank):', 'def', '_thunk():', 'env...
432,586
sony/nnabla-rl
test_td3.py
TestTD3.test_discrete_action_env_unsupported
test_discrete_action_env_unsupported
Check that error occurs when training on discrete action env.
[ "Check", "that", "error", "occurs", "when", "training", "on", "discrete", "action", "env." ]
def test_discrete_action_env_unsupported(self): dummy_env = E.DummyDiscrete() with pytest.raises(Exception): A.TD3(dummy_env)
['def', 'test_discrete_action_env_unsupported(self):', 'dummy_env', '=', 'E.DummyDiscrete()', 'with', 'pytest.raises(Exception):', 'A.TD3(dummy_env)']
727,459
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
thinkstats2.py
EvalExponentialCdf
EvalExponentialCdf
Evaluates CDF of the exponential distribution with parameter lam.
[ "Evaluates", "CDF", "of", "the", "exponential", "distribution", "with", "parameter", "lam." ]
def EvalExponentialCdf(x, lam): return 1 - math.exp(-lam * x)
['def', 'EvalExponentialCdf(x,', 'lam):', 'return', '1', '-', 'math.exp(-lam', '*', 'x)']
12,844
nicknochnack/RealTimeSignLanguageTFJS
data_download.py
write_file
write_file
Write all of lines from file using the writer.
[ "Write", "all", "of", "lines", "from", "file", "using", "the", "writer." ]
def write_file(writer, filename): for line in txt_line_iterator(filename): writer.write(line) writer.write('\n')
['def', 'write_file(writer,', 'filename):', 'for', 'line', 'in', 'txt_line_iterator(filename):', 'writer.write(line)', "writer.write('\\n')"]
850,569
43Carrig/recurrent_neural_networks_practice
_flagvalues.py
FlagValues.register_key_flag_for_module
register_key_flag_for_module
Specifies that a flag is a key flag for a module.
[ "Specifies", "that", "a", "flag", "is", "a", "key", "flag", "for", "a", "module." ]
def register_key_flag_for_module(self, module_name, flag): key_flags_by_module = self.key_flags_by_module_dict() key_flags = key_flags_by_module.setdefault(module_name, []) if flag not in key_flags: key_flags.append(flag)
['def', 'register_key_flag_for_module(self,', 'module_name,', 'flag):', 'key_flags_by_module', '=', 'self.key_flags_by_module_dict()', 'key_flags', '=', 'key_flags_by_module.setdefault(module_name,', '[])', 'if', 'flag', 'not', 'in', 'key_flags:', 'key_flags.append(flag)']
309,628
LLNL/Abmarl
observer.py
StackedPositionCenteredEncodingObserver.supported_agent_type
supported_agent_type
This Observer works with GridObservingAgents.
[ "This", "Observer", "works", "with", "GridObservingAgents." ]
def supported_agent_type(self): return GridObservingAgent
['def', 'supported_agent_type(self):', 'return', 'GridObservingAgent']
405,781
43Carrig/recurrent_neural_networks_practice
implementations.py
Channel.subscribe
subscribe
Subscribes to this Channel's connectivity.
[ "Subscribes", "to", "this", "Channel's", "connectivity." ]
def subscribe(self, callback, try_to_connect=None): self._channel.subscribe(callback, try_to_connect=try_to_connect)
['def', 'subscribe(self,', 'callback,', 'try_to_connect=None):', 'self._channel.subscribe(callback,', 'try_to_connect=try_to_connect)']
310,121
ashwanitanwar/nmt-transfer-learning-xlm-r
multihead_attention.py
MultiheadAttention.reorder_incremental_state
reorder_incremental_state
Reorder buffered internal state (for incremental generation).
[ "Reorder", "buffered", "internal", "state", "(for", "incremental", "generation)." ]
def reorder_incremental_state(self, incremental_state, new_order): input_buffer = self._get_input_buffer(incremental_state) if input_buffer is not None: for k in input_buffer.keys(): input_buffer[k] = input_buffer[k].index_select(0, new_order) self._set_input_buffer(incremental_state...
['def', 'reorder_incremental_state(self,', 'incremental_state,', 'new_order):', 'input_buffer', '=', 'self._get_input_buffer(incremental_state)', 'if', 'input_buffer', 'is', 'not', 'None:', 'for', 'k', 'in', 'input_buffer.keys():', 'input_buffer[k]', '=', 'input_buffer[k].index_select(0,', 'new_order)', 'self._set_inpu...
733,836
huawei-noah/xingtian
logger.py
StatsRecorder.update
update
Update with new status received.
[ "Update", "with", "new", "status", "received." ]
def update(self, **kwargs): self._data.update(**kwargs)
['def', 'update(self,', '**kwargs):', 'self._data.update(**kwargs)']
962,436
azadyasar/AI
inference.py
JointParticleFilter.observe
observe
Resample the set of particles using the likelihood of the noisy observations.
[ "Resample", "the", "set", "of", "particles", "using", "the", "likelihood", "of", "the", "noisy", "observations." ]
def observe(self, gameState): observation = gameState.getNoisyGhostDistances() self.observeUpdate(observation, gameState)
['def', 'observe(self,', 'gameState):', 'observation', '=', 'gameState.getNoisyGhostDistances()', 'self.observeUpdate(observation,', 'gameState)']
67,236
lebrice/Sequoia
measure_performance_test.py
test_last_batch_baseline_model
test_last_batch_baseline_model
BUG: Baseline method is doing something weird at the last batch, and I dont know quite why.
[ "BUG:", "Baseline", "method", "is", "doing", "something", "weird", "at", "the", "last", "batch,", "and", "I", "dont", "know", "quite", "why." ]
def test_last_batch_baseline_model(): n_samples = 110 batch_size = 20 dataset = TensorDataset(torch.arange(n_samples).reshape([n_samples, 1, 1, 1]) * torch.ones([n_samples, 3, 32, 32]), torch.zeros(n_samples, dtype=int)) pretend_to_be_active = False env = PassiveEnvironment(dataset, batch_size=batch...
['def', 'test_last_batch_baseline_model():', 'n_samples', '=', '110', 'batch_size', '=', '20', 'dataset', '=', 'TensorDataset(torch.arange(n_samples).reshape([n_samples,', '1,', '1,', '1])', '*', 'torch.ones([n_samples,', '3,', '32,', '32]),', 'torch.zeros(n_samples,', 'dtype=int))', 'pretend_to_be_active', '=', 'False...
349,700
utiasASRL/hero_radar_odometry
monitor.py
SteamMonitor.validation
validation
This function will compute loss, median errors, KITTI metrics, and draw visualizations.
[ "This", "function", "will", "compute", "loss,", "median", "errors,", "KITTI", "metrics,", "and", "draw", "visualizations." ]
def validation(self): time_used = [] valid_loss = 0 aux_losses = {} aux_init = False T_gt = [] T_pred = [] for (batchi, batch) in enumerate(self.valid_loader): ts = time() if (batchi + 1) % self.config['print_rate'] == 0: print('Eval Batch {}: {:.2}s'.format(batch...
['def', 'validation(self):', 'time_used', '=', '[]', 'valid_loss', '=', '0', 'aux_losses', '=', '{}', 'aux_init', '=', 'False', 'T_gt', '=', '[]', 'T_pred', '=', '[]', 'for', '(batchi,', 'batch)', 'in', 'enumerate(self.valid_loader):', 'ts', '=', 'time()', 'if', '(batchi', '+', '1)', '%', "self.config['print_rate']", '...
205,953
johnnyp2587/transfer-learning
pytorch_image_classification_model.py
PyTorchImageClassificationModel.predict
predict
Perform feed-forward inference and predict the classes of the input_samples.
[ "Perform", "feed-forward", "inference", "and", "predict", "the", "classes", "of", "the", "input_samples." ]
def predict(self, input_samples, return_type='class'): return_types = ['class', 'probabilities', 'scores'] if not isinstance(return_type, str) or return_type not in return_types: raise ValueError('Invalid return_type ({}). Expected one of {}.'.format(return_type, return_types)) self._model.eval() ...
['def', 'predict(self,', 'input_samples,', "return_type='class'):", 'return_types', '=', "['class',", "'probabilities',", "'scores']", 'if', 'not', 'isinstance(return_type,', 'str)', 'or', 'return_type', 'not', 'in', 'return_types:', 'raise', "ValueError('Invalid", 'return_type', '({}).', 'Expected', 'one', 'of', "{}.'...
928,314
ziberna/i3-py
wsbar.py
i3wsbar.display
display
Displays a text on the bar by piping it to the bar application.
[ "Displays", "a", "text", "on", "the", "bar", "by", "piping", "it", "to", "the", "bar", "application." ]
def display(self, bar_text): bar_text += '\n' try: bar_text = bar_text.encode() except AttributeError: pass self.bar.stdin.write(bar_text)
['def', 'display(self,', 'bar_text):', 'bar_text', '+=', "'\\n'", 'try:', 'bar_text', '=', 'bar_text.encode()', 'except', 'AttributeError:', 'pass', 'self.bar.stdin.write(bar_text)']
228,215
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
norb_input_record_test.py
NorbInputRecordTest.testImageRange
testImageRange
Checks the image to be zero meaned with std of one.
[ "Checks", "the", "image", "to", "be", "zero", "meaned", "with", "std", "of", "one." ]
def testImageRange(self): with self.test_session(graph=tf.Graph()) as sess: features = norb_input_record.inputs(data_dir=os.path.join(DATA_DIR), batch_size=1, split='train', batch_capacity=6) image_mean = tf.reduce_mean(features['images']) coord = tf.train.Coordinator() threads = tf....
['def', 'testImageRange(self):', 'with', 'self.test_session(graph=tf.Graph())', 'as', 'sess:', 'features', '=', 'norb_input_record.inputs(data_dir=os.path.join(DATA_DIR),', 'batch_size=1,', "split='train',", 'batch_capacity=6)', 'image_mean', '=', "tf.reduce_mean(features['images'])", 'coord', '=', 'tf.train.Coordinato...
53,197
thuml/Transfer-Learning-Library
feedback.py
load_feedbacks_into_dataset
load_feedbacks_into_dataset
Load precomputed object feedbacks into the dataset.
[ "Load", "precomputed", "object", "feedbacks", "into", "the", "dataset." ]
def load_feedbacks_into_dataset(dataset_dicts, proposals_list: List[Proposal]): feedbacks = {} for record in dataset_dicts: image_id = str(record['image_id']) feedbacks[image_id] = {'pred_boxes': [], 'pred_classes': []} for proposals in proposals_list: image_id = str(proposals.image_...
['def', 'load_feedbacks_into_dataset(dataset_dicts,', 'proposals_list:', 'List[Proposal]):', 'feedbacks', '=', '{}', 'for', 'record', 'in', 'dataset_dicts:', 'image_id', '=', "str(record['image_id'])", 'feedbacks[image_id]', '=', "{'pred_boxes':", '[],', "'pred_classes':", '[]}', 'for', 'proposals', 'in', 'proposals_li...
921,115
ashwin-phadke/cvplayground
autoaugment_utils.py
random_shift_bbox
random_shift_bbox
Move the bbox and the image content to a slightly new random location.
[ "Move", "the", "bbox", "and", "the", "image", "content", "to", "a", "slightly", "new", "random", "location." ]
def random_shift_bbox(image, bbox, pixel_scaling, replace, new_min_bbox_coords=None): image_height = tf.to_float(tf.shape(image)[0]) image_width = tf.to_float(tf.shape(image)[1]) def clip_y(val): return tf.clip_by_value(val, 0, tf.to_int32(image_height) - 1) def clip_x(val): return tf....
['def', 'random_shift_bbox(image,', 'bbox,', 'pixel_scaling,', 'replace,', 'new_min_bbox_coords=None):', 'image_height', '=', 'tf.to_float(tf.shape(image)[0])', 'image_width', '=', 'tf.to_float(tf.shape(image)[1])', 'def', 'clip_y(val):', 'return', 'tf.clip_by_value(val,', '0,', 'tf.to_int32(image_height)', '-', '1)', ...
510,200
ameet-1997/Natural-Language-Processing
RNN_machine_translation.py
TokenizerWrap.tokens_to_string
tokens_to_string
Convert a list of integer-tokens to a string.
[ "Convert", "a", "list", "of", "integer-tokens", "to", "a", "string." ]
def tokens_to_string(self, tokens): words = [self.index_to_word[token] for token in tokens if token != 0] text = ' '.join(words) return text
['def', 'tokens_to_string(self,', 'tokens):', 'words', '=', '[self.index_to_word[token]', 'for', 'token', 'in', 'tokens', 'if', 'token', '!=', '0]', 'text', '=', "'", "'.join(words)", 'return', 'text']
709,129
instadeepai/jumanji
utils.py
move_right
move_right
Move the board right.
[ "Move", "the", "board", "right." ]
def move_right(board: Board) -> Tuple[Board, float]: return move(board, 1)
['def', 'move_right(board:', 'Board)', '->', 'Tuple[Board,', 'float]:', 'return', 'move(board,', '1)']
594,022
ldkong1205/LaserMix
gaussian.py
gaussian_radius
gaussian_radius
Get radius of gaussian.
[ "Get", "radius", "of", "gaussian." ]
def gaussian_radius(det_size: Tuple[Tensor, Tensor], min_overlap: float=0.5) -> Tensor: (height, width) = det_size a1 = 1 b1 = height + width c1 = width * height * (1 - min_overlap) / (1 + min_overlap) sq1 = torch.sqrt(b1 ** 2 - 4 * a1 * c1) r1 = (b1 + sq1) / 2 a2 = 4 b2 = 2 * (height + ...
['def', 'gaussian_radius(det_size:', 'Tuple[Tensor,', 'Tensor],', 'min_overlap:', 'float=0.5)', '->', 'Tensor:', '(height,', 'width)', '=', 'det_size', 'a1', '=', '1', 'b1', '=', 'height', '+', 'width', 'c1', '=', 'width', '*', 'height', '*', '(1', '-', 'min_overlap)', '/', '(1', '+', 'min_overlap)', 'sq1', '=', 'torch...
624,313
facebookresearch/CompilerGym
__init__.py
LoopsDataset.preprocess
preprocess
Front a C source through the compiler frontend.
[ "Front", "a", "C", "source", "through", "the", "compiler", "frontend." ]
def preprocess(src: Path) -> bytes: cmd = [str(llvm.clang_path()), '-E', '-o', '-', '-I', str(NEURO_VECTORIZER_HEADER.parent), src] cmd += get_system_library_flags() return subprocess.check_output(cmd, timeout=300)
['def', 'preprocess(src:', 'Path)', '->', 'bytes:', 'cmd', '=', '[str(llvm.clang_path()),', "'-E',", "'-o',", "'-',", "'-I',", 'str(NEURO_VECTORIZER_HEADER.parent),', 'src]', 'cmd', '+=', 'get_system_library_flags()', 'return', 'subprocess.check_output(cmd,', 'timeout=300)']
125,818
eth-ait/motion-infilling
visualize.py
show_images
show_images
Visualize the reconstruction as images like it is done during training.
[ "Visualize", "the", "reconstruction", "as", "images", "like", "it", "is", "done", "during", "training." ]
def show_images(batch, reconstruction, l2_losses, reconstruction_c=None, l2_losses_c=None): reconstructions = [reconstruction] sub_titles = [FLAGS.descr1] losses = [l2_losses] if reconstruction_c is not None: reconstructions.append(reconstruction_c) sub_titles.append(FLAGS.descr2) ...
['def', 'show_images(batch,', 'reconstruction,', 'l2_losses,', 'reconstruction_c=None,', 'l2_losses_c=None):', 'reconstructions', '=', '[reconstruction]', 'sub_titles', '=', '[FLAGS.descr1]', 'losses', '=', '[l2_losses]', 'if', 'reconstruction_c', 'is', 'not', 'None:', 'reconstructions.append(reconstruction_c)', 'sub_t...
656,148
AiIsBetter/computer_vision
image_resizer_builder.py
build
build
Builds callable for image resizing operations.
[ "Builds", "callable", "for", "image", "resizing", "operations." ]
def build(image_resizer_config): if not isinstance(image_resizer_config, image_resizer_pb2.ImageResizer): raise ValueError('image_resizer_config not of type image_resizer_pb2.ImageResizer.') image_resizer_oneof = image_resizer_config.WhichOneof('image_resizer_oneof') if image_resizer_oneof == 'keep_...
['def', 'build(image_resizer_config):', 'if', 'not', 'isinstance(image_resizer_config,', 'image_resizer_pb2.ImageResizer):', 'raise', "ValueError('image_resizer_config", 'not', 'of', 'type', "image_resizer_pb2.ImageResizer.')", 'image_resizer_oneof', '=', "image_resizer_config.WhichOneof('image_resizer_oneof')", 'if', ...
504,073
boslbi92/dialogue-generation
optim.py
Optimizer.update
update
Update the learning rate if the criteria of the scheduler are met.
[ "Update", "the", "learning", "rate", "if", "the", "criteria", "of", "the", "scheduler", "are", "met." ]
def update(self, loss, epoch): if self.scheduler is None: pass elif isinstance(self.scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau): self.scheduler.step(loss) else: self.scheduler.step()
['def', 'update(self,', 'loss,', 'epoch):', 'if', 'self.scheduler', 'is', 'None:', 'pass', 'elif', 'isinstance(self.scheduler,', 'torch.optim.lr_scheduler.ReduceLROnPlateau):', 'self.scheduler.step(loss)', 'else:', 'self.scheduler.step()']
550,155
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials
core.py
make_index
make_index
Creates an index for fast and efficient spatial queries.
[ "Creates", "an", "index", "for", "fast", "and", "efficient", "spatial", "queries." ]
def make_index(shapes): prop = Property() prop.dimension = 2 prop.leaf_capacity = 1000 prop.fill_factor = 0.9 def bounded(): for (i, shape) in enumerate(shapes): yield (i, shape.bounds, None) return Index(bounded(), properties=prop)
['def', 'make_index(shapes):', 'prop', '=', 'Property()', 'prop.dimension', '=', '2', 'prop.leaf_capacity', '=', '1000', 'prop.fill_factor', '=', '0.9', 'def', 'bounded():', 'for', '(i,', 'shape)', 'in', 'enumerate(shapes):', 'yield', '(i,', 'shape.bounds,', 'None)', 'return', 'Index(bounded(),', 'properties=prop)']
12,105
VincentAuriau/Natural-Language-Processing
train.py
train
train
Trains a model on the given training instances as configured and returns the trained model.
[ "Trains", "a", "model", "on", "the", "given", "training", "instances", "as", "configured", "and", "returns", "the", "trained", "model." ]
def train(model: models.Model, optimizer: optimizers.Optimizer, train_instances: List[Dict[str, np.ndarray]], validation_sentences: List[List[str]], validation_trees: List[DependencyTree], parsing_system: ParsingSystem, vocabulary: Vocabulary, num_epochs: int, batch_size: int) -> Dict[str, Union[models.Model, str]]: ...
['def', 'train(model:', 'models.Model,', 'optimizer:', 'optimizers.Optimizer,', 'train_instances:', 'List[Dict[str,', 'np.ndarray]],', 'validation_sentences:', 'List[List[str]],', 'validation_trees:', 'List[DependencyTree],', 'parsing_system:', 'ParsingSystem,', 'vocabulary:', 'Vocabulary,', 'num_epochs:', 'int,', 'bat...
686,310
Ruturaj123/Flowchart-Detection
real_nvp_utils.py
unsqueeze_2x2
unsqueeze_2x2
Unsqueezing operation: reshape to convert channels into space.
[ "Unsqueezing", "operation:", "reshape", "to", "convert", "channels", "into", "space." ]
def unsqueeze_2x2(input_): if isinstance(input_, (float, int)): return input_ shape = input_.get_shape().as_list() batch_size = shape[0] height = shape[1] width = shape[2] channels = shape[3] if channels % 4 != 0: raise ValueError('Number of channels not divisible by 4.') ...
['def', 'unsqueeze_2x2(input_):', 'if', 'isinstance(input_,', '(float,', 'int)):', 'return', 'input_', 'shape', '=', 'input_.get_shape().as_list()', 'batch_size', '=', 'shape[0]', 'height', '=', 'shape[1]', 'width', '=', 'shape[2]', 'channels', '=', 'shape[3]', 'if', 'channels', '%', '4', '!=', '0:', 'raise', "ValueErr...
586,334
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects
__init__.py
Canvas.canvasx
canvasx
Return the canvas x coordinate of pixel position SCREENX rounded to nearest multiple of GRIDSPACING units.
[ "Return", "the", "canvas", "x", "coordinate", "of", "pixel", "position", "SCREENX", "rounded", "to", "nearest", "multiple", "of", "GRIDSPACING", "units." ]
def canvasx(self, screenx, gridspacing=None): return self.tk.getdouble(self.tk.call(self._w, 'canvasx', screenx, gridspacing))
['def', 'canvasx(self,', 'screenx,', 'gridspacing=None):', 'return', 'self.tk.getdouble(self.tk.call(self._w,', "'canvasx',", 'screenx,', 'gridspacing))']
376,936
rudranil723/mini-main
_base.py
_AxesBase.get_xlabel
get_xlabel
Get the xlabel text string.
[ "Get", "the", "xlabel", "text", "string." ]
def get_xlabel(self): label = self.xaxis.get_label() return label.get_text()
['def', 'get_xlabel(self):', 'label', '=', 'self.xaxis.get_label()', 'return', 'label.get_text()']
319,975
nosmokingbandit/watcher
__init__.py
ntob
ntob
Return the given native string as a byte string in the given encoding.
[ "Return", "the", "given", "native", "string", "as", "a", "byte", "string", "in", "the", "given", "encoding." ]
def ntob(n, encoding='ISO-8859-1'): return n.encode(encoding)
['def', 'ntob(n,', "encoding='ISO-8859-1'):", 'return', 'n.encode(encoding)']
381,610
DevHunterYZ/Natural-Language-Processing
batcher.py
Example.pad_decoder_inp_targ
pad_decoder_inp_targ
For rewriter, pad decoder input and target sequences with pad_id up to max_len.
[ "For", "rewriter,", "pad", "decoder", "input", "and", "target", "sequences", "with", "pad_id", "up", "to", "max_len." ]
def pad_decoder_inp_targ(self, max_len, pad_id): while len(self.dec_input) < max_len: self.dec_input.append(pad_id) while len(self.target) < max_len: self.target.append(pad_id)
['def', 'pad_decoder_inp_targ(self,', 'max_len,', 'pad_id):', 'while', 'len(self.dec_input)', '<', 'max_len:', 'self.dec_input.append(pad_id)', 'while', 'len(self.target)', '<', 'max_len:', 'self.target.append(pad_id)']
666,387
xvjiarui/VFS
ssn_head.py
parse_stage_config
parse_stage_config
Parse config of STPP for three stages.
[ "Parse", "config", "of", "STPP", "for", "three", "stages." ]
def parse_stage_config(stage_cfg): if isinstance(stage_cfg, int): return ((stage_cfg,), stage_cfg) elif isinstance(stage_cfg, tuple): return (stage_cfg, sum(stage_cfg)) else: raise ValueError(f'Incorrect STPP config {stage_cfg}')
['def', 'parse_stage_config(stage_cfg):', 'if', 'isinstance(stage_cfg,', 'int):', 'return', '((stage_cfg,),', 'stage_cfg)', 'elif', 'isinstance(stage_cfg,', 'tuple):', 'return', '(stage_cfg,', 'sum(stage_cfg))', 'else:', 'raise', "ValueError(f'Incorrect", 'STPP', 'config', "{stage_cfg}')"]
379,650
BinhPhanVan/NaturalLanguageProcessing
modeling.py
create_initializer
create_initializer
Creates a `truncated_normal_initializer` with the given range.
[ "Creates", "a", "`truncated_normal_initializer`", "with", "the", "given", "range." ]
def create_initializer(initializer_range=0.02): return tf.truncated_normal_initializer(stddev=initializer_range)
['def', 'create_initializer(initializer_range=0.02):', 'return', 'tf.truncated_normal_initializer(stddev=initializer_range)']
712,451
azadyasar/AI
inference.py
DiscreteDistribution.copy
copy
Return a copy of the distribution.
[ "Return", "a", "copy", "of", "the", "distribution." ]
def copy(self): return DiscreteDistribution(dict.copy(self))
['def', 'copy(self):', 'return', 'DiscreteDistribution(dict.copy(self))']
67,211
facebookresearch/DejaVu
train_SSL.py
ByolLoss.forward
forward
Cross-entropy between softmax outputs of the teacher and student networks.
[ "Cross-entropy", "between", "softmax", "outputs", "of", "the", "teacher", "and", "student", "networks." ]
def forward(self, student_output, teacher_output): student_out = student_output.chunk(2) teacher_out = teacher_output.detach().chunk(2) (student_out_1, student_out_2) = student_out student_out_1 = F.normalize(student_out_1, dim=-1, p=2) student_out_2 = F.normalize(student_out_2, dim=-1, p=2) (te...
['def', 'forward(self,', 'student_output,', 'teacher_output):', 'student_out', '=', 'student_output.chunk(2)', 'teacher_out', '=', 'teacher_output.detach().chunk(2)', '(student_out_1,', 'student_out_2)', '=', 'student_out', 'student_out_1', '=', 'F.normalize(student_out_1,', 'dim=-1,', 'p=2)', 'student_out_2', '=', 'F....
183,729
rudranil723/mini-main
ttGlyphPen.py
TTGlyphPointPen.addPoint
addPoint
Add a point to the current sub path.
[ "Add", "a", "point", "to", "the", "current", "sub", "path." ]
def addPoint(self, pt: Tuple[float, float], segmentType: Optional[str]=None, smooth: bool=False, name: Optional[str]=None, identifier: Optional[str]=None, **kwargs: Any) -> None: if self._isClosed(): raise PenError("Can't add a point to a closed contour.") if segmentType is None: self.types.appe...
['def', 'addPoint(self,', 'pt:', 'Tuple[float,', 'float],', 'segmentType:', 'Optional[str]=None,', 'smooth:', 'bool=False,', 'name:', 'Optional[str]=None,', 'identifier:', 'Optional[str]=None,', '**kwargs:', 'Any)', '->', 'None:', 'if', 'self._isClosed():', 'raise', 'PenError("Can\'t', 'add', 'a', 'point', 'to', 'a', '...
317,353
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials
model_rotator.py
get_metrics
get_metrics
Aggregate the metrics for rotator model.
[ "Aggregate", "the", "metrics", "for", "rotator", "model." ]
def get_metrics(inputs, outputs, params): names_to_values = dict() names_to_updates = dict() (tmp_values, tmp_updates) = metrics.add_image_pred_metrics(inputs, outputs, params.num_views, 3 * params.image_size ** 2) names_to_values.update(tmp_values) names_to_updates.update(tmp_updates) (tmp_valu...
['def', 'get_metrics(inputs,', 'outputs,', 'params):', 'names_to_values', '=', 'dict()', 'names_to_updates', '=', 'dict()', '(tmp_values,', 'tmp_updates)', '=', 'metrics.add_image_pred_metrics(inputs,', 'outputs,', 'params.num_views,', '3', '*', 'params.image_size', '**', '2)', 'names_to_values.update(tmp_values)', 'na...
109,231
ivanwilliammd/I3DR-Net-Transfer-Learning
ufrcnn.py
net.build
build
Build Mask R-CNN architecture.
[ "Build", "Mask", "R-CNN", "architecture." ]
def build(self): (h, w) = self.cf.patch_size[:2] if h / 2 ** 5 != int(h / 2 ** 5) or w / 2 ** 5 != int(w / 2 ** 5): raise Exception('Image size must be dividable by 2 at least 5 times to avoid fractions when downscaling and upscaling.For example, use 256, 320, 384, 448, 512, ... etc. ') conv = mutil...
['def', 'build(self):', '(h,', 'w)', '=', 'self.cf.patch_size[:2]', 'if', 'h', '/', '2', '**', '5', '!=', 'int(h', '/', '2', '**', '5)', 'or', 'w', '/', '2', '**', '5', '!=', 'int(w', '/', '2', '**', '5):', 'raise', "Exception('Image", 'size', 'must', 'be', 'dividable', 'by', '2', 'at', 'least', '5', 'times', 'to', 'av...
596,792
43Carrig/recurrent_neural_networks_practice
sessions.py
SessionStore.new
new
Generate a new session.
[ "Generate", "a", "new", "session." ]
def new(self): return self.session_class({}, self.generate_key(), True)
['def', 'new(self):', 'return', 'self.session_class({},', 'self.generate_key(),', 'True)']
340,286