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 |
|---|---|---|---|---|---|---|---|---|
facebookresearch/ReAgent | circular_replay_buffer.py | ReplayBuffer.sample_index_batch | sample_index_batch | Returns a batch of valid indices sampled uniformly. | [
"Returns",
"a",
"batch",
"of",
"valid",
"indices",
"sampled",
"uniformly."
] | def sample_index_batch(self, batch_size: int) -> torch.Tensor:
if self._num_valid_indices == 0:
raise RuntimeError(f'Cannot sample {batch_size} since there are no valid indices so far.')
valid_indices = self._is_index_valid.nonzero().squeeze(1)
return valid_indices[torch.randint(valid_indices.shape[... | ['def', 'sample_index_batch(self,', 'batch_size:', 'int)', '->', 'torch.Tensor:', 'if', 'self._num_valid_indices', '==', '0:', 'raise', "RuntimeError(f'Cannot", 'sample', '{batch_size}', 'since', 'there', 'are', 'no', 'valid', 'indices', 'so', "far.')", 'valid_indices', '=', 'self._is_index_valid.nonzero().squeeze(1)',... | 308,856 |
goodfeli/adversarial | sgd.py | OneOverEpoch.current_lr | current_lr | Returns the learning rate currently desired by the decay schedule. | [
"Returns",
"the",
"learning",
"rate",
"currently",
"desired",
"by",
"the",
"decay",
"schedule."
] | def current_lr(self):
if self._count < self.start:
scale = 1
else:
scale = float(self.half_life) / float(self._count - self.start + self.half_life)
lr = self._init_lr * scale
clipped = max(self.min_lr, lr)
return clipped | ['def', 'current_lr(self):', 'if', 'self._count', '<', 'self.start:', 'scale', '=', '1', 'else:', 'scale', '=', 'float(self.half_life)', '/', 'float(self._count', '-', 'self.start', '+', 'self.half_life)', 'lr', '=', 'self._init_lr', '*', 'scale', 'clipped', '=', 'max(self.min_lr,', 'lr)', 'return', 'clipped'] | 397,427 |
facebookresearch/CompilerGym | random_search.py | RandomAgentWorker.should_run_one_episode | should_run_one_episode | Whether to run an episode. | [
"Whether",
"to",
"run",
"an",
"episode."
] | def should_run_one_episode(self) -> bool:
return self.alive or not self.total_episode_count | ['def', 'should_run_one_episode(self)', '->', 'bool:', 'return', 'self.alive', 'or', 'not', 'self.total_episode_count'] | 126,044 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | data_providers.py | singleview_tcn_provider | singleview_tcn_provider | Provides data to train singleview TCNs. | [
"Provides",
"data",
"to",
"train",
"singleview",
"TCNs."
] | def singleview_tcn_provider(file_list, preprocess_fn, num_views, is_training, batch_size, num_parallel_calls=12, sequence_prefetch_size=12, batch_prefetch_size=12):
def _parse_sequence(x):
return parse_sequence_to_svtcn_batch(x, preprocess_fn, is_training, num_views, batch_size)
dataset = get_shuffled_... | ['def', 'singleview_tcn_provider(file_list,', 'preprocess_fn,', 'num_views,', 'is_training,', 'batch_size,', 'num_parallel_calls=12,', 'sequence_prefetch_size=12,', 'batch_prefetch_size=12):', 'def', '_parse_sequence(x):', 'return', 'parse_sequence_to_svtcn_batch(x,', 'preprocess_fn,', 'is_training,', 'num_views,', 'ba... | 29,216 |
RE-OWOD/RE-OWOD | mask_head.py | mask_rcnn_loss | mask_rcnn_loss | Compute the mask prediction loss defined in the Mask R-CNN paper. | [
"Compute",
"the",
"mask",
"prediction",
"loss",
"defined",
"in",
"the",
"Mask",
"R-CNN",
"paper."
] | def mask_rcnn_loss(pred_mask_logits: torch.Tensor, instances: List[Instances], vis_period: int=0):
cls_agnostic_mask = pred_mask_logits.size(1) == 1
total_num_masks = pred_mask_logits.size(0)
mask_side_len = pred_mask_logits.size(2)
assert pred_mask_logits.size(2) == pred_mask_logits.size(3), 'Mask pred... | ['def', 'mask_rcnn_loss(pred_mask_logits:', 'torch.Tensor,', 'instances:', 'List[Instances],', 'vis_period:', 'int=0):', 'cls_agnostic_mask', '=', 'pred_mask_logits.size(1)', '==', '1', 'total_num_masks', '=', 'pred_mask_logits.size(0)', 'mask_side_len', '=', 'pred_mask_logits.size(2)', 'assert', 'pred_mask_logits.size... | 849,041 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_bases.py | FigureManagerBase.key_press | key_press | Implement the default Matplotlib key bindings defined at :ref:`key-event-handling`. | [
"Implement",
"the",
"default",
"Matplotlib",
"key",
"bindings",
"defined",
"at",
":ref:`key-event-handling`."
] | def key_press(self, event):
if rcParams['toolbar'] != 'toolmanager':
key_press_handler(event, self.canvas, self.canvas.toolbar) | ['def', 'key_press(self,', 'event):', 'if', "rcParams['toolbar']", '!=', "'toolmanager':", 'key_press_handler(event,', 'self.canvas,', 'self.canvas.toolbar)'] | 256,731 |
GRAND-Lab/CoLA | utils.py | adj_to_dgl_graph | adj_to_dgl_graph | Convert adjacency matrix to dgl format. | [
"Convert",
"adjacency",
"matrix",
"to",
"dgl",
"format."
] | def adj_to_dgl_graph(adj):
nx_graph = nx.from_scipy_sparse_matrix(adj)
dgl_graph = dgl.DGLGraph(nx_graph)
return dgl_graph | ['def', 'adj_to_dgl_graph(adj):', 'nx_graph', '=', 'nx.from_scipy_sparse_matrix(adj)', 'dgl_graph', '=', 'dgl.DGLGraph(nx_graph)', 'return', 'dgl_graph'] | 124,765 |
aivclab/vision | test_video_reader.py | TestVideoReader.test_read_video_from_file | test_read_video_from_file | Test the case when decoder starts with a video file to decode frames. | [
"Test",
"the",
"case",
"when",
"decoder",
"starts",
"with",
"a",
"video",
"file",
"to",
"decode",
"frames."
] | def test_read_video_from_file(self, test_video, config):
(width, height, min_dimension, max_dimension) = (0, 0, 0, 0)
(video_start_pts, video_end_pts) = (0, -1)
(video_timebase_num, video_timebase_den) = (0, 1)
(samples, channels) = (0, 0)
(audio_start_pts, audio_end_pts) = (0, -1)
(audio_timeba... | ['def', 'test_read_video_from_file(self,', 'test_video,', 'config):', '(width,', 'height,', 'min_dimension,', 'max_dimension)', '=', '(0,', '0,', '0,', '0)', '(video_start_pts,', 'video_end_pts)', '=', '(0,', '-1)', '(video_timebase_num,', 'video_timebase_den)', '=', '(0,', '1)', '(samples,', 'channels)', '=', '(0,', '... | 958,048 |
myothida/Supervised-Machine-Learning | test_axes.py | TestScatter.test_scatter_norm_vminvmax | test_scatter_norm_vminvmax | Parameters vmin, vmax should error if norm is given. | [
"Parameters",
"vmin,",
"vmax",
"should",
"error",
"if",
"norm",
"is",
"given."
] | def test_scatter_norm_vminvmax(self):
x = [1, 2, 3]
ax = plt.axes()
with pytest.raises(ValueError, match='Passing a Normalize instance simultaneously with vmin/vmax is not supported.'):
ax.scatter(x, x, c=x, norm=mcolors.Normalize(-10, 10), vmin=0, vmax=5) | ['def', 'test_scatter_norm_vminvmax(self):', 'x', '=', '[1,', '2,', '3]', 'ax', '=', 'plt.axes()', 'with', 'pytest.raises(ValueError,', "match='Passing", 'a', 'Normalize', 'instance', 'simultaneously', 'with', 'vmin/vmax', 'is', 'not', "supported.'):", 'ax.scatter(x,', 'x,', 'c=x,', 'norm=mcolors.Normalize(-10,', '10),... | 362,792 |
google/deluca | _acrobot.py | bound | bound | Either have m as scalar, so bound(x,m,M) which returns m <= x <= M *OR* have m as length 2 vector, bound(x,m, <IGNORED>) returns m[0] <= x <= m[1]. | [
"Either",
"have",
"m",
"as",
"scalar,",
"so",
"bound(x,m,M)",
"which",
"returns",
"m",
"<=",
"x",
"<=",
"M",
"*OR*",
"have",
"m",
"as",
"length",
"2",
"vector,",
"bound(x,m,",
"<IGNORED>)",
"returns",
"m[0]",
"<=",
"x",
"<=",
"m[1]."
] | def bound(x, m, M=None):
if M is None:
M = m[1]
m = m[0]
return jnp.minimum(jnp.maximum(x, m), M) | ['def', 'bound(x,', 'm,', 'M=None):', 'if', 'M', 'is', 'None:', 'M', '=', 'm[1]', 'm', '=', 'm[0]', 'return', 'jnp.minimum(jnp.maximum(x,', 'm),', 'M)'] | 537,860 |
supervisely/supervisely | project_class_api.py | ProjectClassApi.info_tuple_name | info_tuple_name | NamedTuple name - **ProjectClassInfo**. | [
"NamedTuple",
"name",
"-",
"**ProjectClassInfo**."
] | def info_tuple_name():
return 'ProjectClassInfo' | ['def', 'info_tuple_name():', 'return', "'ProjectClassInfo'"] | 881,235 |
tensorflow/quantum | expectation_test.py | ExpectationTest.test_static_cases | test_static_cases | Run inputs through in complex cases. | [
"Run",
"inputs",
"through",
"in",
"complex",
"cases."
] | def test_static_cases(self):
bit = cirq.GridQubit(0, 0)
symbol = sympy.Symbol('alpha')
test_pstring = cirq.Z(bit)
test_psum = cirq.PauliSum.from_pauli_strings([test_pstring])
symb_circuit = cirq.Circuit(cirq.H(bit) ** symbol)
reg_circuit = cirq.Circuit(cirq.H(bit))
expectation.Expectation()(... | ['def', 'test_static_cases(self):', 'bit', '=', 'cirq.GridQubit(0,', '0)', 'symbol', '=', "sympy.Symbol('alpha')", 'test_pstring', '=', 'cirq.Z(bit)', 'test_psum', '=', 'cirq.PauliSum.from_pauli_strings([test_pstring])', 'symb_circuit', '=', 'cirq.Circuit(cirq.H(bit)', '**', 'symbol)', 'reg_circuit', '=', 'cirq.Circuit... | 835,283 |
SerpentBit/ovl | sorters.py | length_sort | length_sort | Sorts the list of contours from the longest to the shortest based on length of the contour (for open contours) :param contour_list: List of Contours to filter :param descending_sort: true if the sort is from longest to shortest contour, False reverses it :return: the contour list sorted. | [
"Sorts",
"the",
"list",
"of",
"contours",
"from",
"the",
"longest",
"to",
"the",
"shortest",
"based",
"on",
"length",
"of",
"the",
"contour",
"(for",
"open",
"contours)",
":param",
"contour_list:",
"List",
"of",
"Contours",
"to",
"filter",
":param",
"descendin... | def length_sort(contour_list, descending_sort=True):
return sorted(contour_list, key=open_arc_length, reverse=descending_sort) | ['def', 'length_sort(contour_list,', 'descending_sort=True):', 'return', 'sorted(contour_list,', 'key=open_arc_length,', 'reverse=descending_sort)'] | 776,832 |
danijar/mindpark | policy.py | Policy.receive | receive | Receive a reward from the environment. | [
"Receive",
"a",
"reward",
"from",
"the",
"environment."
] | def receive(self, reward, final):
self._assert_state(State.observed)
self._state = State.received
assert reward is not None | ['def', 'receive(self,', 'reward,', 'final):', 'self._assert_state(State.observed)', 'self._state', '=', 'State.received', 'assert', 'reward', 'is', 'not', 'None'] | 286,408 |
clips/pattern | inflect.py | Verbs.find_lexeme | find_lexeme | For a regular verb (base form), returns the forms using a rule-based approach. | [
"For",
"a",
"regular",
"verb",
"(base",
"form),",
"returns",
"the",
"forms",
"using",
"a",
"rule-based",
"approach."
] | def find_lexeme(self, verb):
return [] | ['def', 'find_lexeme(self,', 'verb):', 'return', '[]'] | 765,007 |
ahthie7u/cockpit | loss.py | Loss.compute | compute | Track the loss at the current point. | [
"Track",
"the",
"loss",
"at",
"the",
"current",
"point."
] | def compute(self, global_step, params, batch_loss):
if self.is_active(global_step):
loss = batch_loss.item()
self.output[global_step]['mini_batch_loss'] = loss
if self._verbose:
print(f'[Step {global_step}] Loss: {loss:.4f}') | ['def', 'compute(self,', 'global_step,', 'params,', 'batch_loss):', 'if', 'self.is_active(global_step):', 'loss', '=', 'batch_loss.item()', "self.output[global_step]['mini_batch_loss']", '=', 'loss', 'if', 'self._verbose:', "print(f'[Step", '{global_step}]', 'Loss:', "{loss:.4f}')"] | 493,066 |
megvii-research/TreeEnergyLoss | video_helper.py | VideoReader.get_frame | get_frame | Get frame by index. | [
"Get",
"frame",
"by",
"index."
] | def get_frame(self, frame_id):
if frame_id < 0 or frame_id >= self._frame_cnt:
raise IndexError('"frame_id" must be between 0 and {}'.format(self._frame_cnt - 1))
if frame_id == self._position:
return self.read()
if self._cache:
img = self._cache.get(frame_id)
if img is not N... | ['def', 'get_frame(self,', 'frame_id):', 'if', 'frame_id', '<', '0', 'or', 'frame_id', '>=', 'self._frame_cnt:', 'raise', 'IndexError(\'"frame_id"', 'must', 'be', 'between', '0', 'and', "{}'.format(self._frame_cnt", '-', '1))', 'if', 'frame_id', '==', 'self._position:', 'return', 'self.read()', 'if', 'self._cache:', 'i... | 951,455 |
johschmidt42/PyTorch-Object-Detection-Faster-RCNN-Tutorial | anchor_viewer.py | get_center_bounding_box | get_center_bounding_box | Returns the center points of given bounding boxes. | [
"Returns",
"the",
"center",
"points",
"of",
"given",
"bounding",
"boxes."
] | def get_center_bounding_box(boxes: torch.tensor):
return box_convert(boxes=boxes, in_fmt='xyxy', out_fmt='cxcywh')[:, :2] | ['def', 'get_center_bounding_box(boxes:', 'torch.tensor):', 'return', 'box_convert(boxes=boxes,', "in_fmt='xyxy',", "out_fmt='cxcywh')[:,", ':2]'] | 814,924 |
jbwang1997/CrossKD | loading.py | LoadPanopticAnnotations.transform | transform | Function to load multiple types panoptic annotations. | [
"Function",
"to",
"load",
"multiple",
"types",
"panoptic",
"annotations."
] | def transform(self, results: dict) -> dict:
if self.with_bbox:
self._load_bboxes(results)
if self.with_label:
self._load_labels(results)
if self.with_mask or self.with_seg:
self._load_masks_and_semantic_segs(results)
return results | ['def', 'transform(self,', 'results:', 'dict)', '->', 'dict:', 'if', 'self.with_bbox:', 'self._load_bboxes(results)', 'if', 'self.with_label:', 'self._load_labels(results)', 'if', 'self.with_mask', 'or', 'self.with_seg:', 'self._load_masks_and_semantic_segs(results)', 'return', 'results'] | 490,770 |
matsu0228/nlp-jp | completion_html.py | CompletionHtml.cancel_completion | cancel_completion | Cancel the completion should be called when the completer have to be dismissed This reset internal variable, clearing the temporary buffer of the console where the completion are shown. | [
"Cancel",
"the",
"completion",
"should",
"be",
"called",
"when",
"the",
"completer",
"have",
"to",
"be",
"dismissed",
"This",
"reset",
"internal",
"variable,",
"clearing",
"the",
"temporary",
"buffer",
"of",
"the",
"console",
"where",
"the",
"completion",
"are",... | def cancel_completion(self):
self._consecutive_tab = 0
self._slice_start = 0
self._console_widget._clear_temporary_buffer()
self._index = (0, 0)
if self._sliding_interval:
self._sliding_interval = None | ['def', 'cancel_completion(self):', 'self._consecutive_tab', '=', '0', 'self._slice_start', '=', '0', 'self._console_widget._clear_temporary_buffer()', 'self._index', '=', '(0,', '0)', 'if', 'self._sliding_interval:', 'self._sliding_interval', '=', 'None'] | 805,158 |
commonsense/simplenlp | __init__.py | MeCabNL.extract_phrases | extract_phrases | Given some text, extract phrases of up to 2 content words, and map their normalized form to the complete phrase. | [
"Given",
"some",
"text,",
"extract",
"phrases",
"of",
"up",
"to",
"2",
"content",
"words,",
"and",
"map",
"their",
"normalized",
"form",
"to",
"the",
"complete",
"phrase."
] | def extract_phrases(self, text):
analysis = self.analyze(text)
for pos1 in xrange(len(analysis)):
rec1 = analysis[pos1]
if not self.is_stopword_record(rec1):
yield (self.get_record_root(rec1), rec1[0])
for pos2 in xrange(pos1 + 1, len(analysis)):
rec2 = an... | ['def', 'extract_phrases(self,', 'text):', 'analysis', '=', 'self.analyze(text)', 'for', 'pos1', 'in', 'xrange(len(analysis)):', 'rec1', '=', 'analysis[pos1]', 'if', 'not', 'self.is_stopword_record(rec1):', 'yield', '(self.get_record_root(rec1),', 'rec1[0])', 'for', 'pos2', 'in', 'xrange(pos1', '+', '1,', 'len(analysis... | 883,259 |
zcablii/LSKNet | enn.py | ennTrivialConv | ennTrivialConv | enn convolution with trivial input featurn. | [
"enn",
"convolution",
"with",
"trivial",
"input",
"featurn."
] | def ennTrivialConv(inplanes, outplanes, kernel_size=3, stride=1, padding=0, groups=1, bias=False, dilation=1):
in_type = build_enn_trivial_feature(inplanes)
out_type = build_enn_divide_feature(outplanes)
return enn.R2Conv(in_type, out_type, kernel_size, stride=stride, padding=padding, groups=groups, bias=bi... | ['def', 'ennTrivialConv(inplanes,', 'outplanes,', 'kernel_size=3,', 'stride=1,', 'padding=0,', 'groups=1,', 'bias=False,', 'dilation=1):', 'in_type', '=', 'build_enn_trivial_feature(inplanes)', 'out_type', '=', 'build_enn_divide_feature(outplanes)', 'return', 'enn.R2Conv(in_type,', 'out_type,', 'kernel_size,', 'stride=... | 616,249 |
gunthercox/ChatterBot | atom.py | FeedEntry.to_string | to_string | Convert the feed item into a unicode object. | [
"Convert",
"the",
"feed",
"item",
"into",
"a",
"unicode",
"object."
] | def to_string(self):
return u''.join(self.generate()) | ['def', 'to_string(self):', 'return', "u''.join(self.generate())"] | 483,676 |
weimin17/Object-Detection_HelmetDetection | helper.py | variable_summaries | variable_summaries | Attach a lot of summaries to a Tensor. | [
"Attach",
"a",
"lot",
"of",
"summaries",
"to",
"a",
"Tensor."
] | def variable_summaries(var, name):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean/' + name, mean)
with tf.name_scope('stddev'):
stddev = tf.sqrt(tf.reduce_sum(tf.square(var - mean)))
tf.summary.scalar('sttdev/' + name, stddev)
tf.summary.scalar('max/' + name, tf.reduce_max(var))
tf.s... | ['def', 'variable_summaries(var,', 'name):', 'mean', '=', 'tf.reduce_mean(var)', "tf.summary.scalar('mean/'", '+', 'name,', 'mean)', 'with', "tf.name_scope('stddev'):", 'stddev', '=', 'tf.sqrt(tf.reduce_sum(tf.square(var', '-', 'mean)))', "tf.summary.scalar('sttdev/'", '+', 'name,', 'stddev)', "tf.summary.scalar('max/'... | 758,019 |
Kvatsx/Artificial-Intelligence-Assignments | tree.py | Scope.get_suite | get_suite | Returns the part that is executed by the function. | [
"Returns",
"the",
"part",
"that",
"is",
"executed",
"by",
"the",
"function."
] | def get_suite(self):
return self.children[-1] | ['def', 'get_suite(self):', 'return', 'self.children[-1]'] | 74,476 |
43Carrig/recurrent_neural_networks_practice | rate.py | Rate.call | call | Computes the rate since the last call. | [
"Computes",
"the",
"rate",
"since",
"the",
"last",
"call."
] | def call(self, values, denominator):
if denominator.dtype != dtypes.float64:
denominator = math_ops.cast(denominator, dtypes.float64)
if values.dtype != dtypes.float64:
values = math_ops.cast(values, dtypes.float64)
state_ops.assign(self.numer, math_ops.subtract(values, self.prev_values))
... | ['def', 'call(self,', 'values,', 'denominator):', 'if', 'denominator.dtype', '!=', 'dtypes.float64:', 'denominator', '=', 'math_ops.cast(denominator,', 'dtypes.float64)', 'if', 'values.dtype', '!=', 'dtypes.float64:', 'values', '=', 'math_ops.cast(values,', 'dtypes.float64)', 'state_ops.assign(self.numer,', 'math_ops.s... | 335,069 |
ZumoLabs/zpy | gin.py | parse_gin_config | parse_gin_config | Parse a gin config file by path. | [
"Parse",
"a",
"gin",
"config",
"file",
"by",
"path."
] | def parse_gin_config(gin_config: str=None, gin_config_dir: Union[Path, str]='$CONFIG') -> None:
if gin_config is None:
log.info('No gin file to parse.')
else:
if not gin_config.endswith('.gin'):
gin_config = gin_config + '.gin'
gin_config_filename = Path(gin_config)
g... | ['def', 'parse_gin_config(gin_config:', 'str=None,', 'gin_config_dir:', 'Union[Path,', "str]='$CONFIG')", '->', 'None:', 'if', 'gin_config', 'is', 'None:', "log.info('No", 'gin', 'file', 'to', "parse.')", 'else:', 'if', 'not', "gin_config.endswith('.gin'):", 'gin_config', '=', 'gin_config', '+', "'.gin'", 'gin_config_f... | 972,033 |
matterport/Mask_RCNN | nucleus.py | mask_to_rle | mask_to_rle | Encodes instance masks to submission format. | [
"Encodes",
"instance",
"masks",
"to",
"submission",
"format."
] | def mask_to_rle(image_id, mask, scores):
assert mask.ndim == 3, 'Mask must be [H, W, count]'
if mask.shape[-1] == 0:
return '{},'.format(image_id)
order = np.argsort(scores)[::-1] + 1
mask = np.max(mask * np.reshape(order, [1, 1, -1]), -1)
lines = []
for o in order:
m = np.where(... | ['def', 'mask_to_rle(image_id,', 'mask,', 'scores):', 'assert', 'mask.ndim', '==', '3,', "'Mask", 'must', 'be', '[H,', 'W,', "count]'", 'if', 'mask.shape[-1]', '==', '0:', 'return', "'{},'.format(image_id)", 'order', '=', 'np.argsort(scores)[::-1]', '+', '1', 'mask', '=', 'np.max(mask', '*', 'np.reshape(order,', '[1,',... | 645,400 |
mahossam/OptiGAN | relational_memory.py | RelationalMemory.input_gate | input_gate | Returns the input gate Tensor. | [
"Returns",
"the",
"input",
"gate",
"Tensor."
] | def input_gate(self):
return self._input_gate | ['def', 'input_gate(self):', 'return', 'self._input_gate'] | 776,332 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | PmfProbEqual | PmfProbEqual | Probability that a value from pmf1 equals a value from pmf2. | [
"Probability",
"that",
"a",
"value",
"from",
"pmf1",
"equals",
"a",
"value",
"from",
"pmf2."
] | def PmfProbEqual(pmf1, pmf2):
total = 0.0
for (v1, p1) in pmf1.Items():
for (v2, p2) in pmf2.Items():
if v1 == v2:
total += p1 * p2
return total | ['def', 'PmfProbEqual(pmf1,', 'pmf2):', 'total', '=', '0.0', 'for', '(v1,', 'p1)', 'in', 'pmf1.Items():', 'for', '(v2,', 'p2)', 'in', 'pmf2.Items():', 'if', 'v1', '==', 'v2:', 'total', '+=', 'p1', '*', 'p2', 'return', 'total'] | 13,558 |
suarez12138/AI-Reversi_IMP_TextDichotomy | models.py | Response.raise_for_status | raise_for_status | Raises :class:`HTTPError`, if one occurred. | [
"Raises",
":class:`HTTPError`,",
"if",
"one",
"occurred."
] | def raise_for_status(self):
http_error_msg = ''
if isinstance(self.reason, bytes):
try:
reason = self.reason.decode('utf-8')
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
else:
reason = self.reason
if 400 <= self.status_code < 500:
... | ['def', 'raise_for_status(self):', 'http_error_msg', '=', "''", 'if', 'isinstance(self.reason,', 'bytes):', 'try:', 'reason', '=', "self.reason.decode('utf-8')", 'except', 'UnicodeDecodeError:', 'reason', '=', "self.reason.decode('iso-8859-1')", 'else:', 'reason', '=', 'self.reason', 'if', '400', '<=', 'self.status_cod... | 99,094 |
robustness-gym/robustness-gym | tools.py | persistent_hash | persistent_hash | Compute a hash that persists across multiple Python sessions for a string. | [
"Compute",
"a",
"hash",
"that",
"persists",
"across",
"multiple",
"Python",
"sessions",
"for",
"a",
"string."
] | def persistent_hash(s: str):
return int(hashlib.sha224(s.encode()).hexdigest(), 16) | ['def', 'persistent_hash(s:', 'str):', 'return', 'int(hashlib.sha224(s.encode()).hexdigest(),', '16)'] | 826,301 |
43Carrig/recurrent_neural_networks_practice | boosted_trees_ops.py | TreeEnsemble.deserialize | deserialize | Deserialize the input proto and resets the ensemble from it. | [
"Deserialize",
"the",
"input",
"proto",
"and",
"resets",
"the",
"ensemble",
"from",
"it."
] | def deserialize(self, stamp_token, serialized_proto):
return gen_boosted_trees_ops.boosted_trees_deserialize_ensemble(self.resource_handle, stamp_token, serialized_proto) | ['def', 'deserialize(self,', 'stamp_token,', 'serialized_proto):', 'return', 'gen_boosted_trees_ops.boosted_trees_deserialize_ensemble(self.resource_handle,', 'stamp_token,', 'serialized_proto)'] | 337,091 |
EricSteinberger/PokerRL | EvaluatorMasterBase.py | EvaluatorMasterBase.evaluate | evaluate | Evaluate an agent and send the results as logs to the Chief. | [
"Evaluate",
"an",
"agent",
"and",
"send",
"the",
"results",
"as",
"logs",
"to",
"the",
"Chief."
] | def evaluate(self, iter_nr):
raise NotImplementedError | ['def', 'evaluate(self,', 'iter_nr):', 'raise', 'NotImplementedError'] | 305,697 |
lektor/lektor-archive | packages.py | wipe_package_cache | wipe_package_cache | Wipes the entire package cache. | [
"Wipes",
"the",
"entire",
"package",
"cache."
] | def wipe_package_cache(env):
package_root = env.project.get_package_cache_path()
try:
shutil.rmtree(package_root)
except (OSError, IOError):
pass | ['def', 'wipe_package_cache(env):', 'package_root', '=', 'env.project.get_package_cache_path()', 'try:', 'shutil.rmtree(package_root)', 'except', '(OSError,', 'IOError):', 'pass'] | 216,482 |
google/deepvariant | runtime_by_region_vis.py | summarize_by_task | summarize_by_task | Groups regions to get the total runtime for each task. | [
"Groups",
"regions",
"to",
"get",
"the",
"total",
"runtime",
"for",
"each",
"task."
] | def summarize_by_task(df: pd.DataFrame) -> pd.DataFrame:
by_task = df.groupby(by=['Task']).sum()
return by_task.reset_index() | ['def', 'summarize_by_task(df:', 'pd.DataFrame)', '->', 'pd.DataFrame:', 'by_task', '=', "df.groupby(by=['Task']).sum()", 'return', 'by_task.reset_index()'] | 540,423 |
wenyudu/Natural-Language-Processing-A-Machine-Learning-Perspective | modules.py | DecoderLayer.forward | forward | Follow Figure 1 (right) for connections. | [
"Follow",
"Figure",
"1",
"(right)",
"for",
"connections."
] | def forward(self, x, memory, src_mask, tgt_mask):
residual = x
if self.normalize_before:
x = self.self_attn_layer_norm(x)
x = self.self_attn(x, x, x, tgt_mask)
x = self.dropout_module(x)
x = residual + x
if not self.normalize_before:
x = self.self_attn_layer_norm(x)
residual ... | ['def', 'forward(self,', 'x,', 'memory,', 'src_mask,', 'tgt_mask):', 'residual', '=', 'x', 'if', 'self.normalize_before:', 'x', '=', 'self.self_attn_layer_norm(x)', 'x', '=', 'self.self_attn(x,', 'x,', 'x,', 'tgt_mask)', 'x', '=', 'self.dropout_module(x)', 'x', '=', 'residual', '+', 'x', 'if', 'not', 'self.normalize_be... | 652,227 |
43Carrig/recurrent_neural_networks_practice | debugger_cli_common.py | CommandHistory.add_command | add_command | Add a command to the command history. | [
"Add",
"a",
"command",
"to",
"the",
"command",
"history."
] | def add_command(self, command):
if self._commands and command == self._commands[-1]:
return
if not isinstance(command, six.string_types):
raise TypeError('Attempt to enter non-str entry to command history')
self._commands.append(command)
if len(self._commands) > self._limit:
self... | ['def', 'add_command(self,', 'command):', 'if', 'self._commands', 'and', 'command', '==', 'self._commands[-1]:', 'return', 'if', 'not', 'isinstance(command,', 'six.string_types):', 'raise', "TypeError('Attempt", 'to', 'enter', 'non-str', 'entry', 'to', 'command', "history')", 'self._commands.append(command)', 'if', 'le... | 335,894 |
kornia/kornia | base.py | ImageSequentialBase.get_forward_sequence | get_forward_sequence | Get module sequence by input params. | [
"Get",
"module",
"sequence",
"by",
"input",
"params."
] | def get_forward_sequence(self, params: Optional[List[ParamItem]]=None) -> Iterator[Tuple[str, Module]]:
raise NotImplementedError | ['def', 'get_forward_sequence(self,', 'params:', 'Optional[List[ParamItem]]=None)', '->', 'Iterator[Tuple[str,', 'Module]]:', 'raise', 'NotImplementedError'] | 621,488 |
facebookresearch/dmae_st | lr_util.py | lr_fn_stair | lr_fn_stair | Learning rate with warmup and staircase exponential decay. | [
"Learning",
"rate",
"with",
"warmup",
"and",
"staircase",
"exponential",
"decay."
] | def lr_fn_stair(base_lr: float, decay_steps: int, decay_rate: float) -> float:
def step_fn(step: int):
lr = base_lr
lr = lr * decay_rate ** max(0.0, math.floor(step / decay_steps))
return lr
return step_fn | ['def', 'lr_fn_stair(base_lr:', 'float,', 'decay_steps:', 'int,', 'decay_rate:', 'float)', '->', 'float:', 'def', 'step_fn(step:', 'int):', 'lr', '=', 'base_lr', 'lr', '=', 'lr', '*', 'decay_rate', '**', 'max(0.0,', 'math.floor(step', '/', 'decay_steps))', 'return', 'lr', 'return', 'step_fn'] | 522,051 |
zihuitang/medical_AI_platform | pdb.py | Pdb.do_unalias | do_unalias | unalias name Delete the specified alias. | [
"unalias",
"name",
"Delete",
"the",
"specified",
"alias."
] | def do_unalias(self, arg):
args = arg.split()
if len(args) == 0:
return
if args[0] in self.aliases:
del self.aliases[args[0]] | ['def', 'do_unalias(self,', 'arg):', 'args', '=', 'arg.split()', 'if', 'len(args)', '==', '0:', 'return', 'if', 'args[0]', 'in', 'self.aliases:', 'del', 'self.aliases[args[0]]'] | 281,045 |
zhihou7/HOI-CL-OneStage | fast_rcnn.py | BoxOutputLayers.forward | forward | Returns: Tensor: Nx(K+1) scores for each box Tensor: Nx4 or Nx(Kx4) bounding box regression deltas. | [
"Returns:",
"Tensor:",
"Nx(K+1)",
"scores",
"for",
"each",
"box",
"Tensor:",
"Nx4",
"or",
"Nx(Kx4)",
"bounding",
"box",
"regression",
"deltas."
] | def forward(self, x):
if x.dim() > 2:
x = torch.flatten(x, start_dim=1)
scores = self.cls_score(x)
proposal_deltas = self.bbox_pred(x)
return (scores, proposal_deltas) | ['def', 'forward(self,', 'x):', 'if', 'x.dim()', '>', '2:', 'x', '=', 'torch.flatten(x,', 'start_dim=1)', 'scores', '=', 'self.cls_score(x)', 'proposal_deltas', '=', 'self.bbox_pred(x)', 'return', '(scores,', 'proposal_deltas)'] | 569,213 |
TrellixVulnTeam/Unsupervised_Learning_HFI7 | resample.py | get_resampler_for_grouping | get_resampler_for_grouping | Return our appropriate resampler when grouping as well. | [
"Return",
"our",
"appropriate",
"resampler",
"when",
"grouping",
"as",
"well."
] | def get_resampler_for_grouping(groupby, rule, how=None, fill_method=None, limit=None, kind=None, **kwargs):
kwargs['key'] = kwargs.pop('on', None)
tg = TimeGrouper(freq=rule, **kwargs)
resampler = tg._get_resampler(groupby.obj, kind=kind)
return resampler._get_resampler_for_grouping(groupby=groupby) | ['def', 'get_resampler_for_grouping(groupby,', 'rule,', 'how=None,', 'fill_method=None,', 'limit=None,', 'kind=None,', '**kwargs):', "kwargs['key']", '=', "kwargs.pop('on',", 'None)', 'tg', '=', 'TimeGrouper(freq=rule,', '**kwargs)', 'resampler', '=', 'tg._get_resampler(groupby.obj,', 'kind=kind)', 'return', 'resampler... | 452,664 |
matsu0228/nlp-jp | helpers.py | cache_call_signatures | cache_call_signatures | This function calculates the cache key. | [
"This",
"function",
"calculates",
"the",
"cache",
"key."
] | def cache_call_signatures(evaluator, context, bracket_leaf, code_lines, user_pos):
index = user_pos[0] - 1
before_cursor = code_lines[index][:user_pos[1]]
other_lines = code_lines[bracket_leaf.start_pos[0]:index]
whole = '\n'.join(other_lines + [before_cursor])
before_bracket = re.match('.*\\(', who... | ['def', 'cache_call_signatures(evaluator,', 'context,', 'bracket_leaf,', 'code_lines,', 'user_pos):', 'index', '=', 'user_pos[0]', '-', '1', 'before_cursor', '=', 'code_lines[index][:user_pos[1]]', 'other_lines', '=', 'code_lines[bracket_leaf.start_pos[0]:index]', 'whole', '=', "'\\n'.join(other_lines", '+', '[before_c... | 787,682 |
worldbank/wb-nlp-tools | scripts.py | configure_logger | configure_logger | Configures how the logger output is formatted. | [
"Configures",
"how",
"the",
"logger",
"output",
"is",
"formatted."
] | def configure_logger(log_level):
logging.basicConfig(stream=sys.stdout, level=log_level, datefmt='%Y-%m-%d %H:%M:%S', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') | ['def', 'configure_logger(log_level):', 'logging.basicConfig(stream=sys.stdout,', 'level=log_level,', "datefmt='%Y-%m-%d", "%H:%M:%S',", "format='%(asctime)s", '-', '%(name)s', '-', '%(levelname)s', '-', "%(message)s')"] | 975,968 |
ashwin-phadke/cvplayground | flask_server.py | download_file | download_file | Download video obejct detection processed file. | [
"Download",
"video",
"obejct",
"detection",
"processed",
"file."
] | def download_file(filename):
return render_template('downloadindex.html', value=filename) | ['def', 'download_file(filename):', 'return', "render_template('downloadindex.html',", 'value=filename)'] | 510,486 |
lhotse-speech/lhotse | test_custom_attrs.py | test_cut_load_array_pad | test_cut_load_array_pad | Check that loading a custom Array works after padding. | [
"Check",
"that",
"loading",
"a",
"custom",
"Array",
"works",
"after",
"padding."
] | def test_cut_load_array_pad():
ivector = np.arange(20).astype(np.float32)
with TemporaryDirectory() as d, LilcomFilesWriter(d) as writer:
cut = MonoCut(id='x', start=0, duration=5, channel=0, recording=dummy_recording(1, duration=5.0))
cut.ivector = writer.store_array(key='utt1', value=ivector)
... | ['def', 'test_cut_load_array_pad():', 'ivector', '=', 'np.arange(20).astype(np.float32)', 'with', 'TemporaryDirectory()', 'as', 'd,', 'LilcomFilesWriter(d)', 'as', 'writer:', 'cut', '=', "MonoCut(id='x',", 'start=0,', 'duration=5,', 'channel=0,', 'recording=dummy_recording(1,', 'duration=5.0))', 'cut.ivector', '=', "wr... | 601,051 |
enuguru/artificial_intelligence_and_machine_learning | idsets.py | DocIdSet.invert_update | invert_update | Updates the set in-place to contain numbers in the range ``[0 - size)`` except numbers that are in this set. | [
"Updates",
"the",
"set",
"in-place",
"to",
"contain",
"numbers",
"in",
"the",
"range",
"``[0",
"-",
"size)``",
"except",
"numbers",
"that",
"are",
"in",
"this",
"set."
] | def invert_update(self, size):
for i in xrange(size):
if i in self:
self.discard(i)
else:
self.add(i) | ['def', 'invert_update(self,', 'size):', 'for', 'i', 'in', 'xrange(size):', 'if', 'i', 'in', 'self:', 'self.discard(i)', 'else:', 'self.add(i)'] | 162,035 |
rifqind/Agent-Programs-3KS1 | test_bundler_tools.py | TestBundlerTools.test_glob_subdir | test_glob_subdir | Should expand to all files in the resources/ subfolder. | [
"Should",
"expand",
"to",
"all",
"files",
"in",
"the",
"resources/",
"subfolder."
] | def test_glob_subdir(self):
self.assertIn(os.path.join('resources', 'empty.ipynb'), tools.expand_references(HERE, ['resources/'])) | ['def', 'test_glob_subdir(self):', "self.assertIn(os.path.join('resources',", "'empty.ipynb'),", 'tools.expand_references(HERE,', "['resources/']))"] | 43,182 |
sw-gong/coma | utils.py | TextRCV1.show_doc_per_class | show_doc_per_class | Number of documents per class. | [
"Number",
"of",
"documents",
"per",
"class."
] | def show_doc_per_class(self, print_=False):
docs_per_class = np.array(self.target.astype(np.uint64).sum(axis=0)).squeeze()
print('categories ({} assignments in total)'.format(docs_per_class.sum()))
if print_:
for (i, cat) in enumerate(self.class_names):
print(' {:5s}: {:6d} documents'.f... | ['def', 'show_doc_per_class(self,', 'print_=False):', 'docs_per_class', '=', 'np.array(self.target.astype(np.uint64).sum(axis=0)).squeeze()', "print('categories", '({}', 'assignments', 'in', "total)'.format(docs_per_class.sum()))", 'if', 'print_:', 'for', '(i,', 'cat)', 'in', 'enumerate(self.class_names):', "print('", ... | 467,147 |
wandb/wandb | test_kubernetes.py | pod_factory | pod_factory | Factory for creating pod events. | [
"Factory",
"for",
"creating",
"pod",
"events."
] | def pod_factory(event_type, condition_types, condition_reasons, phase=None):
return MockDict({'type': event_type, 'object': MockDict({'status': MockDict({'phase': phase, 'conditions': [MockDict({'type': condition_type, 'reason': condition_reason}) for (condition_type, condition_reason) in zip(condition_types, condi... | ['def', 'pod_factory(event_type,', 'condition_types,', 'condition_reasons,', 'phase=None):', 'return', "MockDict({'type':", 'event_type,', "'object':", "MockDict({'status':", "MockDict({'phase':", 'phase,', "'conditions':", "[MockDict({'type':", 'condition_type,', "'reason':", 'condition_reason})', 'for', '(condition_t... | 941,295 |
Media-Smart/volkscv | coco2xml.py | instance2xml_base | instance2xml_base | Parse xml base information from annotation. | [
"Parse",
"xml",
"base",
"information",
"from",
"annotation."
] | def instance2xml_base(anno):
E = objectify.ElementMaker(annotate=False)
anno_tree = E.annotation(E.folder('VOC dataset'), E.filename(anno['file_name']), E.source(E.database('COCO format'), E.annotation('COCO format'), E.image('Flickr')), E.size(E.width(anno['width']), E.height(anno['height']), E.depth(3)), E.se... | ['def', 'instance2xml_base(anno):', 'E', '=', 'objectify.ElementMaker(annotate=False)', 'anno_tree', '=', "E.annotation(E.folder('VOC", "dataset'),", "E.filename(anno['file_name']),", "E.source(E.database('COCO", "format'),", "E.annotation('COCO", "format'),", "E.image('Flickr')),", "E.size(E.width(anno['width']),", "E... | 946,476 |
rudranil723/mini-main | list.py | MultipleObjectMixin.get_paginate_orphans | get_paginate_orphans | Return the maximum number of orphans extend the last page by when paginating. | [
"Return",
"the",
"maximum",
"number",
"of",
"orphans",
"extend",
"the",
"last",
"page",
"by",
"when",
"paginating."
] | def get_paginate_orphans(self):
return self.paginate_orphans | ['def', 'get_paginate_orphans(self):', 'return', 'self.paginate_orphans'] | 316,932 |
myothida/Supervised-Machine-Learning | ansi.py | AnsiDecoder.decode | decode | Decode ANSI codes in an iterable of lines. | [
"Decode",
"ANSI",
"codes",
"in",
"an",
"iterable",
"of",
"lines."
] | def decode(self, terminal_text: str) -> Iterable[Text]:
for line in terminal_text.splitlines():
yield self.decode_line(line) | ['def', 'decode(self,', 'terminal_text:', 'str)', '->', 'Iterable[Text]:', 'for', 'line', 'in', 'terminal_text.splitlines():', 'yield', 'self.decode_line(line)'] | 444,988 |
jbwang1997/CrossKD | solo_head.py | SOLOHead.loss_by_feat | loss_by_feat | Calculate the loss based on the features extracted by the mask head. | [
"Calculate",
"the",
"loss",
"based",
"on",
"the",
"features",
"extracted",
"by",
"the",
"mask",
"head."
] | def loss_by_feat(self, mlvl_mask_preds: List[Tensor], mlvl_cls_preds: List[Tensor], batch_gt_instances: InstanceList, batch_img_metas: List[dict], **kwargs) -> dict:
num_levels = self.num_levels
num_imgs = len(batch_img_metas)
featmap_sizes = [featmap.size()[-2:] for featmap in mlvl_mask_preds]
(pos_mas... | ['def', 'loss_by_feat(self,', 'mlvl_mask_preds:', 'List[Tensor],', 'mlvl_cls_preds:', 'List[Tensor],', 'batch_gt_instances:', 'InstanceList,', 'batch_img_metas:', 'List[dict],', '**kwargs)', '->', 'dict:', 'num_levels', '=', 'self.num_levels', 'num_imgs', '=', 'len(batch_img_metas)', 'featmap_sizes', '=', '[featmap.siz... | 491,144 |
43Carrig/recurrent_neural_networks_practice | ops.py | Graph.seed | seed | The graph-level random seed of this graph. | [
"The",
"graph-level",
"random",
"seed",
"of",
"this",
"graph."
] | def seed(self):
return self._seed | ['def', 'seed(self):', 'return', 'self._seed'] | 336,406 |
ArdaGunay99/Key_Detection_Unsupervised_Learning | backend_bases.py | NavigationToolbar2.forward | forward | Move forward in the view lim stack. | [
"Move",
"forward",
"in",
"the",
"view",
"lim",
"stack."
] | def forward(self, *args):
self._nav_stack.forward()
self.set_history_buttons()
self._update_view() | ['def', 'forward(self,', '*args):', 'self._nav_stack.forward()', 'self.set_history_buttons()', 'self._update_view()'] | 256,737 |
wandb/wandb | test_metric_internal.py | test_metric_dot_glob | test_metric_dot_glob | Glob escapes the defined metric name. | [
"Glob",
"escapes",
"the",
"defined",
"metric",
"name."
] | def test_metric_dot_glob(relay_server, user, publish_util, mock_run):
run = mock_run(use_magic_mock=True)
with relay_server() as relay:
history = []
history.append(dict(step=0, data={'this.has.dots': 2}))
history.append(dict(step=1, data={'this.also': 2}))
history.append(dict(ste... | ['def', 'test_metric_dot_glob(relay_server,', 'user,', 'publish_util,', 'mock_run):', 'run', '=', 'mock_run(use_magic_mock=True)', 'with', 'relay_server()', 'as', 'relay:', 'history', '=', '[]', 'history.append(dict(step=0,', "data={'this.has.dots':", '2}))', 'history.append(dict(step=1,', "data={'this.also':", '2}))',... | 941,176 |
math-a3k/django-ai | 0015_sfptenron_sfptyoutube.py | download_and_process_pretrain_data_files | download_and_process_pretrain_data_files | Forward Operation: Downloads if neccesary the sample data and populates Pre-Train Models. | [
"Forward",
"Operation:",
"Downloads",
"if",
"neccesary",
"the",
"sample",
"data",
"and",
"populates",
"Pre-Train",
"Models."
] | def download_and_process_pretrain_data_files(apps, schema_editor):
SFPTEnron = apps.get_model('examples', 'SFPTEnron')
SFPTYoutube = apps.get_model('examples', 'SFPTYoutube')
random.seed(1234567)
if not os.path.exists(ENRON_MAILS_FILE_NAME) or not os.path.exists(YOUTUBE_COMMENTS_FILE_NAME):
if c... | ['def', 'download_and_process_pretrain_data_files(apps,', 'schema_editor):', 'SFPTEnron', '=', "apps.get_model('examples',", "'SFPTEnron')", 'SFPTYoutube', '=', "apps.get_model('examples',", "'SFPTYoutube')", 'random.seed(1234567)', 'if', 'not', 'os.path.exists(ENRON_MAILS_FILE_NAME)', 'or', 'not', 'os.path.exists(YOUT... | 189,531 |
jesolem/PCV | harris.py | match | match | For each corner point descriptor in the first image, select its match to second image using normalized cross correlation. | [
"For",
"each",
"corner",
"point",
"descriptor",
"in",
"the",
"first",
"image,",
"select",
"its",
"match",
"to",
"second",
"image",
"using",
"normalized",
"cross",
"correlation."
] | def match(desc1, desc2, threshold=0.5):
n = len(desc1[0])
d = -ones((len(desc1), len(desc2)))
for i in range(len(desc1)):
for j in range(len(desc2)):
d1 = (desc1[i] - mean(desc1[i])) / std(desc1[i])
d2 = (desc2[j] - mean(desc2[j])) / std(desc2[j])
ncc_value = sum(... | ['def', 'match(desc1,', 'desc2,', 'threshold=0.5):', 'n', '=', 'len(desc1[0])', 'd', '=', '-ones((len(desc1),', 'len(desc2)))', 'for', 'i', 'in', 'range(len(desc1)):', 'for', 'j', 'in', 'range(len(desc2)):', 'd1', '=', '(desc1[i]', '-', 'mean(desc1[i]))', '/', 'std(desc1[i])', 'd2', '=', '(desc2[j]', '-', 'mean(desc2[j... | 765,730 |
v0lta/Complex-gated-recurrent-- | custom_cells.py | hilbert | hilbert | Implements the hilbert transform, a mapping from C to R. | [
"Implements",
"the",
"hilbert",
"transform,",
"a",
"mapping",
"from",
"C",
"to",
"R."
] | def hilbert(xr):
with tf.variable_scope('hilbert_transform'):
n = tf.Tensor.get_shape(xr).as_list()[0]
x = tf.transpose(tf.fft(tf.transpose(xr)))
h = np.zeros([n])
if n > 0 and 2 * np.fix(n / 2) == n:
h[0:int(n / 2 + 1)] = 1
h[1:int(n / 2)] = 2
elif n ... | ['def', 'hilbert(xr):', 'with', "tf.variable_scope('hilbert_transform'):", 'n', '=', 'tf.Tensor.get_shape(xr).as_list()[0]', 'x', '=', 'tf.transpose(tf.fft(tf.transpose(xr)))', 'h', '=', 'np.zeros([n])', 'if', 'n', '>', '0', 'and', '2', '*', 'np.fix(n', '/', '2)', '==', 'n:', 'h[0:int(n', '/', '2', '+', '1)]', '=', '1'... | 135,951 |
MycroftAI/mycroft-core | test_download.py | TestDownload.test_download_with_header | test_download_with_header | Test download with specific header. | [
"Test",
"download",
"with",
"specific",
"header."
] | def test_download_with_header(self, mock_os, mock_subprocess):
mock_subprocess.call.return_value = 0
test_hdr = 'TEST_HEADER'
downloader = download(url=TEST_URL, dest=TEST_DEST, header=test_hdr)
downloader.join()
self.assertTrue(downloader.done)
mock_subprocess.call.assert_called_once_with(['wge... | ['def', 'test_download_with_header(self,', 'mock_os,', 'mock_subprocess):', 'mock_subprocess.call.return_value', '=', '0', 'test_hdr', '=', "'TEST_HEADER'", 'downloader', '=', 'download(url=TEST_URL,', 'dest=TEST_DEST,', 'header=test_hdr)', 'downloader.join()', 'self.assertTrue(downloader.done)', "mock_subprocess.call.... | 291,000 |
hamza-murad/AALU | natural_language_understanding_v1.py | SemanticRolesResult.from_dict | from_dict | Initialize a SemanticRolesResult object from a json dictionary. | [
"Initialize",
"a",
"SemanticRolesResult",
"object",
"from",
"a",
"json",
"dictionary."
] | def from_dict(cls, _dict: Dict) -> 'SemanticRolesResult':
args = {}
valid_keys = ['sentence', 'subject', 'action', 'object']
bad_keys = set(_dict.keys()) - set(valid_keys)
if bad_keys:
raise ValueError('Unrecognized keys detected in dictionary for class SemanticRolesResult: ' + ', '.join(bad_key... | ['def', 'from_dict(cls,', '_dict:', 'Dict)', '->', "'SemanticRolesResult':", 'args', '=', '{}', 'valid_keys', '=', "['sentence',", "'subject',", "'action',", "'object']", 'bad_keys', '=', 'set(_dict.keys())', '-', 'set(valid_keys)', 'if', 'bad_keys:', 'raise', "ValueError('Unrecognized", 'keys', 'detected', 'in', 'dict... | 5,963 |
dlshriver/dnnv | test_mappings_s_shaped.py | TestMappingSShaped.test_tanh_propagate_float | test_tanh_propagate_float | Test the propagate() method with floats. | [
"Test",
"the",
"propagate()",
"method",
"with",
"floats."
] | def test_tanh_propagate_float(self):
(x0, x1) = (2.5, -2.5)
self.assertAlmostEqual(self.tanh.propagate(x0), np.tanh(x0))
self.assertAlmostEqual(self.tanh.propagate(x1), np.tanh(x1)) | ['def', 'test_tanh_propagate_float(self):', '(x0,', 'x1)', '=', '(2.5,', '-2.5)', 'self.assertAlmostEqual(self.tanh.propagate(x0),', 'np.tanh(x0))', 'self.assertAlmostEqual(self.tanh.propagate(x1),', 'np.tanh(x1))'] | 522,691 |
rifqind/Agent-Programs-3KS1 | tree.py | Scope.iter_imports | iter_imports | Returns a generator of `import_name` and `import_from` nodes. | [
"Returns",
"a",
"generator",
"of",
"`import_name`",
"and",
"`import_from`",
"nodes."
] | def iter_imports(self):
return self._search_in_scope('import_name', 'import_from') | ['def', 'iter_imports(self):', 'return', "self._search_in_scope('import_name',", "'import_from')"] | 44,081 |
chribsen/simple-machine-learning-examples | gradient_boosting.py | MultinomialDeviance.negative_gradient | negative_gradient | Compute negative gradient for the ``k``-th class. | [
"Compute",
"negative",
"gradient",
"for",
"the",
"``k``-th",
"class."
] | def negative_gradient(self, y, pred, k=0, **kwargs):
return y - np.nan_to_num(np.exp(pred[:, k] - logsumexp(pred, axis=1))) | ['def', 'negative_gradient(self,', 'y,', 'pred,', 'k=0,', '**kwargs):', 'return', 'y', '-', 'np.nan_to_num(np.exp(pred[:,', 'k]', '-', 'logsumexp(pred,', 'axis=1)))'] | 939,165 |
omarmhaimdat/twitter_nlp_native_swift | quoprimime.py | _body_accumulator.write_wrapped | write_wrapped | Add a soft line break if needed, then write s. | [
"Add",
"a",
"soft",
"line",
"break",
"if",
"needed,",
"then",
"write",
"s."
] | def write_wrapped(self, s, extra_room=0):
if self.room < len(s) + extra_room:
self.write_soft_break()
self.write_str(s) | ['def', 'write_wrapped(self,', 's,', 'extra_room=0):', 'if', 'self.room', '<', 'len(s)', '+', 'extra_room:', 'self.write_soft_break()', 'self.write_str(s)'] | 953,357 |
lhotse-speech/lhotse | torchaudio.py | Volume.reverse_timestamps | reverse_timestamps | This method just returnes the original offset and duration as volume perturbation doesn't change any these audio properies. | [
"This",
"method",
"just",
"returnes",
"the",
"original",
"offset",
"and",
"duration",
"as",
"volume",
"perturbation",
"doesn't",
"change",
"any",
"these",
"audio",
"properies."
] | def reverse_timestamps(self, offset: Seconds, duration: Optional[Seconds], sampling_rate: Optional[int]) -> Tuple[Seconds, Optional[Seconds]]:
return (offset, duration) | ['def', 'reverse_timestamps(self,', 'offset:', 'Seconds,', 'duration:', 'Optional[Seconds],', 'sampling_rate:', 'Optional[int])', '->', 'Tuple[Seconds,', 'Optional[Seconds]]:', 'return', '(offset,', 'duration)'] | 600,525 |
thaines/helit | prog_bar.py | ProgBar.callback | callback | Hand this into the callback of methods to get a progress bar - it works by users repeatedly calling it to indicate how many units of work they have done (nDone) out of the total number of units required (nToDo). | [
"Hand",
"this",
"into",
"the",
"callback",
"of",
"methods",
"to",
"get",
"a",
"progress",
"bar",
"-",
"it",
"works",
"by",
"users",
"repeatedly",
"calling",
"it",
"to",
"indicate",
"how",
"many",
"units",
"of",
"work",
"they",
"have",
"done",
"(nDone)",
... | def callback(self, nDone, nToDo):
if self.onCallback:
self.onCallback()
n = int(float(self.width) * float(nDone) / float(nToDo))
n = min((n, self.width))
if n > self.fill:
self.__show(n) | ['def', 'callback(self,', 'nDone,', 'nToDo):', 'if', 'self.onCallback:', 'self.onCallback()', 'n', '=', 'int(float(self.width)', '*', 'float(nDone)', '/', 'float(nToDo))', 'n', '=', 'min((n,', 'self.width))', 'if', 'n', '>', 'self.fill:', 'self.__show(n)'] | 592,664 |
intelligent-environments-lab/CityLearn | energy_model.py | Battery.capacity_history | capacity_history | Time series of maximum amount of energy the storage device can store in [kWh]. | [
"Time",
"series",
"of",
"maximum",
"amount",
"of",
"energy",
"the",
"storage",
"device",
"can",
"store",
"in",
"[kWh]."
] | def capacity_history(self) -> List[float]:
return self._capacity_history | ['def', 'capacity_history(self)', '->', 'List[float]:', 'return', 'self._capacity_history'] | 105,759 |
lingorX/HieraSeg | test_config.py | test_config_build_segmentor | test_config_build_segmentor | Test that all segmentation models defined in the configs can be initialized. | [
"Test",
"that",
"all",
"segmentation",
"models",
"defined",
"in",
"the",
"configs",
"can",
"be",
"initialized."
] | def test_config_build_segmentor():
config_dpath = _get_config_directory()
print('Found config_dpath = {!r}'.format(config_dpath))
config_fpaths = []
for sub_folder in os.listdir(config_dpath):
if isdir(sub_folder):
config_fpaths.append(list(glob.glob(join(config_dpath, sub_folder, '*... | ['def', 'test_config_build_segmentor():', 'config_dpath', '=', '_get_config_directory()', "print('Found", 'config_dpath', '=', "{!r}'.format(config_dpath))", 'config_fpaths', '=', '[]', 'for', 'sub_folder', 'in', 'os.listdir(config_dpath):', 'if', 'isdir(sub_folder):', 'config_fpaths.append(list(glob.glob(join(config_d... | 593,194 |
alex-petrenko/sample-factory | arguments.py | maybe_load_from_checkpoint | maybe_load_from_checkpoint | Will attempt to load experiment configuration from the checkpoint while preserving any new overrides passed from command line. | [
"Will",
"attempt",
"to",
"load",
"experiment",
"configuration",
"from",
"the",
"checkpoint",
"while",
"preserving",
"any",
"new",
"overrides",
"passed",
"from",
"command",
"line."
] | def maybe_load_from_checkpoint(cfg: Config) -> AttrDict:
filename = cfg_file(cfg)
if not os.path.isfile(filename):
log.warning('Saved parameter configuration for experiment %s not found!', cfg.experiment)
log.warning('Starting experiment from scratch!')
return AttrDict(vars(cfg))
ret... | ['def', 'maybe_load_from_checkpoint(cfg:', 'Config)', '->', 'AttrDict:', 'filename', '=', 'cfg_file(cfg)', 'if', 'not', 'os.path.isfile(filename):', "log.warning('Saved", 'parameter', 'configuration', 'for', 'experiment', '%s', 'not', "found!',", 'cfg.experiment)', "log.warning('Starting", 'experiment', 'from', "scratc... | 329,152 |
rifqind/Agent-Programs-3KS1 | jstest.py | prepare_controllers | prepare_controllers | Returns two lists of TestController instances, those to run, and those not to run. | [
"Returns",
"two",
"lists",
"of",
"TestController",
"instances,",
"those",
"to",
"run,",
"and",
"those",
"not",
"to",
"run."
] | def prepare_controllers(options):
testgroups = options.testgroups
if not testgroups:
testgroups = all_js_groups()
engine = 'slimerjs' if options.slimerjs else 'phantomjs'
c_js = [JSController(name, xunit=options.xunit, engine=engine, url=options.url) for name in testgroups]
controllers = c_j... | ['def', 'prepare_controllers(options):', 'testgroups', '=', 'options.testgroups', 'if', 'not', 'testgroups:', 'testgroups', '=', 'all_js_groups()', 'engine', '=', "'slimerjs'", 'if', 'options.slimerjs', 'else', "'phantomjs'", 'c_js', '=', '[JSController(name,', 'xunit=options.xunit,', 'engine=engine,', 'url=options.url... | 43,019 |
kornia/kornia | depth.py | DepthWarper.forward | forward | Warp a tensor from destination frame to reference given the depth in the reference frame. | [
"Warp",
"a",
"tensor",
"from",
"destination",
"frame",
"to",
"reference",
"given",
"the",
"depth",
"in",
"the",
"reference",
"frame."
] | def forward(self, depth_src: Tensor, patch_dst: Tensor) -> Tensor:
return kornia_ops.map_coordinates(patch_dst, self.warp_grid(depth_src), mode=self.mode, padding_mode=self.padding_mode, align_corners=self.align_corners) | ['def', 'forward(self,', 'depth_src:', 'Tensor,', 'patch_dst:', 'Tensor)', '->', 'Tensor:', 'return', 'kornia_ops.map_coordinates(patch_dst,', 'self.warp_grid(depth_src),', 'mode=self.mode,', 'padding_mode=self.padding_mode,', 'align_corners=self.align_corners)'] | 621,906 |
Farama-Foundation/Gymnasium | vector_list_info.py | VectorListInfo.step | step | Steps through the environment, convert dict info to list. | [
"Steps",
"through",
"the",
"environment,",
"convert",
"dict",
"info",
"to",
"list."
] | def step(self, action):
(observation, reward, terminated, truncated, infos) = self.env.step(action)
list_info = self._convert_info_to_list(infos)
return (observation, reward, terminated, truncated, list_info) | ['def', 'step(self,', 'action):', '(observation,', 'reward,', 'terminated,', 'truncated,', 'infos)', '=', 'self.env.step(action)', 'list_info', '=', 'self._convert_info_to_list(infos)', 'return', '(observation,', 'reward,', 'terminated,', 'truncated,', 'list_info)'] | 573,421 |
victordibia/data2vis | utils.py | create_temporary_vocab_file | create_temporary_vocab_file | Creates a temporary vocabulary file. | [
"Creates",
"a",
"temporary",
"vocabulary",
"file."
] | def create_temporary_vocab_file(words, counts=None):
vocab_file = tempfile.NamedTemporaryFile()
if counts is None:
for token in words:
vocab_file.write((token + '\n').encode('utf-8'))
else:
for (token, count) in zip(words, counts):
vocab_file.write('{}\t{}\n'.format(t... | ['def', 'create_temporary_vocab_file(words,', 'counts=None):', 'vocab_file', '=', 'tempfile.NamedTemporaryFile()', 'if', 'counts', 'is', 'None:', 'for', 'token', 'in', 'words:', 'vocab_file.write((token', '+', "'\\n').encode('utf-8'))", 'else:', 'for', '(token,', 'count)', 'in', 'zip(words,', 'counts):', "vocab_file.wr... | 126,882 |
lorenlugosch/end-to-end-SLU | models.py | FinalPool.forward | forward | input : Tensor of shape (batch size, T, Cin) Outputs a Tensor of shape (batch size, Cin). | [
"input",
":",
"Tensor",
"of",
"shape",
"(batch",
"size,",
"T,",
"Cin)",
"Outputs",
"a",
"Tensor",
"of",
"shape",
"(batch",
"size,",
"Cin)."
] | def forward(self, input):
return input.max(dim=1)[0] | ['def', 'forward(self,', 'input):', 'return', 'input.max(dim=1)[0]'] | 561,757 |
bhateharsh/computer_vision | cpp_lint.py | _CppLintState.ResetErrorCounts | ResetErrorCounts | Sets the module's error statistic back to zero. | [
"Sets",
"the",
"module's",
"error",
"statistic",
"back",
"to",
"zero."
] | def ResetErrorCounts(self):
self.error_count = 0
self.errors_by_category = {} | ['def', 'ResetErrorCounts(self):', 'self.error_count', '=', '0', 'self.errors_by_category', '=', '{}'] | 473,363 |
salesforce/CodeRL | check_repo.py | check_all_objects_are_documented | check_all_objects_are_documented | Check all models are properly documented. | [
"Check",
"all",
"models",
"are",
"properly",
"documented."
] | def check_all_objects_are_documented():
documented_objs = find_all_documented_objects()
modules = transformers._modules
objects = [c for c in dir(transformers) if c not in modules and (not c.startswith('_'))]
undocumented_objs = [c for c in objects if c not in documented_objs and (not ignore_undocumente... | ['def', 'check_all_objects_are_documented():', 'documented_objs', '=', 'find_all_documented_objects()', 'modules', '=', 'transformers._modules', 'objects', '=', '[c', 'for', 'c', 'in', 'dir(transformers)', 'if', 'c', 'not', 'in', 'modules', 'and', '(not', "c.startswith('_'))]", 'undocumented_objs', '=', '[c', 'for', 'c... | 495,754 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | thinkstats2.py | Beta.Random | Random | Generates a random variate from this distribution. | [
"Generates",
"a",
"random",
"variate",
"from",
"this",
"distribution."
] | def Random(self):
return random.betavariate(self.alpha, self.beta) | ['def', 'Random(self):', 'return', 'random.betavariate(self.alpha,', 'self.beta)'] | 13,335 |
XuyangSHEN/Non-binary-deep-transfer-learning-for-image-classification | resnet.py | tv_resnet34 | tv_resnet34 | Constructs a ResNet-34 model with original Torchvision weights. | [
"Constructs",
"a",
"ResNet-34",
"model",
"with",
"original",
"Torchvision",
"weights."
] | def tv_resnet34(pretrained=False, **kwargs):
model_args = dict(block=BasicBlock, layers=[3, 4, 6, 3], **kwargs)
return _create_resnet('tv_resnet34', pretrained, **model_args) | ['def', 'tv_resnet34(pretrained=False,', '**kwargs):', 'model_args', '=', 'dict(block=BasicBlock,', 'layers=[3,', '4,', '6,', '3],', '**kwargs)', 'return', "_create_resnet('tv_resnet34',", 'pretrained,', '**model_args)'] | 729,462 |
dataiteam/Reinforcement-Learning | ae_random.py | autoencoder.predict | predict | Predicts the next state based on the current action. | [
"Predicts",
"the",
"next",
"state",
"based",
"on",
"the",
"current",
"action."
] | def predict(self, sess, s, a):
return sess.run(self.pred_frame, {self.state: s, self.action: a}) | ['def', 'predict(self,', 'sess,', 's,', 'a):', 'return', 'sess.run(self.pred_frame,', '{self.state:', 's,', 'self.action:', 'a})'] | 341,006 |
triaquae/triaquae | _winapi.py | MemoryMap.read | read | Read n bytes from mapped view. | [
"Read",
"n",
"bytes",
"from",
"mapped",
"view."
] | def read(self, n):
out = ctypes.create_string_buffer(n)
ctypes.windll.msvcrt.memcpy(out, self.view + self.pos, n)
self.pos += n
return out.raw | ['def', 'read(self,', 'n):', 'out', '=', 'ctypes.create_string_buffer(n)', 'ctypes.windll.msvcrt.memcpy(out,', 'self.view', '+', 'self.pos,', 'n)', 'self.pos', '+=', 'n', 'return', 'out.raw'] | 356,485 |
huma-teknofest/Keras-RetinaNet-for-Teknofest-2019 | coco.py | CocoGenerator.coco_label_to_name | coco_label_to_name | Map COCO label to name. | [
"Map",
"COCO",
"label",
"to",
"name."
] | def coco_label_to_name(self, coco_label):
return self.label_to_name(self.coco_label_to_label(coco_label)) | ['def', 'coco_label_to_name(self,', 'coco_label):', 'return', 'self.label_to_name(self.coco_label_to_label(coco_label))'] | 247,971 |
Eric3911/OpenAGI | config.py | get_pipeline_config | get_pipeline_config | Parses pipeline engine configuration. | [
"Parses",
"pipeline",
"engine",
"configuration."
] | def get_pipeline_config(param_dict):
default_pipeline = {'stages': 'auto', 'partition': 'best', 'seed_layers': False, 'activation_checkpoint_interval': 0}
config = default_pipeline
for (key, val) in param_dict.get('pipeline', {}).items():
config[key] = val
return config | ['def', 'get_pipeline_config(param_dict):', 'default_pipeline', '=', "{'stages':", "'auto',", "'partition':", "'best',", "'seed_layers':", 'False,', "'activation_checkpoint_interval':", '0}', 'config', '=', 'default_pipeline', 'for', '(key,', 'val)', 'in', "param_dict.get('pipeline',", '{}).items():', 'config[key]', '=... | 252,098 |
kiretd/Unsupervised-MIseg | kidney_workflow.py | plot_mask_overlay_ISIC | plot_mask_overlay_ISIC | Plots mask overlays for ISIC 2018 test images. | [
"Plots",
"mask",
"overlays",
"for",
"ISIC",
"2018",
"test",
"images."
] | def plot_mask_overlay_ISIC(im_num='0012611'):
fpath = 'Datasets/ISIC 2018/'
image_path = fpath + '50_test_images/ISIC_' + im_num + '.jpg'
mask_paths = [fpath + '50_predictions_using_fake_images/ISIC_' + im_num + '_segmentation.png', fpath + '50_predictions_using_real_images/ISIC_' + im_num + '_segmentation.... | ['def', "plot_mask_overlay_ISIC(im_num='0012611'):", 'fpath', '=', "'Datasets/ISIC", "2018/'", 'image_path', '=', 'fpath', '+', "'50_test_images/ISIC_'", '+', 'im_num', '+', "'.jpg'", 'mask_paths', '=', '[fpath', '+', "'50_predictions_using_fake_images/ISIC_'", '+', 'im_num', '+', "'_segmentation.png',", 'fpath', '+', ... | 353,650 |
PaccMann/fdsa | shapes_data.py | Shapes.datapoints_circle | datapoints_circle | Generates a set of datapoints sampled from the circumference of a circle. | [
"Generates",
"a",
"set",
"of",
"datapoints",
"sampled",
"from",
"the",
"circumference",
"of",
"a",
"circle."
] | def datapoints_circle(self, set_length: int, sample_id: int, min_radius: int=100, use: str=None):
x = np.random.randint(self.min_boundary, self.max_boundary)
y = np.random.randint(self.min_boundary, self.max_boundary)
radius = self.get_max_radius(x, y, min_radius)
(rr, cc) = draw.circle_perimeter(x, y, ... | ['def', 'datapoints_circle(self,', 'set_length:', 'int,', 'sample_id:', 'int,', 'min_radius:', 'int=100,', 'use:', 'str=None):', 'x', '=', 'np.random.randint(self.min_boundary,', 'self.max_boundary)', 'y', '=', 'np.random.randint(self.min_boundary,', 'self.max_boundary)', 'radius', '=', 'self.get_max_radius(x,', 'y,', ... | 560,848 |
cleanlab/cleanlab | util.py | extract_indices_tf | extract_indices_tf | Extracts subset of tensorflow dataset corresponding to examples at particular indices. | [
"Extracts",
"subset",
"of",
"tensorflow",
"dataset",
"corresponding",
"to",
"examples",
"at",
"particular",
"indices."
] | def extract_indices_tf(X, idx, allow_shuffle) -> DatasetLike:
import tensorflow
idx = np.asarray(idx)
idx = np.int64(idx)
og_batch_size = None
if hasattr(X, '_batch_size'):
og_batch_size = int(X._batch_size)
X = X.unbatch()
(unshuffled_X, buffer_size) = unshuffle_tensorflow_datas... | ['def', 'extract_indices_tf(X,', 'idx,', 'allow_shuffle)', '->', 'DatasetLike:', 'import', 'tensorflow', 'idx', '=', 'np.asarray(idx)', 'idx', '=', 'np.int64(idx)', 'og_batch_size', '=', 'None', 'if', 'hasattr(X,', "'_batch_size'):", 'og_batch_size', '=', 'int(X._batch_size)', 'X', '=', 'X.unbatch()', '(unshuffled_X,',... | 488,045 |
ifwe/digsby | toast.py | Popup.start_long_fade_timer | start_long_fade_timer | Starts the timer that fades away the popup even when the mouse is over it. | [
"Starts",
"the",
"timer",
"that",
"fades",
"away",
"the",
"popup",
"even",
"when",
"the",
"mouse",
"is",
"over",
"it."
] | def start_long_fade_timer(self):
self.long_fade_timer.Start(LONG_FADE_TIME_MS, True) | ['def', 'start_long_fade_timer(self):', 'self.long_fade_timer.Start(LONG_FADE_TIME_MS,', 'True)'] | 185,545 |
open-mmlab/mmsegmentation | transforms.py | CLAHE.transform | transform | Call function to Use CLAHE method process images. | [
"Call",
"function",
"to",
"Use",
"CLAHE",
"method",
"process",
"images."
] | def transform(self, results: dict) -> dict:
for i in range(results['img'].shape[2]):
results['img'][:, :, i] = mmcv.clahe(np.array(results['img'][:, :, i], dtype=np.uint8), self.clip_limit, self.tile_grid_size)
return results | ['def', 'transform(self,', 'results:', 'dict)', '->', 'dict:', 'for', 'i', 'in', "range(results['img'].shape[2]):", "results['img'][:,", ':,', 'i]', '=', "mmcv.clahe(np.array(results['img'][:,", ':,', 'i],', 'dtype=np.uint8),', 'self.clip_limit,', 'self.tile_grid_size)', 'return', 'results'] | 625,322 |
weimin17/Object-Detection_HelmetDetection | mst_units.py | MstSolverNetwork.create | create | Forwards the lengths and scores. | [
"Forwards",
"the",
"lengths",
"and",
"scores."
] | def create(self, fixed_embeddings, linked_embeddings, context_tensor_arrays, attention_tensor, during_training, stride=None):
check.NotNone(stride, 'MstSolverNetwork requires stride')
lengths = network_units.lookup_named_tensor('lengths', linked_embeddings)
lengths_b = tf.to_int32(tf.squeeze(lengths.tensor,... | ['def', 'create(self,', 'fixed_embeddings,', 'linked_embeddings,', 'context_tensor_arrays,', 'attention_tensor,', 'during_training,', 'stride=None):', 'check.NotNone(stride,', "'MstSolverNetwork", 'requires', "stride')", 'lengths', '=', "network_units.lookup_named_tensor('lengths',", 'linked_embeddings)', 'lengths_b', ... | 760,209 |
aeon-toolkit/aeon | test_all_estimators.py | BaseFixtureGenerator.estimator_instance | estimator_instance | estimator_instance fixture definition for indirect use. | [
"estimator_instance",
"fixture",
"definition",
"for",
"indirect",
"use."
] | def estimator_instance(self, request):
return request.param.clone() | ['def', 'estimator_instance(self,', 'request):', 'return', 'request.param.clone()'] | 399,845 |
microsoft/UniSpeech | trainer.py | Trainer.should_save_checkpoint_on_current_rank | should_save_checkpoint_on_current_rank | Indicates whether to save checkpoints on the current DDP rank. | [
"Indicates",
"whether",
"to",
"save",
"checkpoints",
"on",
"the",
"current",
"DDP",
"rank."
] | def should_save_checkpoint_on_current_rank(self) -> bool:
if self.cfg.distributed_training.ddp_backend == 'fully_sharded' and self.cfg.distributed_training.use_sharded_state or getattr(self.cfg.model, 'base_layers', 0) > 0:
return True
else:
return self.is_data_parallel_master | ['def', 'should_save_checkpoint_on_current_rank(self)', '->', 'bool:', 'if', 'self.cfg.distributed_training.ddp_backend', '==', "'fully_sharded'", 'and', 'self.cfg.distributed_training.use_sharded_state', 'or', 'getattr(self.cfg.model,', "'base_layers',", '0)', '>', '0:', 'return', 'True', 'else:', 'return', 'self.is_d... | 378,174 |
rishab-sharma/object_detection | config_util.py | update_input_reader_config | update_input_reader_config | Updates specified input reader config field. | [
"Updates",
"specified",
"input",
"reader",
"config",
"field."
] | def update_input_reader_config(configs, key_name=None, input_name=None, field_name=None, value=None, path_updater=_update_tf_record_input_path):
if isinstance(configs[key_name], input_reader_pb2.InputReader):
target_input_config = configs[key_name]
if field_name == 'input_path':
path_upd... | ['def', 'update_input_reader_config(configs,', 'key_name=None,', 'input_name=None,', 'field_name=None,', 'value=None,', 'path_updater=_update_tf_record_input_path):', 'if', 'isinstance(configs[key_name],', 'input_reader_pb2.InputReader):', 'target_input_config', '=', 'configs[key_name]', 'if', 'field_name', '==', "'inp... | 792,703 |
usmancheema89/computer_vision | config_util_test.py | ConfigUtilTest.testEvalShuffle | testEvalShuffle | Tests that `eval_shuffle` keyword arguments are applied correctly. | [
"Tests",
"that",
"`eval_shuffle`",
"keyword",
"arguments",
"are",
"applied",
"correctly."
] | def testEvalShuffle(self):
original_shuffle = True
desired_shuffle = False
pipeline_config_path = os.path.join(self.get_temp_dir(), 'pipeline.config')
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
pipeline_config.eval_input_reader.add().shuffle = original_shuffle
_write_config(pipelin... | ['def', 'testEvalShuffle(self):', 'original_shuffle', '=', 'True', 'desired_shuffle', '=', 'False', 'pipeline_config_path', '=', 'os.path.join(self.get_temp_dir(),', "'pipeline.config')", 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'pipeline_config.eval_input_reader.add().shuffle', '=', 'original_... | 512,327 |
greydanus/mr_london | flipflop.py | Connection.run | run | Begin processing data from the socket. | [
"Begin",
"processing",
"data",
"from",
"the",
"socket."
] | def run(self):
self._keep_going = True
while self._keep_going:
try:
self.process_input()
except (EOFError, KeyboardInterrupt):
break
except (select.error, socket.error) as exception:
if exception.args[0] == errno.EBADF:
break
... | ['def', 'run(self):', 'self._keep_going', '=', 'True', 'while', 'self._keep_going:', 'try:', 'self.process_input()', 'except', '(EOFError,', 'KeyboardInterrupt):', 'break', 'except', '(select.error,', 'socket.error)', 'as', 'exception:', 'if', 'exception.args[0]', '==', 'errno.EBADF:', 'break', 'raise', 'self._cleanup_... | 241,779 |
scotthuang1989/object_detection_with_tensorflow | transformer_units.py | combine_heads | combine_heads | Performs the inverse of split_heads. | [
"Performs",
"the",
"inverse",
"of",
"split_heads."
] | def combine_heads(x):
return combine_last_two_dimensions(tf.transpose(x, [0, 2, 1, 3])) | ['def', 'combine_heads(x):', 'return', 'combine_last_two_dimensions(tf.transpose(x,', '[0,', '2,', '1,', '3]))'] | 739,875 |
google-research/scenic | ops.py | random_solarization | random_solarization | Randomly solarizes the images. | [
"Randomly",
"solarizes",
"the",
"images."
] | def random_solarization(p=0.1):
def _solarize(image):
image = image * tf.cast(tf.less(image, 0.5), tf.float32) + (1.0 - image) * tf.cast(tf.greater_equal(image, 0.5), tf.float32)
return image
def _random_solarize(image):
return tf.cond(tf.less(tf.random.uniform([], minval=0, maxval=1, ... | ['def', 'random_solarization(p=0.1):', 'def', '_solarize(image):', 'image', '=', 'image', '*', 'tf.cast(tf.less(image,', '0.5),', 'tf.float32)', '+', '(1.0', '-', 'image)', '*', 'tf.cast(tf.greater_equal(image,', '0.5),', 'tf.float32)', 'return', 'image', 'def', '_random_solarize(image):', 'return', 'tf.cond(tf.less(tf... | 847,007 |
pyRiemann/pyRiemann | test_simulated.py | test_make_matrices_return | test_make_matrices_return | Test function for make matrices. | [
"Test",
"function",
"for",
"make",
"matrices."
] | def test_make_matrices_return(rndstate, kind, eigvecs_same):
(n_matrices, n_dim) = (5, 4)
(X, evals, evecs) = make_matrices(n_matrices=n_matrices, n_dim=n_dim, kind=kind, return_params=True, eigvecs_same=eigvecs_same, rs=rndstate)
assert X.shape == (n_matrices, n_dim, n_dim)
assert evals.shape == (n_mat... | ['def', 'test_make_matrices_return(rndstate,', 'kind,', 'eigvecs_same):', '(n_matrices,', 'n_dim)', '=', '(5,', '4)', '(X,', 'evals,', 'evecs)', '=', 'make_matrices(n_matrices=n_matrices,', 'n_dim=n_dim,', 'kind=kind,', 'return_params=True,', 'eigvecs_same=eigvecs_same,', 'rs=rndstate)', 'assert', 'X.shape', '==', '(n_... | 809,336 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | mel_features.py | log_mel_spectrogram | log_mel_spectrogram | Convert waveform to a log magnitude mel-frequency spectrogram. | [
"Convert",
"waveform",
"to",
"a",
"log",
"magnitude",
"mel-frequency",
"spectrogram."
] | def log_mel_spectrogram(data, audio_sample_rate=8000, log_offset=0.0, window_length_secs=0.025, hop_length_secs=0.01, **kwargs):
window_length_samples = int(round(audio_sample_rate * window_length_secs))
hop_length_samples = int(round(audio_sample_rate * hop_length_secs))
fft_length = 2 ** int(np.ceil(np.lo... | ['def', 'log_mel_spectrogram(data,', 'audio_sample_rate=8000,', 'log_offset=0.0,', 'window_length_secs=0.025,', 'hop_length_secs=0.01,', '**kwargs):', 'window_length_samples', '=', 'int(round(audio_sample_rate', '*', 'window_length_secs))', 'hop_length_samples', '=', 'int(round(audio_sample_rate', '*', 'hop_length_secs... | 20,957 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.