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 |
|---|---|---|---|---|---|---|---|---|
iyah4888/SIGGRAPH18SSS | utils.py | decode_labels | decode_labels | Decode batch of segmentation masks. | [
"Decode",
"batch",
"of",
"segmentation",
"masks."
] | def decode_labels(mask, num_images=1, num_classes=21):
(n, h, w, c) = mask.shape
assert n >= num_images, 'Batch size %d should be greater or equal than number of images to save %d.' % (n, num_images)
outputs = np.zeros((num_images, h, w, 3), dtype=np.uint8)
for i in range(num_images):
img = Imag... | ['def', 'decode_labels(mask,', 'num_images=1,', 'num_classes=21):', '(n,', 'h,', 'w,', 'c)', '=', 'mask.shape', 'assert', 'n', '>=', 'num_images,', "'Batch", 'size', '%d', 'should', 'be', 'greater', 'or', 'equal', 'than', 'number', 'of', 'images', 'to', 'save', "%d.'", '%', '(n,', 'num_images)', 'outputs', '=', 'np.zer... | 934,335 |
kianak2002/Sentiment-Emotion-Analysis-project | self_outdated_check.py | was_installed_by_pip | was_installed_by_pip | Checks whether pkg was installed by pip This is used not to display the upgrade message when pip is in fact installed by system package manager, such as dnf on Fedora. | [
"Checks",
"whether",
"pkg",
"was",
"installed",
"by",
"pip",
"This",
"is",
"used",
"not",
"to",
"display",
"the",
"upgrade",
"message",
"when",
"pip",
"is",
"in",
"fact",
"installed",
"by",
"system",
"package",
"manager,",
"such",
"as",
"dnf",
"on",
"Fedor... | def was_installed_by_pip(pkg):
dist = get_default_environment().get_distribution(pkg)
return dist is not None and 'pip' == dist.installer | ['def', 'was_installed_by_pip(pkg):', 'dist', '=', 'get_default_environment().get_distribution(pkg)', 'return', 'dist', 'is', 'not', 'None', 'and', "'pip'", '==', 'dist.installer'] | 874,514 |
mj-will/nessai | test_flow_proposal.py | test_check_flow_model_reset_not_trained | test_check_flow_model_reset_not_trained | Verify that the flow model is not reset if it has never been trained. | [
"Verify",
"that",
"the",
"flow",
"model",
"is",
"not",
"reset",
"if",
"it",
"has",
"never",
"been",
"trained."
] | def test_check_flow_model_reset_not_trained(sampler):
sampler.proposal = MagicMock()
sampler.proposal.reset_model_weights = MagicMock()
sampler.proposal.training_count = 0
NestedSampler.check_flow_model_reset(sampler)
sampler.proposal.reset_model_weights.assert_not_called() | ['def', 'test_check_flow_model_reset_not_trained(sampler):', 'sampler.proposal', '=', 'MagicMock()', 'sampler.proposal.reset_model_weights', '=', 'MagicMock()', 'sampler.proposal.training_count', '=', '0', 'NestedSampler.check_flow_model_reset(sampler)', 'sampler.proposal.reset_model_weights.assert_not_called()'] | 292,970 |
asyml/texar | mono_text_data.py | MonoTextData.length_name | length_name | The name of length tensor, "length" by default. | [
"The",
"name",
"of",
"length",
"tensor,",
"\"length\"",
"by",
"default."
] | def length_name(self):
name = dsutils._connect_name(self._data_spec.name_prefix, self._data_spec.decoder.length_tensor_name)
return name | ['def', 'length_name(self):', 'name', '=', 'dsutils._connect_name(self._data_spec.name_prefix,', 'self._data_spec.decoder.length_tensor_name)', 'return', 'name'] | 924,541 |
deepmind/dm_control | renderer.py | RenderSettings.select_next_rendering_mode | select_next_rendering_mode | Cycles to the next rendering mode. | [
"Cycles",
"to",
"the",
"next",
"rendering",
"mode."
] | def select_next_rendering_mode(self):
self._visualization_options.frame = (self._visualization_options.frame + 1) % mujoco.mjtFrame.mjNFRAME | ['def', 'select_next_rendering_mode(self):', 'self._visualization_options.frame', '=', '(self._visualization_options.frame', '+', '1)', '%', 'mujoco.mjtFrame.mjNFRAME'] | 165,667 |
RasaHQ/rasa | test_pattern_utils.py | test_regex_validation | test_regex_validation | Tests if exception is raised when regex patterns are invalid. | [
"Tests",
"if",
"exception",
"is",
"raised",
"when",
"regex",
"patterns",
"are",
"invalid."
] | def test_regex_validation(lookup_tables: Dict[Text, List[Text]], regex_features: Dict[Text, Text], use_lookup_tables: bool, use_regex_features: bool):
training_data = TrainingData()
if lookup_tables:
training_data.lookup_tables = [lookup_tables]
if regex_features:
training_data.regex_feature... | ['def', 'test_regex_validation(lookup_tables:', 'Dict[Text,', 'List[Text]],', 'regex_features:', 'Dict[Text,', 'Text],', 'use_lookup_tables:', 'bool,', 'use_regex_features:', 'bool):', 'training_data', '=', 'TrainingData()', 'if', 'lookup_tables:', 'training_data.lookup_tables', '=', '[lookup_tables]', 'if', 'regex_fea... | 838,090 |
Caojunxu/AC-FPN | config.py | merge_cfg_from_cfg | merge_cfg_from_cfg | Merge `cfg_other` into the global config. | [
"Merge",
"`cfg_other`",
"into",
"the",
"global",
"config."
] | def merge_cfg_from_cfg(cfg_other):
_merge_a_into_b(cfg_other, __C) | ['def', 'merge_cfg_from_cfg(cfg_other):', '_merge_a_into_b(cfg_other,', '__C)'] | 406,353 |
apple/ml-cvnets | speech_commands_v2.py | SpeechCommandsv2Dataset.get_transformed_sample | get_transformed_sample | Get the sample at the index specified by @index. | [
"Get",
"the",
"sample",
"at",
"the",
"index",
"specified",
"by",
"@index."
] | def get_transformed_sample(self, index: int) -> Dict[str, Union[Dict[str, Tensor], Tensor, int]]:
(waveform, audio_fps, label) = self.get_sample(index)
data = {'samples': {'audio': waveform}, 'targets': label, 'sample_id': index, 'metadata': {'audio_fps': audio_fps}}
transform_fn = self.get_augmentation_tra... | ['def', 'get_transformed_sample(self,', 'index:', 'int)', '->', 'Dict[str,', 'Union[Dict[str,', 'Tensor],', 'Tensor,', 'int]]:', '(waveform,', 'audio_fps,', 'label)', '=', 'self.get_sample(index)', 'data', '=', "{'samples':", "{'audio':", 'waveform},', "'targets':", 'label,', "'sample_id':", 'index,', "'metadata':", "{... | 671,407 |
AtmaHou/MetaDialog | context_embedder_base.py | BertSeparateContextEmbedder.separate_reps | separate_reps | Separately get two sent reps. | [
"Separately",
"get",
"two",
"sent",
"reps."
] | def separate_reps(self, test_token_ids: torch.Tensor, test_segment_ids: torch.Tensor, test_nwp_index: torch.Tensor, test_input_mask: torch.Tensor, support_token_ids: torch.Tensor=None, support_segment_ids: torch.Tensor=None, support_nwp_index: torch.Tensor=None, support_input_mask: torch.Tensor=None, reps_type: str=Non... | ['def', 'separate_reps(self,', 'test_token_ids:', 'torch.Tensor,', 'test_segment_ids:', 'torch.Tensor,', 'test_nwp_index:', 'torch.Tensor,', 'test_input_mask:', 'torch.Tensor,', 'support_token_ids:', 'torch.Tensor=None,', 'support_segment_ids:', 'torch.Tensor=None,', 'support_nwp_index:', 'torch.Tensor=None,', 'support... | 633,583 |
caiiiac/Machine-Learning-with-Python | backend_qt4agg.py | new_figure_manager_given_figure | new_figure_manager_given_figure | Create a new figure manager instance for the given figure. | [
"Create",
"a",
"new",
"figure",
"manager",
"instance",
"for",
"the",
"given",
"figure."
] | def new_figure_manager_given_figure(num, figure):
canvas = FigureCanvasQTAgg(figure)
return FigureManagerQT(canvas, num) | ['def', 'new_figure_manager_given_figure(num,', 'figure):', 'canvas', '=', 'FigureCanvasQTAgg(figure)', 'return', 'FigureManagerQT(canvas,', 'num)'] | 716,481 |
RasaHQ/rasa | importer.py | E2EImporter.get_config | get_config | Retrieves model config (see parent class for full docstring). | [
"Retrieves",
"model",
"config",
"(see",
"parent",
"class",
"for",
"full",
"docstring)."
] | def get_config(self) -> Dict:
return self.importer.get_config() | ['def', 'get_config(self)', '->', 'Dict:', 'return', 'self.importer.get_config()'] | 837,645 |
tobegit3hub/deep_image_model | nn_ops.py | relu6 | relu6 | Computes Rectified Linear 6: `min(max(features, 0), 6)`. | [
"Computes",
"Rectified",
"Linear",
"6:",
"`min(max(features,",
"0),",
"6)`."
] | def relu6(features, name=None):
with ops.name_scope(name, 'Relu6', [features]) as name:
features = ops.convert_to_tensor(features, name='features')
return gen_nn_ops._relu6(features, name=name) | ['def', 'relu6(features,', 'name=None):', 'with', 'ops.name_scope(name,', "'Relu6',", '[features])', 'as', 'name:', 'features', '=', 'ops.convert_to_tensor(features,', "name='features')", 'return', 'gen_nn_ops._relu6(features,', 'name=name)'] | 183,006 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | convolutional.py | maybe_download | maybe_download | Download the data from Yann's website, unless it's already here. | [
"Download",
"the",
"data",
"from",
"Yann's",
"website,",
"unless",
"it's",
"already",
"here."
] | def maybe_download(filename):
if not tf.gfile.Exists(WORK_DIRECTORY):
tf.gfile.MakeDirs(WORK_DIRECTORY)
filepath = os.path.join(WORK_DIRECTORY, filename)
if not tf.gfile.Exists(filepath):
(filepath, _) = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
with tf.gfile.GFile(... | ['def', 'maybe_download(filename):', 'if', 'not', 'tf.gfile.Exists(WORK_DIRECTORY):', 'tf.gfile.MakeDirs(WORK_DIRECTORY)', 'filepath', '=', 'os.path.join(WORK_DIRECTORY,', 'filename)', 'if', 'not', 'tf.gfile.Exists(filepath):', '(filepath,', '_)', '=', 'urllib.request.urlretrieve(SOURCE_URL', '+', 'filename,', 'filepat... | 30,400 |
viko-3/DiffSeqMol | _internals.py | check_tensor | check_tensor | Checks if the shards_metadata is compatible with the provided tensor dims. | [
"Checks",
"if",
"the",
"shards_metadata",
"is",
"compatible",
"with",
"the",
"provided",
"tensor",
"dims."
] | def check_tensor(shards_metadata, tensor_dims) -> None:
tensor_rank = len(tensor_dims)
shards_rank = len(shards_metadata[0].shard_offsets)
if tensor_rank != shards_rank:
raise ValueError(f'Rank of tensor is {tensor_rank}, but shards rank is {shards_rank}')
total_shard_volume = 0
for shard in... | ['def', 'check_tensor(shards_metadata,', 'tensor_dims)', '->', 'None:', 'tensor_rank', '=', 'len(tensor_dims)', 'shards_rank', '=', 'len(shards_metadata[0].shard_offsets)', 'if', 'tensor_rank', '!=', 'shards_rank:', 'raise', "ValueError(f'Rank", 'of', 'tensor', 'is', '{tensor_rank},', 'but', 'shards', 'rank', 'is', "{s... | 551,585 |
mike-gimelfarb/deep-successor-features-for-transfer | agent.py | Agent.add_training_task | add_training_task | Adds a training task to be trained by the agent. | [
"Adds",
"a",
"training",
"task",
"to",
"be",
"trained",
"by",
"the",
"agent."
] | def add_training_task(self, task):
self.tasks.append(task)
self.n_tasks = len(self.tasks)
self.phis.append(task.features)
if self.n_tasks == 1:
self.n_actions = task.action_count()
self.n_features = task.feature_dim()
if self.encoding == 'task':
self.encoding = task.e... | ['def', 'add_training_task(self,', 'task):', 'self.tasks.append(task)', 'self.n_tasks', '=', 'len(self.tasks)', 'self.phis.append(task.features)', 'if', 'self.n_tasks', '==', '1:', 'self.n_actions', '=', 'task.action_count()', 'self.n_features', '=', 'task.feature_dim()', 'if', 'self.encoding', '==', "'task':", 'self.e... | 519,815 |
rifqind/Agent-Programs-3KS1 | traitlets.py | Type.validate | validate | Validates that the value is a valid object instance. | [
"Validates",
"that",
"the",
"value",
"is",
"a",
"valid",
"object",
"instance."
] | def validate(self, obj, value):
if isinstance(value, six.string_types):
try:
value = self._resolve_string(value)
except ImportError:
raise TraitError("The '%s' trait of %s instance must be a type, but %r could not be imported" % (self.name, obj, value))
try:
if is... | ['def', 'validate(self,', 'obj,', 'value):', 'if', 'isinstance(value,', 'six.string_types):', 'try:', 'value', '=', 'self._resolve_string(value)', 'except', 'ImportError:', 'raise', 'TraitError("The', "'%s'", 'trait', 'of', '%s', 'instance', 'must', 'be', 'a', 'type,', 'but', '%r', 'could', 'not', 'be', 'imported"', '%... | 21,593 |
Speech-Lab-IITM/CCC-wav2vec-2.0 | utils.py | infer_output_norm | infer_output_norm | Infer the output norm (string and module) needed on the module gvien desired output normalization. | [
"Infer",
"the",
"output",
"norm",
"(string",
"and",
"module)",
"needed",
"on",
"the",
"module",
"gvien",
"desired",
"output",
"normalization."
] | def infer_output_norm(module, output_norm=None):
if output_norm == module.output_norm():
return (None, NoOp())
if output_norm is None and module.output_norm() is not None:
logger = logging.getLogger('infer_output_norm()')
logger.warning('trying to set output_norm ({}) '.format(output_nor... | ['def', 'infer_output_norm(module,', 'output_norm=None):', 'if', 'output_norm', '==', 'module.output_norm():', 'return', '(None,', 'NoOp())', 'if', 'output_norm', 'is', 'None', 'and', 'module.output_norm()', 'is', 'not', 'None:', 'logger', '=', "logging.getLogger('infer_output_norm()')", "logger.warning('trying", 'to',... | 103,894 |
instadeepai/jumanji | viewer.py | KnapsackViewer.animate | animate | Create an animation from a sequence of environment states. | [
"Create",
"an",
"animation",
"from",
"a",
"sequence",
"of",
"environment",
"states."
] | def animate(self, states: Sequence[State], interval: int=200, save_path: Optional[str]=None) -> matplotlib.animation.FuncAnimation:
fig = plt.figure(f'{self._name}Animation', figsize=self.FIGURE_SIZE)
ax = fig.add_subplot(111)
self._prepare_figure(ax)
def make_frame(state_index: int) -> None:
s... | ['def', 'animate(self,', 'states:', 'Sequence[State],', 'interval:', 'int=200,', 'save_path:', 'Optional[str]=None)', '->', 'matplotlib.animation.FuncAnimation:', 'fig', '=', "plt.figure(f'{self._name}Animation',", 'figsize=self.FIGURE_SIZE)', 'ax', '=', 'fig.add_subplot(111)', 'self._prepare_figure(ax)', 'def', 'make_... | 594,245 |
Ruturaj123/Flowchart-Detection | tf_utils.py | accum_val_ops | accum_val_ops | Processes the collected outputs to compute AP for action prediction. | [
"Processes",
"the",
"collected",
"outputs",
"to",
"compute",
"AP",
"for",
"action",
"prediction."
] | def accum_val_ops(outputs, names, global_step, output_dir, metric_summary, N):
outs = []
if N >= 0:
outputs = outputs[:N]
for i in range(len(outputs[0])):
scalar = np.array(map(lambda x: x[i], outputs))
assert scalar.ndim == 1
add_value_to_summary(metric_summary, names[i], np... | ['def', 'accum_val_ops(outputs,', 'names,', 'global_step,', 'output_dir,', 'metric_summary,', 'N):', 'outs', '=', '[]', 'if', 'N', '>=', '0:', 'outputs', '=', 'outputs[:N]', 'for', 'i', 'in', 'range(len(outputs[0])):', 'scalar', '=', 'np.array(map(lambda', 'x:', 'x[i],', 'outputs))', 'assert', 'scalar.ndim', '==', '1',... | 585,511 |
ldkong1205/LaserMix | paconv_regularization_loss.py | PAConvRegularizationLoss.forward | forward | Forward function of loss calculation. | [
"Forward",
"function",
"of",
"loss",
"calculation."
] | def forward(self, modules: List[nn.Module], reduction_override: Optional[str]=None, **kwargs) -> Tensor:
assert reduction_override in (None, 'none', 'mean', 'sum')
reduction = reduction_override if reduction_override else self.reduction
return self.loss_weight * paconv_regularization_loss(modules, reduction... | ['def', 'forward(self,', 'modules:', 'List[nn.Module],', 'reduction_override:', 'Optional[str]=None,', '**kwargs)', '->', 'Tensor:', 'assert', 'reduction_override', 'in', '(None,', "'none',", "'mean',", "'sum')", 'reduction', '=', 'reduction_override', 'if', 'reduction_override', 'else', 'self.reduction', 'return', 'se... | 624,157 |
flavioschneider/rl-transfer- | bc_point.py | OptimalPolicy.get_action | get_action | Get action given observation. | [
"Get",
"action",
"given",
"observation."
] | def get_action(self, observation):
return (self.goal - observation[:2], {}) | ['def', 'get_action(self,', 'observation):', 'return', '(self.goal', '-', 'observation[:2],', '{})'] | 861,114 |
matsu0228/nlp-jp | backend_pgf.py | get_fontspec | get_fontspec | Build fontspec preamble from rc. | [
"Build",
"fontspec",
"preamble",
"from",
"rc."
] | def get_fontspec():
latex_fontspec = []
texcommand = get_texcommand()
if texcommand != 'pdflatex':
latex_fontspec.append('\\usepackage{fontspec}')
if texcommand != 'pdflatex' and rcParams['pgf.rcfonts']:
families = ['serif', 'sans-serif', 'monospace']
fontspecs = ['\\setmainfont{... | ['def', 'get_fontspec():', 'latex_fontspec', '=', '[]', 'texcommand', '=', 'get_texcommand()', 'if', 'texcommand', '!=', "'pdflatex':", "latex_fontspec.append('\\\\usepackage{fontspec}')", 'if', 'texcommand', '!=', "'pdflatex'", 'and', "rcParams['pgf.rcfonts']:", 'families', '=', "['serif',", "'sans-serif',", "'monospa... | 789,644 |
43Carrig/recurrent_neural_networks_practice | timeline.py | _TensorTracker.create_time | create_time | Timestamp when this tensor was created (long integer). | [
"Timestamp",
"when",
"this",
"tensor",
"was",
"created",
"(long",
"integer)."
] | def create_time(self):
return self._create_time | ['def', 'create_time(self):', 'return', 'self._create_time'] | 335,760 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_bases.py | NavigationToolbar2.press_zoom | press_zoom | Callback for mouse button press in zoom to rect mode. | [
"Callback",
"for",
"mouse",
"button",
"press",
"in",
"zoom",
"to",
"rect",
"mode."
] | def press_zoom(self, event):
if self._ids_zoom != []:
for zoom_id in self._ids_zoom:
self.canvas.mpl_disconnect(zoom_id)
self.release(event)
self.draw()
self._xypress = None
self._button_pressed = None
self._ids_zoom = []
return
if event.button... | ['def', 'press_zoom(self,', 'event):', 'if', 'self._ids_zoom', '!=', '[]:', 'for', 'zoom_id', 'in', 'self._ids_zoom:', 'self.canvas.mpl_disconnect(zoom_id)', 'self.release(event)', 'self.draw()', 'self._xypress', '=', 'None', 'self._button_pressed', '=', 'None', 'self._ids_zoom', '=', '[]', 'return', 'if', 'event.butto... | 256,741 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | data_utils.py | add | add | Add two numbers represented as lower-endian digit lists. | [
"Add",
"two",
"numbers",
"represented",
"as",
"lower-endian",
"digit",
"lists."
] | def add(n1, n2, base=10):
k = max(len(n1), len(n2)) + 1
d1 = n1 + [0 for _ in xrange(k - len(n1))]
d2 = n2 + [0 for _ in xrange(k - len(n2))]
res = []
carry = 0
for i in xrange(k):
if d1[i] + d2[i] + carry < base:
res.append(d1[i] + d2[i] + carry)
carry = 0
... | ['def', 'add(n1,', 'n2,', 'base=10):', 'k', '=', 'max(len(n1),', 'len(n2))', '+', '1', 'd1', '=', 'n1', '+', '[0', 'for', '_', 'in', 'xrange(k', '-', 'len(n1))]', 'd2', '=', 'n2', '+', '[0', 'for', '_', 'in', 'xrange(k', '-', 'len(n2))]', 'res', '=', '[]', 'carry', '=', '0', 'for', 'i', 'in', 'xrange(k):', 'if', 'd1[i]... | 50,049 |
triaquae/triaquae | geometries.py | OGRGeometry.geom_count | geom_count | The number of elements in this Geometry. | [
"The",
"number",
"of",
"elements",
"in",
"this",
"Geometry."
] | def geom_count(self):
return capi.get_geom_count(self.ptr) | ['def', 'geom_count(self):', 'return', 'capi.get_geom_count(self.ptr)'] | 357,567 |
Ruturaj123/Flowchart-Detection | ops.py | prepend_name_scope | prepend_name_scope | Prepends name scope to a name. | [
"Prepends",
"name",
"scope",
"to",
"a",
"name."
] | def prepend_name_scope(name, import_scope):
if import_scope:
try:
str_to_replace = '([\\^]|loc:@|^)(.*)'
return re.sub(str_to_replace, '\\1' + import_scope + '/\\2', compat.as_str(name))
except TypeError as e:
logging.warning(e)
return name
else:
... | ['def', 'prepend_name_scope(name,', 'import_scope):', 'if', 'import_scope:', 'try:', 'str_to_replace', '=', "'([\\\\^]|loc:@|^)(.*)'", 'return', 're.sub(str_to_replace,', "'\\\\1'", '+', 'import_scope', '+', "'/\\\\2',", 'compat.as_str(name))', 'except', 'TypeError', 'as', 'e:', 'logging.warning(e)', 'return', 'name', ... | 605,407 |
neurospin/pylearn-parsimony | estimators.py | SVMEstimator.predict | predict | Return a predicted y corresponding to the X given and the model previously determined. | [
"Return",
"a",
"predicted",
"y",
"corresponding",
"to",
"the",
"X",
"given",
"and",
"the",
"model",
"previously",
"determined."
] | def predict(self, X):
X = check_arrays(X)
beta = np.multiply(self.alpha, self.y)
y = np.zeros((X.shape[0], 1))
for j in range(X.shape[0]):
x = X[j, :]
val = 0.0
for i in range(self.X.shape[0]):
val += beta[i, 0] * self.kernel(self.X[i, :], x)
val -= self.bias
... | ['def', 'predict(self,', 'X):', 'X', '=', 'check_arrays(X)', 'beta', '=', 'np.multiply(self.alpha,', 'self.y)', 'y', '=', 'np.zeros((X.shape[0],', '1))', 'for', 'j', 'in', 'range(X.shape[0]):', 'x', '=', 'X[j,', ':]', 'val', '=', '0.0', 'for', 'i', 'in', 'range(self.X.shape[0]):', 'val', '+=', 'beta[i,', '0]', '*', 'se... | 819,909 |
KalleHallden/InstaAutomator | msvc.py | RegistryInfo.vc | vc | Microsoft Visual C++ VC7 registry key. | [
"Microsoft",
"Visual",
"C++",
"VC7",
"registry",
"key."
] | def vc(self):
return os.path.join(self.sxs, 'VC7') | ['def', 'vc(self):', 'return', 'os.path.join(self.sxs,', "'VC7')"] | 232,190 |
eora-ai/torchok | resnet.py | seresnet269d | seresnet269d | Constructs a ResNet-269-D model with SE attn. | [
"Constructs",
"a",
"ResNet-269-D",
"model",
"with",
"SE",
"attn."
] | def seresnet269d(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 30, 48, 8], stem_width=32, stem_type='deep', avg_down=True, block_args=dict(attn_layer='se'), **kwargs)
return _create_resnet('seresnet269d', pretrained, **model_args) | ['def', 'seresnet269d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '30,', '48,', '8],', 'stem_width=32,', "stem_type='deep',", 'avg_down=True,', "block_args=dict(attn_layer='se'),", '**kwargs)', 'return', "_create_resnet('seresnet269d',", 'pretrained,', '**model_args)'] | 903,236 |
shiwt03/MUSTER | lovasz_loss.py | lovasz_hinge_flat | lovasz_hinge_flat | Binary Lovasz hinge loss. | [
"Binary",
"Lovasz",
"hinge",
"loss."
] | def lovasz_hinge_flat(logits, labels):
if len(labels) == 0:
return logits.sum() * 0.0
signs = 2.0 * labels.float() - 1.0
errors = 1.0 - logits * signs
(errors_sorted, perm) = torch.sort(errors, dim=0, descending=True)
perm = perm.data
gt_sorted = labels[perm]
grad = lovasz_grad(gt_so... | ['def', 'lovasz_hinge_flat(logits,', 'labels):', 'if', 'len(labels)', '==', '0:', 'return', 'logits.sum()', '*', '0.0', 'signs', '=', '2.0', '*', 'labels.float()', '-', '1.0', 'errors', '=', '1.0', '-', 'logits', '*', 'signs', '(errors_sorted,', 'perm)', '=', 'torch.sort(errors,', 'dim=0,', 'descending=True)', 'perm', ... | 644,900 |
hsouri/BayesianTransferLearning | ressl.py | ReSSL.forward | forward | Performs forward pass of the online encoder (encoder, projector and predictor). | [
"Performs",
"forward",
"pass",
"of",
"the",
"online",
"encoder",
"(encoder,",
"projector",
"and",
"predictor)."
] | def forward(self, X: torch.Tensor, *args, **kwargs) -> Dict[str, Any]:
out = super().forward(X, *args, **kwargs)
q = F.normalize(self.projector(out['feats']), dim=-1)
return {**out, 'q': q} | ['def', 'forward(self,', 'X:', 'torch.Tensor,', '*args,', '**kwargs)', '->', 'Dict[str,', 'Any]:', 'out', '=', 'super().forward(X,', '*args,', '**kwargs)', 'q', '=', "F.normalize(self.projector(out['feats']),", 'dim=-1)', 'return', '{**out,', "'q':", 'q}'] | 423,000 |
zihuitang/medical_AI_platform | cmd.py | Command.run_command | run_command | Run some other command: uses the 'run_command()' method of Distribution, which creates and finalizes the command object if necessary and then invokes its 'run()' method. | [
"Run",
"some",
"other",
"command:",
"uses",
"the",
"'run_command()'",
"method",
"of",
"Distribution,",
"which",
"creates",
"and",
"finalizes",
"the",
"command",
"object",
"if",
"necessary",
"and",
"then",
"invokes",
"its",
"'run()'",
"method."
] | def run_command(self, command):
self.distribution.run_command(command) | ['def', 'run_command(self,', 'command):', 'self.distribution.run_command(command)'] | 282,202 |
IceClear/MW-GAN | arch_util.py | flow_warp | flow_warp | Warp an image or feature map with optical flow. | [
"Warp",
"an",
"image",
"or",
"feature",
"map",
"with",
"optical",
"flow."
] | def flow_warp(x, flow, interp_mode='bilinear', padding_mode='zeros', align_corners=True):
flow = flow.permute(0, 2, 3, 1)
assert x.size()[-2:] == flow.size()[1:3]
(_, _, h, w) = x.size()
(grid_y, grid_x) = torch.meshgrid(torch.arange(0, h).type_as(x), torch.arange(0, w).type_as(x))
grid = torch.stac... | ['def', 'flow_warp(x,', 'flow,', "interp_mode='bilinear',", "padding_mode='zeros',", 'align_corners=True):', 'flow', '=', 'flow.permute(0,', '2,', '3,', '1)', 'assert', 'x.size()[-2:]', '==', 'flow.size()[1:3]', '(_,', '_,', 'h,', 'w)', '=', 'x.size()', '(grid_y,', 'grid_x)', '=', 'torch.meshgrid(torch.arange(0,', 'h).... | 651,417 |
ldkong1205/LaserMix | encoder_decoder.py | EncoderDecoder3D.predict | predict | Simple test with single scene. | [
"Simple",
"test",
"with",
"single",
"scene."
] | def predict(self, batch_inputs_dict: dict, batch_data_samples: SampleList, rescale: bool=True) -> SampleList:
seg_logits_list = []
batch_input_metas = []
for data_sample in batch_data_samples:
batch_input_metas.append(data_sample.metainfo)
points = batch_inputs_dict['points']
for (point, inp... | ['def', 'predict(self,', 'batch_inputs_dict:', 'dict,', 'batch_data_samples:', 'SampleList,', 'rescale:', 'bool=True)', '->', 'SampleList:', 'seg_logits_list', '=', '[]', 'batch_input_metas', '=', '[]', 'for', 'data_sample', 'in', 'batch_data_samples:', 'batch_input_metas.append(data_sample.metainfo)', 'points', '=', "... | 624,250 |
voxel51/fiftyone | dataset.py | Dataset.delete_saved_views | delete_saved_views | Deletes all saved views from this dataset. | [
"Deletes",
"all",
"saved",
"views",
"from",
"this",
"dataset."
] | def delete_saved_views(self):
for view_doc in self._doc.saved_views:
if isinstance(view_doc, DBRef):
continue
view_doc.delete()
self._doc.saved_views = []
self.save() | ['def', 'delete_saved_views(self):', 'for', 'view_doc', 'in', 'self._doc.saved_views:', 'if', 'isinstance(view_doc,', 'DBRef):', 'continue', 'view_doc.delete()', 'self._doc.saved_views', '=', '[]', 'self.save()'] | 582,935 |
tensorflow/agents | train_eval_atari.py | get_run_args | get_run_args | Builds a dict of run arguments from flags. | [
"Builds",
"a",
"dict",
"of",
"run",
"arguments",
"from",
"flags."
] | def get_run_args():
run_args = {}
if FLAGS.num_iterations:
run_args['num_iterations'] = FLAGS.num_iterations
if FLAGS.initial_collect_steps:
run_args['initial_collect_steps'] = FLAGS.initial_collect_steps
if FLAGS.replay_buffer_capacity:
run_args['replay_buffer_capacity'] = FLAGS... | ['def', 'get_run_args():', 'run_args', '=', '{}', 'if', 'FLAGS.num_iterations:', "run_args['num_iterations']", '=', 'FLAGS.num_iterations', 'if', 'FLAGS.initial_collect_steps:', "run_args['initial_collect_steps']", '=', 'FLAGS.initial_collect_steps', 'if', 'FLAGS.replay_buffer_capacity:', "run_args['replay_buffer_capac... | 23,196 |
alisadeghian/PGMGAN | checkpoints.py | CheckpointIO.load_url | load_url | Load a module dictionary from url. | [
"Load",
"a",
"module",
"dictionary",
"from",
"url."
] | def load_url(self, url):
print('=> Loading checkpoint from url...', url)
state_dict = model_zoo.load_url(url, model_dir=self.checkpoint_dir, progress=True)
scalars = self.parse_state_dict(state_dict)
return scalars | ['def', 'load_url(self,', 'url):', "print('=>", 'Loading', 'checkpoint', 'from', "url...',", 'url)', 'state_dict', '=', 'model_zoo.load_url(url,', 'model_dir=self.checkpoint_dir,', 'progress=True)', 'scalars', '=', 'self.parse_state_dict(state_dict)', 'return', 'scalars'] | 768,392 |
googleapis/python-aiplatform | proto_converters.py | TrialConverter.from_proto | from_proto | Converts from Trial proto to object. | [
"Converts",
"from",
"Trial",
"proto",
"to",
"object."
] | def from_proto(cls, proto: study_pb2.Trial) -> Trial:
parameters = {}
for parameter in proto.parameters:
value = ParameterValueConverter.from_proto(parameter)
if value is not None:
if parameter.parameter_id in parameters:
raise ValueError('Invalid trial proto contains... | ['def', 'from_proto(cls,', 'proto:', 'study_pb2.Trial)', '->', 'Trial:', 'parameters', '=', '{}', 'for', 'parameter', 'in', 'proto.parameters:', 'value', '=', 'ParameterValueConverter.from_proto(parameter)', 'if', 'value', 'is', 'not', 'None:', 'if', 'parameter.parameter_id', 'in', 'parameters:', 'raise', "ValueError('... | 810,293 |
megvii-research/MSCL | resnet_tin.py | ResNetTIN.make_temporal_interlace | make_temporal_interlace | Make temporal interlace for some layers. | [
"Make",
"temporal",
"interlace",
"for",
"some",
"layers."
] | def make_temporal_interlace(self):
num_segment_list = [self.num_segments] * 4
assert num_segment_list[-1] > 0
n_round = 1
if len(list(self.layer3.children())) >= 23:
print(f'=> Using n_round {n_round} to insert temporal shift.')
def make_block_interlace(stage, num_segments, shift_div):
... | ['def', 'make_temporal_interlace(self):', 'num_segment_list', '=', '[self.num_segments]', '*', '4', 'assert', 'num_segment_list[-1]', '>', '0', 'n_round', '=', '1', 'if', 'len(list(self.layer3.children()))', '>=', '23:', "print(f'=>", 'Using', 'n_round', '{n_round}', 'to', 'insert', 'temporal', "shift.')", 'def', 'make... | 264,842 |
flavioschneider/rl-transfer- | gaussian_mlp_policy.py | gaussian_mlp_policy | gaussian_mlp_policy | Create Gaussian MLP Policy on TF-PPO. | [
"Create",
"Gaussian",
"MLP",
"Policy",
"on",
"TF-PPO."
] | def gaussian_mlp_policy(ctxt, env_id, seed):
deterministic.set_seed(seed)
with TFTrainer(ctxt) as trainer:
env = normalize(GymEnv(env_id))
policy = GaussianMLPPolicy(env_spec=env.spec, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, output_nonlinearity=None)
baseline = GaussianMLP... | ['def', 'gaussian_mlp_policy(ctxt,', 'env_id,', 'seed):', 'deterministic.set_seed(seed)', 'with', 'TFTrainer(ctxt)', 'as', 'trainer:', 'env', '=', 'normalize(GymEnv(env_id))', 'policy', '=', 'GaussianMLPPolicy(env_spec=env.spec,', 'hidden_sizes=(32,', '32),', 'hidden_nonlinearity=tf.nn.tanh,', 'output_nonlinearity=None... | 860,924 |
openvinotoolkit/datumaro | __init__.py | HLOps.export | export | Saves the input dataset in some format. | [
"Saves",
"the",
"input",
"dataset",
"in",
"some",
"format."
] | def export(dataset: IDataset, path: str, format: Union[str, Type[Exporter]], *, env: Optional[Environment]=None, **kwargs) -> None:
if isinstance(format, str):
if env is None:
env = Environment()
exporter = env.exporters[format]
else:
exporter = format
if not (inspect.isc... | ['def', 'export(dataset:', 'IDataset,', 'path:', 'str,', 'format:', 'Union[str,', 'Type[Exporter]],', '*,', 'env:', 'Optional[Environment]=None,', '**kwargs)', '->', 'None:', 'if', 'isinstance(format,', 'str):', 'if', 'env', 'is', 'None:', 'env', '=', 'Environment()', 'exporter', '=', 'env.exporters[format]', 'else:', ... | 498,183 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | _pydecimal.py | Context.copy | copy | Returns a deep copy from self. | [
"Returns",
"a",
"deep",
"copy",
"from",
"self."
] | def copy(self):
nc = Context(self.prec, self.rounding, self.Emin, self.Emax, self.capitals, self.clamp, self.flags.copy(), self.traps.copy(), self._ignored_flags)
return nc | ['def', 'copy(self):', 'nc', '=', 'Context(self.prec,', 'self.rounding,', 'self.Emin,', 'self.Emax,', 'self.capitals,', 'self.clamp,', 'self.flags.copy(),', 'self.traps.copy(),', 'self._ignored_flags)', 'return', 'nc'] | 430,010 |
AxeldeRomblay/MLBox | test_drift_estimator.py | test_score_drift_estimator | test_score_drift_estimator | Test score method of DriftEstimator class. | [
"Test",
"score",
"method",
"of",
"DriftEstimator",
"class."
] | def test_score_drift_estimator():
df_train = pd.read_csv('data_for_tests/clean_train.csv')
df_test = pd.read_csv('data_for_tests/clean_test.csv')
drift_estimator = DriftEstimator()
with pytest.raises(ValueError):
drift_estimator.score()
drift_estimator.fit(df_train, df_test)
assert drift... | ['def', 'test_score_drift_estimator():', 'df_train', '=', "pd.read_csv('data_for_tests/clean_train.csv')", 'df_test', '=', "pd.read_csv('data_for_tests/clean_test.csv')", 'drift_estimator', '=', 'DriftEstimator()', 'with', 'pytest.raises(ValueError):', 'drift_estimator.score()', 'drift_estimator.fit(df_train,', 'df_tes... | 630,022 |
rlgraph/rlgraph | graph_builder.py | GraphBuilder.execute_define_by_run_op | execute_define_by_run_op | Executes an API method by simply calling the respective function directly with its parameters to trigger an eager call-chain through the graph. | [
"Executes",
"an",
"API",
"method",
"by",
"simply",
"calling",
"the",
"respective",
"function",
"directly",
"with",
"its",
"parameters",
"to",
"trigger",
"an",
"eager",
"call-chain",
"through",
"the",
"graph."
] | def execute_define_by_run_op(self, api_method, params=None):
Component.reset_profile()
if api_method not in self.api:
raise RLGraphError("No API-method with name '{}' found!".format(api_method))
if params is not None:
if api_method in self.root_component.synthetic_methods:
return... | ['def', 'execute_define_by_run_op(self,', 'api_method,', 'params=None):', 'Component.reset_profile()', 'if', 'api_method', 'not', 'in', 'self.api:', 'raise', 'RLGraphError("No', 'API-method', 'with', 'name', "'{}'", 'found!".format(api_method))', 'if', 'params', 'is', 'not', 'None:', 'if', 'api_method', 'in', 'self.roo... | 862,596 |
meidachen/STPLS3D | cindex.py | Type.is_function_variadic | is_function_variadic | Determine whether this function Type is a variadic function type. | [
"Determine",
"whether",
"this",
"function",
"Type",
"is",
"a",
"variadic",
"function",
"type."
] | def is_function_variadic(self):
assert self.kind == TypeKind.FUNCTIONPROTO
return conf.lib.clang_isFunctionTypeVariadic(self) | ['def', 'is_function_variadic(self):', 'assert', 'self.kind', '==', 'TypeKind.FUNCTIONPROTO', 'return', 'conf.lib.clang_isFunctionTypeVariadic(self)'] | 909,181 |
triaquae/triaquae | util.py | flatten_fieldsets | flatten_fieldsets | Returns a list of field names from an admin fieldsets structure. | [
"Returns",
"a",
"list",
"of",
"field",
"names",
"from",
"an",
"admin",
"fieldsets",
"structure."
] | def flatten_fieldsets(fieldsets):
field_names = []
for (name, opts) in fieldsets:
for field in opts['fields']:
if type(field) == tuple:
field_names.extend(field)
else:
field_names.append(field)
return field_names | ['def', 'flatten_fieldsets(fieldsets):', 'field_names', '=', '[]', 'for', '(name,', 'opts)', 'in', 'fieldsets:', 'for', 'field', 'in', "opts['fields']:", 'if', 'type(field)', '==', 'tuple:', 'field_names.extend(field)', 'else:', 'field_names.append(field)', 'return', 'field_names'] | 357,016 |
nancheng58/Self-supervised-learning-for-Sequential-Recommender-Systems | dataset.py | Dataset.leave_one_out | leave_one_out | Split interaction records by leave one out strategy. | [
"Split",
"interaction",
"records",
"by",
"leave",
"one",
"out",
"strategy."
] | def leave_one_out(self, group_by, leave_one_mode):
self.logger.debug(f'leave one out, group_by=[{group_by}], leave_one_mode=[{leave_one_mode}]')
if group_by is None:
raise ValueError('leave one out strategy require a group field')
grouped_inter_feat_index = self._grouped_index(self.inter_feat[group_... | ['def', 'leave_one_out(self,', 'group_by,', 'leave_one_mode):', "self.logger.debug(f'leave", 'one', 'out,', 'group_by=[{group_by}],', "leave_one_mode=[{leave_one_mode}]')", 'if', 'group_by', 'is', 'None:', 'raise', "ValueError('leave", 'one', 'out', 'strategy', 'require', 'a', 'group', "field')", 'grouped_inter_feat_in... | 341,812 |
googleapis/python-aiplatform | client.py | MetadataServiceClient.common_location_path | common_location_path | Returns a fully-qualified location string. | [
"Returns",
"a",
"fully-qualified",
"location",
"string."
] | def common_location_path(project: str, location: str) -> str:
return 'projects/{project}/locations/{location}'.format(project=project, location=location) | ['def', 'common_location_path(project:', 'str,', 'location:', 'str)', '->', 'str:', 'return', "'projects/{project}/locations/{location}'.format(project=project,", 'location=location)'] | 811,150 |
myothida/Supervised-Machine-Learning | mypy_plugin.py | plugin | plugin | An entry-point for mypy. | [
"An",
"entry-point",
"for",
"mypy."
] | def plugin(version: str) -> type[_NumpyPlugin]:
return _NumpyPlugin | ['def', 'plugin(version:', 'str)', '->', 'type[_NumpyPlugin]:', 'return', '_NumpyPlugin'] | 442,108 |
Center-of-Diagnostics-and-Telemedicine/ai-testing-platform | period.py | PeriodIndex.is_full | is_full | Returns True if this PeriodIndex is range-like in that all Periods between start and end are present, in order. | [
"Returns",
"True",
"if",
"this",
"PeriodIndex",
"is",
"range-like",
"in",
"that",
"all",
"Periods",
"between",
"start",
"and",
"end",
"are",
"present,",
"in",
"order."
] | def is_full(self) -> bool:
if len(self) == 0:
return True
if not self.is_monotonic:
raise ValueError('Index is not monotonic')
values = self.asi8
return (values[1:] - values[:-1] < 2).all() | ['def', 'is_full(self)', '->', 'bool:', 'if', 'len(self)', '==', '0:', 'return', 'True', 'if', 'not', 'self.is_monotonic:', 'raise', "ValueError('Index", 'is', 'not', "monotonic')", 'values', '=', 'self.asi8', 'return', '(values[1:]', '-', 'values[:-1]', '<', '2).all()'] | 82,975 |
MushroomRL/mushroom-rl | serialization.py | Serializable.copy | copy | Returns: A deepcopy of the agent. | [
"Returns:",
"A",
"deepcopy",
"of",
"the",
"agent."
] | def copy(self):
return deepcopy(self) | ['def', 'copy(self):', 'return', 'deepcopy(self)'] | 266,010 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | zmqshell.py | ZMQInteractiveShell.set_next_input | set_next_input | Send the specified text to the frontend to be presented at the next input cell. | [
"Send",
"the",
"specified",
"text",
"to",
"the",
"frontend",
"to",
"be",
"presented",
"at",
"the",
"next",
"input",
"cell."
] | def set_next_input(self, text, replace=False):
payload = dict(source='set_next_input', text=text, replace=replace)
self.payload_manager.write_payload(payload) | ['def', 'set_next_input(self,', 'text,', 'replace=False):', 'payload', '=', "dict(source='set_next_input',", 'text=text,', 'replace=replace)', 'self.payload_manager.write_payload(payload)'] | 447,864 |
cslu-nlp/nlup | perceptron.py | Perceptron.update | update | Rewards correct observation and penalizes incorrect observation for a feature vector. | [
"Rewards",
"correct",
"observation",
"and",
"penalizes",
"incorrect",
"observation",
"for",
"a",
"feature",
"vector."
] | def update(self, y, yhat, phi, alpha=1):
for phi_i in phi:
ptr = self.weights[phi_i]
ptr[y] += alpha
ptr[yhat] -= alpha | ['def', 'update(self,', 'y,', 'yhat,', 'phi,', 'alpha=1):', 'for', 'phi_i', 'in', 'phi:', 'ptr', '=', 'self.weights[phi_i]', 'ptr[y]', '+=', 'alpha', 'ptr[yhat]', '-=', 'alpha'] | 731,729 |
sentinel-hub/eo-learn | test_parsing.py | test_all_features_allowed_feature_types | test_all_features_allowed_feature_types | Ensure that allowed_feature_types is respected when requesting all features. | [
"Ensure",
"that",
"allowed_feature_types",
"is",
"respected",
"when",
"requesting",
"all",
"features."
] | def test_all_features_allowed_feature_types(eopatch: EOPatch, allowed_types: Iterable[FeatureType] | Callable[[FeatureType], bool]):
parser = FeatureParser(..., allowed_feature_types=allowed_types)
assert parser.get_feature_specifications() == [(FeatureType.DATA_TIMELESS, ...), (FeatureType.MASK_TIMELESS, ...)]... | ['def', 'test_all_features_allowed_feature_types(eopatch:', 'EOPatch,', 'allowed_types:', 'Iterable[FeatureType]', '|', 'Callable[[FeatureType],', 'bool]):', 'parser', '=', 'FeatureParser(...,', 'allowed_feature_types=allowed_types)', 'assert', 'parser.get_feature_specifications()', '==', '[(FeatureType.DATA_TIMELESS,'... | 562,695 |
ahthie7u/cockpit | test_mean_gsnr.py | AutogradMeanGSNR.extension_hooks | extension_hooks | Return list of BackPACK extension hooks required for the computation. | [
"Return",
"list",
"of",
"BackPACK",
"extension",
"hooks",
"required",
"for",
"the",
"computation."
] | def extension_hooks(self, global_step):
return [] | ['def', 'extension_hooks(self,', 'global_step):', 'return', '[]'] | 492,851 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | vecs.py | Vecs.lookup | lookup | Returns the embedding for a token, or None if no embedding exists. | [
"Returns",
"the",
"embedding",
"for",
"a",
"token,",
"or",
"None",
"if",
"no",
"embedding",
"exists."
] | def lookup(self, word):
idx = self.word_to_idx.get(word)
return None if idx is None else self.vecs[idx] | ['def', 'lookup(self,', 'word):', 'idx', '=', 'self.word_to_idx.get(word)', 'return', 'None', 'if', 'idx', 'is', 'None', 'else', 'self.vecs[idx]'] | 110,816 |
icantrell/Natural-Language-Processing | test_singlerank.py | test_singlerank_candidate_selection | test_singlerank_candidate_selection | Test SingleRank candidate selection method. | [
"Test",
"SingleRank",
"candidate",
"selection",
"method."
] | def test_singlerank_candidate_selection():
extractor = pke.unsupervised.SingleRank()
extractor.load_document(input=test_file)
extractor.candidate_selection(pos=pos)
assert len(extractor.candidates) == 20 | ['def', 'test_singlerank_candidate_selection():', 'extractor', '=', 'pke.unsupervised.SingleRank()', 'extractor.load_document(input=test_file)', 'extractor.candidate_selection(pos=pos)', 'assert', 'len(extractor.candidates)', '==', '20'] | 663,131 |
ancasag/ensembleObjectDetection | pascal.py | PascalVocGenerator.num_classes | num_classes | Number of classes in the dataset. | [
"Number",
"of",
"classes",
"in",
"the",
"dataset."
] | def num_classes(self):
return len(self.classes) | ['def', 'num_classes(self):', 'return', 'len(self.classes)'] | 561,888 |
iffiX/machin | _world.py | get_cur_name | get_cur_name | Returns: Current real process name. | [
"Returns:",
"Current",
"real",
"process",
"name."
] | def get_cur_name():
if WORLD is None:
raise RuntimeError('Distributed environment not initialized!')
return WORLD.name | ['def', 'get_cur_name():', 'if', 'WORLD', 'is', 'None:', 'raise', "RuntimeError('Distributed", 'environment', 'not', "initialized!')", 'return', 'WORLD.name'] | 620,409 |
yogeshbalaji/InvGAN | optimization.py | Optimization.run_one_step | run_one_step | Run one step of gradient descent for optimization. | [
"Run",
"one",
"step",
"of",
"gradient",
"descent",
"for",
"optimization."
] | def run_one_step(self, eig_init_vec_val, eig_num_iter_val, smooth_val, penalty_val, learning_rate_val):
if self.current_step != 0 and self.current_step % self.params['projection_steps'] == 0:
if self.dual_object.compute_certificate(self.current_step):
return True
step_feed_dict = {self.eig_i... | ['def', 'run_one_step(self,', 'eig_init_vec_val,', 'eig_num_iter_val,', 'smooth_val,', 'penalty_val,', 'learning_rate_val):', 'if', 'self.current_step', '!=', '0', 'and', 'self.current_step', '%', "self.params['projection_steps']", '==', '0:', 'if', 'self.dual_object.compute_certificate(self.current_step):', 'return', ... | 576,694 |
43Carrig/recurrent_neural_networks_practice | gen_collective_ops.py | collective_reduce | collective_reduce | Mutually reduces multiple tensors of identical type and shape. | [
"Mutually",
"reduces",
"multiple",
"tensors",
"of",
"identical",
"type",
"and",
"shape."
] | def collective_reduce(input, group_size, group_key, instance_key, merge_op, final_op, subdiv_offsets, name=None):
_ctx = _context._context
if _ctx is None or not _ctx._eager_context.is_eager:
group_size = _execute.make_int(group_size, 'group_size')
group_key = _execute.make_int(group_key, 'group... | ['def', 'collective_reduce(input,', 'group_size,', 'group_key,', 'instance_key,', 'merge_op,', 'final_op,', 'subdiv_offsets,', 'name=None):', '_ctx', '=', '_context._context', 'if', '_ctx', 'is', 'None', 'or', 'not', '_ctx._eager_context.is_eager:', 'group_size', '=', '_execute.make_int(group_size,', "'group_size')", '... | 337,502 |
LLNL/Abmarl | gym_env_wrapper.py | GymWrapper.reset | reset | Return the observation from the single agent. | [
"Return",
"the",
"observation",
"from",
"the",
"single",
"agent."
] | def reset(self, **kwargs):
obs = self.sim.reset(**kwargs)
return obs[self.agent_id] | ['def', 'reset(self,', '**kwargs):', 'obs', '=', 'self.sim.reset(**kwargs)', 'return', 'obs[self.agent_id]'] | 405,658 |
deepmind/dm_control | dog.py | Stand.get_observation_components | get_observation_components | Returns the observations for the Stand task. | [
"Returns",
"the",
"observations",
"for",
"the",
"Stand",
"task."
] | def get_observation_components(self, physics):
obs = collections.OrderedDict()
obs['joint_angles'] = physics.joint_angles()
obs['joint_velocites'] = physics.joint_velocities()
obs['torso_pelvis_height'] = physics.torso_pelvis_height()
obs['z_projection'] = physics.z_projection().flatten()
obs['t... | ['def', 'get_observation_components(self,', 'physics):', 'obs', '=', 'collections.OrderedDict()', "obs['joint_angles']", '=', 'physics.joint_angles()', "obs['joint_velocites']", '=', 'physics.joint_velocities()', "obs['torso_pelvis_height']", '=', 'physics.torso_pelvis_height()', "obs['z_projection']", '=', 'physics.z_... | 166,325 |
open-mmlab/mmdetection3d | loading.py | NormalizePointsColor.transform | transform | Call function to normalize color of points. | [
"Call",
"function",
"to",
"normalize",
"color",
"of",
"points."
] | def transform(self, input_dict: dict) -> dict:
points = input_dict['points']
assert points.attribute_dims is not None and 'color' in points.attribute_dims.keys(), 'Expect points have color attribute'
if self.color_mean is not None:
points.color = points.color - points.color.new_tensor(self.color_mea... | ['def', 'transform(self,', 'input_dict:', 'dict)', '->', 'dict:', 'points', '=', "input_dict['points']", 'assert', 'points.attribute_dims', 'is', 'not', 'None', 'and', "'color'", 'in', 'points.attribute_dims.keys(),', "'Expect", 'points', 'have', 'color', "attribute'", 'if', 'self.color_mean', 'is', 'not', 'None:', 'po... | 631,715 |
rudranil723/mini-main | backend_bases.py | GraphicsContextBase.get_url | get_url | Return a url if one is set, None otherwise. | [
"Return",
"a",
"url",
"if",
"one",
"is",
"set,",
"None",
"otherwise."
] | def get_url(self):
return self._url | ['def', 'get_url(self):', 'return', 'self._url'] | 319,096 |
aws/sagemaker-python-sdk | utils.py | verify_model_region_and_return_specs | verify_model_region_and_return_specs | Verifies that an acceptable model_id, version, scope, and region combination is provided. | [
"Verifies",
"that",
"an",
"acceptable",
"model_id,",
"version,",
"scope,",
"and",
"region",
"combination",
"is",
"provided."
] | def verify_model_region_and_return_specs(model_id: Optional[str], version: Optional[str], scope: Optional[str], region: str, tolerate_vulnerable_model: bool=False, tolerate_deprecated_model: bool=False, sagemaker_session: Session=constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION) -> JumpStartModelSpecs:
if scope is Non... | ['def', 'verify_model_region_and_return_specs(model_id:', 'Optional[str],', 'version:', 'Optional[str],', 'scope:', 'Optional[str],', 'region:', 'str,', 'tolerate_vulnerable_model:', 'bool=False,', 'tolerate_deprecated_model:', 'bool=False,', 'sagemaker_session:', 'Session=constants.DEFAULT_JUMPSTART_SAGEMAKER_SESSION)... | 830,215 |
Ruturaj123/Flowchart-Detection | ops.py | select | select | Slice out a subset of the tensor. | [
"Slice",
"out",
"a",
"subset",
"of",
"the",
"tensor."
] | def select(labeled_tensor, selection, name=None):
with ops.name_scope(name, 'lt_select', [labeled_tensor]) as scope:
labeled_tensor = core.convert_to_labeled_tensor(labeled_tensor)
slices = {}
indexers = {}
for (axis_name, value) in selection.items():
if axis_name not in ... | ['def', 'select(labeled_tensor,', 'selection,', 'name=None):', 'with', 'ops.name_scope(name,', "'lt_select',", '[labeled_tensor])', 'as', 'scope:', 'labeled_tensor', '=', 'core.convert_to_labeled_tensor(labeled_tensor)', 'slices', '=', '{}', 'indexers', '=', '{}', 'for', '(axis_name,', 'value)', 'in', 'selection.items(... | 603,571 |
Yuting-Gao/DisCo-pytorch | resnet.py | ecaresnet269d | ecaresnet269d | Constructs a ResNet-269-D model with ECA. | [
"Constructs",
"a",
"ResNet-269-D",
"model",
"with",
"ECA."
] | def ecaresnet269d(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 30, 48, 8], stem_width=32, stem_type='deep', avg_down=True, block_args=dict(attn_layer='eca'), **kwargs)
return _create_resnet('ecaresnet269d', pretrained, **model_args) | ['def', 'ecaresnet269d(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=Bottleneck,', 'layers=[3,', '30,', '48,', '8],', 'stem_width=32,', "stem_type='deep',", 'avg_down=True,', "block_args=dict(attn_layer='eca'),", '**kwargs)', 'return', "_create_resnet('ecaresnet269d',", 'pretrained,', '**model_args)'... | 186,863 |
davidventuri/udacity-aind | solution.py | solve | solve | Find the solution to a Sudoku grid. | [
"Find",
"the",
"solution",
"to",
"a",
"Sudoku",
"grid."
] | def solve(grid):
values = grid_values(grid)
return search(values) | ['def', 'solve(grid):', 'values', '=', 'grid_values(grid)', 'return', 'search(values)'] | 427,907 |
exiawsh/StreamPETR | repdetr3d.py | RepDetr3D.extract_img_feat | extract_img_feat | Extract features of images. | [
"Extract",
"features",
"of",
"images."
] | def extract_img_feat(self, img, len_queue=1, training_mode=False):
B = img.size(0)
if img is not None:
if img.dim() == 6:
img = img.flatten(1, 2)
if img.dim() == 5 and img.size(0) == 1:
img.squeeze_()
elif img.dim() == 5 and img.size(0) > 1:
(B, N, C, ... | ['def', 'extract_img_feat(self,', 'img,', 'len_queue=1,', 'training_mode=False):', 'B', '=', 'img.size(0)', 'if', 'img', 'is', 'not', 'None:', 'if', 'img.dim()', '==', '6:', 'img', '=', 'img.flatten(1,', '2)', 'if', 'img.dim()', '==', '5', 'and', 'img.size(0)', '==', '1:', 'img.squeeze_()', 'elif', 'img.dim()', '==', '... | 910,073 |
deepmind/acme | builder.py | TD3Builder.make_dataset_iterator | make_dataset_iterator | Creates a dataset iterator to use for learning. | [
"Creates",
"a",
"dataset",
"iterator",
"to",
"use",
"for",
"learning."
] | def make_dataset_iterator(self, replay_client: reverb.Client) -> Iterator[reverb.ReplaySample]:
dataset = datasets.make_reverb_dataset(table=self._config.replay_table_name, server_address=replay_client.server_address, batch_size=self._config.batch_size * self._config.num_sgd_steps_per_step, prefetch_size=self._conf... | ['def', 'make_dataset_iterator(self,', 'replay_client:', 'reverb.Client)', '->', 'Iterator[reverb.ReplaySample]:', 'dataset', '=', 'datasets.make_reverb_dataset(table=self._config.replay_table_name,', 'server_address=replay_client.server_address,', 'batch_size=self._config.batch_size', '*', 'self._config.num_sgd_steps_... | 8,200 |
thaines/helit | model.py | Sample.getTopicUseWeight | getTopicUseWeight | Returns how many times the given topic has been instanced in a cluster. | [
"Returns",
"how",
"many",
"times",
"the",
"given",
"topic",
"has",
"been",
"instanced",
"in",
"a",
"cluster."
] | def getTopicUseWeight(self, t):
return self.topicUse[t] | ['def', 'getTopicUseWeight(self,', 't):', 'return', 'self.topicUse[t]'] | 591,484 |
ajMIT95/MIT_Artificial_Intelligence_Labs | lab7.py | check_alpha_signs | check_alpha_signs | Returns the set of training points that violate either condition: * all non-support-vector training points have alpha = 0 * all support vectors have alpha > 0 Assumes that the SVM has support vectors assigned, and that all training points have alpha values assigned. | [
"Returns",
"the",
"set",
"of",
"training",
"points",
"that",
"violate",
"either",
"condition:",
"*",
"all",
"non-support-vector",
"training",
"points",
"have",
"alpha",
"=",
"0",
"*",
"all",
"support",
"vectors",
"have",
"alpha",
">",
"0",
"Assumes",
"that",
... | def check_alpha_signs(svm):
illegal_points = []
for point in svm.training_points:
is_support_vector = True if point in svm.support_vectors else False
if not is_support_vector and point.alpha != 0:
illegal_points.append(point)
if is_support_vector and point.alpha <= 0:
... | ['def', 'check_alpha_signs(svm):', 'illegal_points', '=', '[]', 'for', 'point', 'in', 'svm.training_points:', 'is_support_vector', '=', 'True', 'if', 'point', 'in', 'svm.support_vectors', 'else', 'False', 'if', 'not', 'is_support_vector', 'and', 'point.alpha', '!=', '0:', 'illegal_points.append(point)', 'if', 'is_suppo... | 239,383 |
sktime/sktime | test_all_distrs.py | TestAllDistributions.test_methods_p | test_methods_p | Test expected return of methods that take percentage-like argument. | [
"Test",
"expected",
"return",
"of",
"methods",
"that",
"take",
"percentage-like",
"argument."
] | def test_methods_p(self, estimator_instance, method):
if not _has_capability(estimator_instance, method):
return None
d = estimator_instance
np_unif = np.random.uniform(size=d.shape)
p = pd.DataFrame(np_unif, index=d.index, columns=d.columns)
res = getattr(estimator_instance, method)(p)
... | ['def', 'test_methods_p(self,', 'estimator_instance,', 'method):', 'if', 'not', '_has_capability(estimator_instance,', 'method):', 'return', 'None', 'd', '=', 'estimator_instance', 'np_unif', '=', 'np.random.uniform(size=d.shape)', 'p', '=', 'pd.DataFrame(np_unif,', 'index=d.index,', 'columns=d.columns)', 'res', '=', '... | 877,496 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | map_utils.py | compute_traversibility | compute_traversibility | Returns a bit map with pixels that are traversible or not as long as the robot center is inside this volume we are good colisions can be detected by doing a line search on things, or walking from current location to final location in the bitmap, or doing bwlabel on the traversibility map. | [
"Returns",
"a",
"bit",
"map",
"with",
"pixels",
"that",
"are",
"traversible",
"or",
"not",
"as",
"long",
"as",
"the",
"robot",
"center",
"is",
"inside",
"this",
"volume",
"we",
"are",
"good",
"colisions",
"can",
"be",
"detected",
"by",
"doing",
"a",
"lin... | def compute_traversibility(map, robot_base, robot_height, robot_radius, valid_min, valid_max, num_point_threshold, shapess, sc=100.0, n_samples_per_face=200):
tt = utils.Timer()
tt.tic()
num_obstcale_points = np.zeros((map.size[1], map.size[0]))
num_points = np.zeros((map.size[1], map.size[0]))
for ... | ['def', 'compute_traversibility(map,', 'robot_base,', 'robot_height,', 'robot_radius,', 'valid_min,', 'valid_max,', 'num_point_threshold,', 'shapess,', 'sc=100.0,', 'n_samples_per_face=200):', 'tt', '=', 'utils.Timer()', 'tt.tic()', 'num_obstcale_points', '=', 'np.zeros((map.size[1],', 'map.size[0]))', 'num_points', '=... | 53,541 |
TheCurryMan/MedicAI | dictconfig.py | DictConfigurator.configure_formatter | configure_formatter | Configure a formatter from a dictionary. | [
"Configure",
"a",
"formatter",
"from",
"a",
"dictionary."
] | def configure_formatter(self, config):
if '()' in config:
factory = config['()']
try:
result = self.configure_custom(config)
except TypeError as te:
if "'format'" not in str(te):
raise
config['fmt'] = config.pop('format')
config... | ['def', 'configure_formatter(self,', 'config):', 'if', "'()'", 'in', 'config:', 'factory', '=', "config['()']", 'try:', 'result', '=', 'self.configure_custom(config)', 'except', 'TypeError', 'as', 'te:', 'if', '"\'format\'"', 'not', 'in', 'str(te):', 'raise', "config['fmt']", '=', "config.pop('format')", "config['()']"... | 648,603 |
nicknochnack/RealTimeSignLanguageTFJS | classifier_trainer_test.py | get_params_override | get_params_override | Converts params_override dict to string command. | [
"Converts",
"params_override",
"dict",
"to",
"string",
"command."
] | def get_params_override(params_override: Mapping[str, Any]) -> str:
return '--params_override=' + json.dumps(params_override) | ['def', 'get_params_override(params_override:', 'Mapping[str,', 'Any])', '->', 'str:', 'return', "'--params_override='", '+', 'json.dumps(params_override)'] | 851,154 |
mkusner/grammarVAE | test_conv.py | TestSignalConv2D.test_fail | test_fail | Test that conv2d fails for dimensions other than 2 or 3. | [
"Test",
"that",
"conv2d",
"fails",
"for",
"dimensions",
"other",
"than",
"2",
"or",
"3."
] | def test_fail(self):
self.assertRaises(Exception, conv.conv2d, T.dtensor4(), T.dtensor3())
self.assertRaises(Exception, conv.conv2d, T.dtensor3(), T.dvector()) | ['def', 'test_fail(self):', 'self.assertRaises(Exception,', 'conv.conv2d,', 'T.dtensor4(),', 'T.dtensor3())', 'self.assertRaises(Exception,', 'conv.conv2d,', 'T.dtensor3(),', 'T.dvector())'] | 580,111 |
zzndream/ShipRSImageNet | utils.py | verify_model | verify_model | Run the model in onnxruntime env. | [
"Run",
"the",
"model",
"in",
"onnxruntime",
"env."
] | def verify_model(feat, onnx_io='tmp.onnx'):
onnx_model = onnx.load(onnx_io)
onnx.checker.check_model(onnx_model)
session_options = ort.SessionOptions()
if osp.exists(ort_custom_op_path):
session_options.register_custom_ops_library(ort_custom_op_path)
sess = ort.InferenceSession(onnx_io, sess... | ['def', 'verify_model(feat,', "onnx_io='tmp.onnx'):", 'onnx_model', '=', 'onnx.load(onnx_io)', 'onnx.checker.check_model(onnx_model)', 'session_options', '=', 'ort.SessionOptions()', 'if', 'osp.exists(ort_custom_op_path):', 'session_options.register_custom_ops_library(ort_custom_op_path)', 'sess', '=', 'ort.InferenceSe... | 933,643 |
surafelml/adapt-mnmt | decoder.py | logits_to_cum_log_probs | logits_to_cum_log_probs | Returns the cumulated log probabilities of sequences. | [
"Returns",
"the",
"cumulated",
"log",
"probabilities",
"of",
"sequences."
] | def logits_to_cum_log_probs(logits, sequence_length):
mask = tf.sequence_mask(sequence_length, maxlen=tf.shape(logits)[1], dtype=logits.dtype)
mask = tf.expand_dims(mask, -1)
log_probs = tf.nn.log_softmax(logits)
log_probs = log_probs * mask
log_probs = tf.reduce_max(log_probs, axis=-1)
log_prob... | ['def', 'logits_to_cum_log_probs(logits,', 'sequence_length):', 'mask', '=', 'tf.sequence_mask(sequence_length,', 'maxlen=tf.shape(logits)[1],', 'dtype=logits.dtype)', 'mask', '=', 'tf.expand_dims(mask,', '-1)', 'log_probs', '=', 'tf.nn.log_softmax(logits)', 'log_probs', '=', 'log_probs', '*', 'mask', 'log_probs', '=',... | 407,920 |
LorenzoCassano/TablutChallenge22-23 | games.py | Backgammon.outcome | outcome | Return the state which is the outcome of a dice roll. | [
"Return",
"the",
"state",
"which",
"is",
"the",
"outcome",
"of",
"a",
"dice",
"roll."
] | def outcome(self, state, chance):
dice = tuple(map(self.direction[state.to_move].__mul__, chance))
return StochasticGameState(to_move=state.to_move, utility=state.utility, board=state.board, moves=state.moves, chance=dice) | ['def', 'outcome(self,', 'state,', 'chance):', 'dice', '=', 'tuple(map(self.direction[state.to_move].__mul__,', 'chance))', 'return', 'StochasticGameState(to_move=state.to_move,', 'utility=state.utility,', 'board=state.board,', 'moves=state.moves,', 'chance=dice)'] | 365,190 |
openvinotoolkit/training_extensions | hpo.py | TaskEnvironmentManager.get_new_model_entity | get_new_model_entity | Get new model entity using environment. | [
"Get",
"new",
"model",
"entity",
"using",
"environment."
] | def get_new_model_entity(self, dataset=None) -> ModelEntity:
return ModelEntity(dataset, self._environment.get_model_configuration()) | ['def', 'get_new_model_entity(self,', 'dataset=None)', '->', 'ModelEntity:', 'return', 'ModelEntity(dataset,', 'self._environment.get_model_configuration())'] | 918,990 |
googleapis/python-aiplatform | base.py | IndexServiceTransport.operations_client | operations_client | Return the client designed to process long-running operations. | [
"Return",
"the",
"client",
"designed",
"to",
"process",
"long-running",
"operations."
] | def operations_client(self):
raise NotImplementedError() | ['def', 'operations_client(self):', 'raise', 'NotImplementedError()'] | 812,990 |
enuguru/artificial_intelligence_and_machine_learning | base.py | Segment.doc_count | doc_count | Returns the number of (undeleted) documents in this segment. | [
"Returns",
"the",
"number",
"of",
"(undeleted)",
"documents",
"in",
"this",
"segment."
] | def doc_count(self):
return self.doc_count_all() - self.deleted_count() | ['def', 'doc_count(self):', 'return', 'self.doc_count_all()', '-', 'self.deleted_count()'] | 133,271 |
chengfx/neural-networks-and-deep-learning-for-python3 | Network_SoftmaxAndLog-likelihood.py | sigmoid_prime | sigmoid_prime | Derivative of the sigmoid function. | [
"Derivative",
"of",
"the",
"sigmoid",
"function."
] | def sigmoid_prime(z):
return sigmoid(z) * (1 - sigmoid(z)) | ['def', 'sigmoid_prime(z):', 'return', 'sigmoid(z)', '*', '(1', '-', 'sigmoid(z))'] | 722,042 |
matsu0228/nlp-jp | group.py | AutoScalingGroup.delete_notification_configuration | delete_notification_configuration | Deletes notifications created by put_notification_configuration. | [
"Deletes",
"notifications",
"created",
"by",
"put_notification_configuration."
] | def delete_notification_configuration(self, topic):
return self.connection.delete_notification_configuration(self, topic) | ['def', 'delete_notification_configuration(self,', 'topic):', 'return', 'self.connection.delete_notification_configuration(self,', 'topic)'] | 784,450 |
eric-erki/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | pytorch_train_timeseries.py | loss_function | loss_function | Calculate the loss as the weighted sum of a Binary Cross-Entropy term and a Total Variation penalty term. | [
"Calculate",
"the",
"loss",
"as",
"the",
"weighted",
"sum",
"of",
"a",
"Binary",
"Cross-Entropy",
"term",
"and",
"a",
"Total",
"Variation",
"penalty",
"term."
] | def loss_function(y_pred, y_true, weights, reg=regularization_parameter):
bce_loss = nn.BCELoss(weight=weights)
if torch.cuda.is_available():
bce_loss = bce_loss.cuda()
if reg > 0:
tv_loss = torch.sum(torch.abs(weights[:, :-1] * y_pred[:, :-1] - weights[:, 1:] * y_pred[:, 1:]))
else:
... | ['def', 'loss_function(y_pred,', 'y_true,', 'weights,', 'reg=regularization_parameter):', 'bce_loss', '=', 'nn.BCELoss(weight=weights)', 'if', 'torch.cuda.is_available():', 'bce_loss', '=', 'bce_loss.cuda()', 'if', 'reg', '>', '0:', 'tv_loss', '=', 'torch.sum(torch.abs(weights[:,', ':-1]', '*', 'y_pred[:,', ':-1]', '-'... | 18,565 |
zehuichen123/AutoAlignV2 | inference.py | inference_segmentor | inference_segmentor | Inference point cloud with the segmentor. | [
"Inference",
"point",
"cloud",
"with",
"the",
"segmentor."
] | def inference_segmentor(model, pcd):
cfg = model.cfg
device = next(model.parameters()).device
test_pipeline = deepcopy(cfg.data.test.pipeline)
test_pipeline = Compose(test_pipeline)
data = dict(pts_filename=pcd, img_fields=[], bbox3d_fields=[], pts_mask_fields=[], pts_seg_fields=[], bbox_fields=[], ... | ['def', 'inference_segmentor(model,', 'pcd):', 'cfg', '=', 'model.cfg', 'device', '=', 'next(model.parameters()).device', 'test_pipeline', '=', 'deepcopy(cfg.data.test.pipeline)', 'test_pipeline', '=', 'Compose(test_pipeline)', 'data', '=', 'dict(pts_filename=pcd,', 'img_fields=[],', 'bbox3d_fields=[],', 'pts_mask_fiel... | 416,466 |
tianjiu233/cv-models | augment.py | RandomFrequencyErasing.get_params | get_params | Get parameters for ``erase`` for a random erasing. | [
"Get",
"parameters",
"for",
"``erase``",
"for",
"a",
"random",
"erasing."
] | def get_params(img: Tensor, scale: Tuple[float, float], ratio: Tuple[float, float]) -> Tuple[int, int, int, int, Tensor]:
(img_h, img_w) = (img.shape[-2], img.shape[-1])
area = img_h * img_w
log_ratio = torch.log(torch.tensor(ratio))
for _ in range(10):
erase_area = area * torch.empty(1).uniform... | ['def', 'get_params(img:', 'Tensor,', 'scale:', 'Tuple[float,', 'float],', 'ratio:', 'Tuple[float,', 'float])', '->', 'Tuple[int,', 'int,', 'int,', 'int,', 'Tensor]:', '(img_h,', 'img_w)', '=', '(img.shape[-2],', 'img.shape[-1])', 'area', '=', 'img_h', '*', 'img_w', 'log_ratio', '=', 'torch.log(torch.tensor(ratio))', '... | 509,314 |
cedkoffeto/artificial-intelligence | __init__.py | VersionControl.update | update | Update an already-existing repo to the given ``rev_options``. | [
"Update",
"an",
"already-existing",
"repo",
"to",
"the",
"given",
"``rev_options``."
] | def update(self, dest, rev_options):
raise NotImplementedError | ['def', 'update(self,', 'dest,', 'rev_options):', 'raise', 'NotImplementedError'] | 90,103 |
Katja-M/Python_NaturalLanguageProcessing | test_tgrep.py | TestSequenceFunctions.test_node_nocase | test_node_nocase | Test selecting nodes using case insensitive node names. | [
"Test",
"selecting",
"nodes",
"using",
"case",
"insensitive",
"node",
"names."
] | def test_node_nocase(self):
tree = ParentedTree.fromstring('(S (n x) (N x))')
self.assertEqual(list(tgrep.tgrep_positions('"N"', [tree])), [[(1,)]])
self.assertEqual(list(tgrep.tgrep_positions('i@"N"', [tree])), [[(0,), (1,)]]) | ['def', 'test_node_nocase(self):', 'tree', '=', "ParentedTree.fromstring('(S", '(n', 'x)', '(N', "x))')", 'self.assertEqual(list(tgrep.tgrep_positions(\'"N"\',', '[tree])),', '[[(1,)]])', 'self.assertEqual(list(tgrep.tgrep_positions(\'i@"N"\',', '[tree])),', '[[(0,),', '(1,)]])'] | 867,088 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | losses.py | add_volume_loss | add_volume_loss | Computes the volume loss of voxel generation model. | [
"Computes",
"the",
"volume",
"loss",
"of",
"voxel",
"generation",
"model."
] | def add_volume_loss(inputs, outputs, num_views, weight_scale):
batch_size = tf.shape(inputs['images_1'])[0]
vol_loss = 0
for k in range(num_views):
vol_loss += tf.nn.l2_loss(inputs['voxels'] - outputs['voxels_%d' % (k + 1)])
vol_loss /= tf.to_float(num_views * batch_size)
slim.summaries.add_... | ['def', 'add_volume_loss(inputs,', 'outputs,', 'num_views,', 'weight_scale):', 'batch_size', '=', "tf.shape(inputs['images_1'])[0]", 'vol_loss', '=', '0', 'for', 'k', 'in', 'range(num_views):', 'vol_loss', '+=', "tf.nn.l2_loss(inputs['voxels']", '-', "outputs['voxels_%d'", '%', '(k', '+', '1)])', 'vol_loss', '/=', 'tf.... | 26,290 |
apeterswu/RL4NMT | common_layers.py | fn_device_dependency | fn_device_dependency | Add control deps for name and device. | [
"Add",
"control",
"deps",
"for",
"name",
"and",
"device."
] | def fn_device_dependency(name, device=''):
key = name + '_' + device
outs = []
def body():
with tf.control_dependencies(fn_device_dependency_dict()[key]):
yield outs
assert outs
deps = outs
if isinstance(outs[0], list) or isinstance(outs[0], tuple):
... | ['def', 'fn_device_dependency(name,', "device=''):", 'key', '=', 'name', '+', "'_'", '+', 'device', 'outs', '=', '[]', 'def', 'body():', 'with', 'tf.control_dependencies(fn_device_dependency_dict()[key]):', 'yield', 'outs', 'assert', 'outs', 'deps', '=', 'outs', 'if', 'isinstance(outs[0],', 'list)', 'or', 'isinstance(o... | 331,074 |
googleapis/python-aiplatform | grpc.py | FeatureRegistryServiceGrpcTransport.grpc_channel | grpc_channel | Return the channel designed to connect to this service. | [
"Return",
"the",
"channel",
"designed",
"to",
"connect",
"to",
"this",
"service."
] | def grpc_channel(self) -> grpc.Channel:
return self._grpc_channel | ['def', 'grpc_channel(self)', '->', 'grpc.Channel:', 'return', 'self._grpc_channel'] | 812,820 |
43Carrig/recurrent_neural_networks_practice | summary_ops_v2.py | image | image | Writes an image summary if possible. | [
"Writes",
"an",
"image",
"summary",
"if",
"possible."
] | def image(name, tensor, bad_color=None, max_images=3, family=None, step=None):
def function(tag, scope):
bad_color_ = constant_op.constant([255, 0, 0, 255], dtype=dtypes.uint8) if bad_color is None else bad_color
return gen_summary_ops.write_image_summary(context.context().summary_writer_resource, ... | ['def', 'image(name,', 'tensor,', 'bad_color=None,', 'max_images=3,', 'family=None,', 'step=None):', 'def', 'function(tag,', 'scope):', 'bad_color_', '=', 'constant_op.constant([255,', '0,', '0,', '255],', 'dtype=dtypes.uint8)', 'if', 'bad_color', 'is', 'None', 'else', 'bad_color', 'return', 'gen_summary_ops.write_imag... | 339,012 |
deeplearningturkiye/reinforcement-learning-project | CartPole.py | make_epsilon_greedy_policy | make_epsilon_greedy_policy | Creates an epsilon-greedy policy based on a given Q-function and epsilon. | [
"Creates",
"an",
"epsilon-greedy",
"policy",
"based",
"on",
"a",
"given",
"Q-function",
"and",
"epsilon."
] | def make_epsilon_greedy_policy(Q, epsilon, nA):
def policy_fn(observation):
A_probs = np.ones(nA, dtype=float) * epsilon / nA
best_action = np.argmax(Q[observation[0][0]][observation[0][1]])
A_probs[best_action] += 1.0 - epsilon
return A_probs
return policy_fn | ['def', 'make_epsilon_greedy_policy(Q,', 'epsilon,', 'nA):', 'def', 'policy_fn(observation):', 'A_probs', '=', 'np.ones(nA,', 'dtype=float)', '*', 'epsilon', '/', 'nA', 'best_action', '=', 'np.argmax(Q[observation[0][0]][observation[0][1]])', 'A_probs[best_action]', '+=', '1.0', '-', 'epsilon', 'return', 'A_probs', 're... | 833,524 |
alibaba-mmai-research/Masked-Action-Recognition | meters.py | ValMeter.update_stats | update_stats | Update the current stats. | [
"Update",
"the",
"current",
"stats."
] | def update_stats(self, top1_err, top5_err, mb_size, **kwargs):
for (k, v) in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
self.opts[k].add_value(v)
self.mb_top1_err.add_value(top1_err)
self.mb_top5_err.add_value(top5_err)
self.num_top1_mis += top1_err * mb_siz... | ['def', 'update_stats(self,', 'top1_err,', 'top5_err,', 'mb_size,', '**kwargs):', 'for', '(k,', 'v)', 'in', 'kwargs.items():', 'if', 'isinstance(v,', 'torch.Tensor):', 'v', '=', 'v.item()', 'self.opts[k].add_value(v)', 'self.mb_top1_err.add_value(top1_err)', 'self.mb_top5_err.add_value(top5_err)', 'self.num_top1_mis', ... | 629,048 |
asyml/texar-pytorch | gpt2_decoder_test.py | GPT2DecoderTest.test_hparams | test_hparams | Tests the priority of the decoder arch parameters. | [
"Tests",
"the",
"priority",
"of",
"the",
"decoder",
"arch",
"parameters."
] | def test_hparams(self):
hparams = {'pretrained_model_name': 'gpt2-medium'}
decoder = GPT2Decoder(pretrained_model_name='gpt2-small', hparams=hparams)
self.assertEqual(decoder.hparams.decoder.num_blocks, 12)
_ = decoder(self.inputs)
hparams = {'pretrained_model_name': 'gpt2-small', 'decoder': {'num_b... | ['def', 'test_hparams(self):', 'hparams', '=', "{'pretrained_model_name':", "'gpt2-medium'}", 'decoder', '=', "GPT2Decoder(pretrained_model_name='gpt2-small',", 'hparams=hparams)', 'self.assertEqual(decoder.hparams.decoder.num_blocks,', '12)', '_', '=', 'decoder(self.inputs)', 'hparams', '=', "{'pretrained_model_name':... | 924,920 |
google/ml-compiler-opt | gtest_executable_utils.py | parse_perf_stat_output | parse_perf_stat_output | Parses raw output from perf stat This function takes in the raw decoded output from perf stat and parses it into a dictionary containing each of the requested performance counters as a key. | [
"Parses",
"raw",
"output",
"from",
"perf",
"stat",
"This",
"function",
"takes",
"in",
"the",
"raw",
"decoded",
"output",
"from",
"perf",
"stat",
"and",
"parses",
"it",
"into",
"a",
"dictionary",
"containing",
"each",
"of",
"the",
"requested",
"performance",
... | def parse_perf_stat_output(perf_stat_output: str, perf_counters: List[str]):
counters_dict = {}
for line in perf_stat_output.split('\n'):
for perf_counter in perf_counters:
if perf_counter in line:
count_string = re.findall('^\\s*\\d*', line)[0].replace(' ', '')
... | ['def', 'parse_perf_stat_output(perf_stat_output:', 'str,', 'perf_counters:', 'List[str]):', 'counters_dict', '=', '{}', 'for', 'line', 'in', "perf_stat_output.split('\\n'):", 'for', 'perf_counter', 'in', 'perf_counters:', 'if', 'perf_counter', 'in', 'line:', 'count_string', '=', "re.findall('^\\\\s*\\\\d*',", "line)[0... | 671,133 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.