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 |
|---|---|---|---|---|---|---|---|---|
sulc/tfrecord-viewer | detection_overlay.py | DetectionOverlay.draw_bboxes | draw_bboxes | Draw bounding boxes onto image. | [
"Draw",
"bounding",
"boxes",
"onto",
"image."
] | def draw_bboxes(self, image_bytes, bboxes):
img = Image.open(io.BytesIO(image_bytes))
draw = ImageDraw.Draw(img)
(width, height) = img.size
for bbox in bboxes:
(label, xmin, xmax, ymin, ymax) = self.bboxes_to_pixels(bbox, width, height)
draw.rectangle([xmin, ymin, xmax, ymax], outline=se... | ['def', 'draw_bboxes(self,', 'image_bytes,', 'bboxes):', 'img', '=', 'Image.open(io.BytesIO(image_bytes))', 'draw', '=', 'ImageDraw.Draw(img)', '(width,', 'height)', '=', 'img.size', 'for', 'bbox', 'in', 'bboxes:', '(label,', 'xmin,', 'xmax,', 'ymin,', 'ymax)', '=', 'self.bboxes_to_pixels(bbox,', 'width,', 'height)', '... | 915,784 |
wandb/wandb | interfaces.py | MetricsMonitor.monitor | monitor | Poll the Asset metrics. | [
"Poll",
"the",
"Asset",
"metrics."
] | def monitor(self) -> None:
while not self._shutdown_event.is_set():
for _ in range(self.samples_to_aggregate):
for metric in self.metrics:
try:
metric.sample()
except psutil.NoSuchProcess:
logger.info(f'Process {metric.name}... | ['def', 'monitor(self)', '->', 'None:', 'while', 'not', 'self._shutdown_event.is_set():', 'for', '_', 'in', 'range(self.samples_to_aggregate):', 'for', 'metric', 'in', 'self.metrics:', 'try:', 'metric.sample()', 'except', 'psutil.NoSuchProcess:', "logger.info(f'Process", '{metric.name}', 'has', "exited.')", 'self._shut... | 941,734 |
aeon-toolkit/aeon | eagglo.py | euclidean_matrix_to_matrix | euclidean_matrix_to_matrix | Compute the Euclidean distances between the rows of two matrices. | [
"Compute",
"the",
"Euclidean",
"distances",
"between",
"the",
"rows",
"of",
"two",
"matrices."
] | def euclidean_matrix_to_matrix(a, b):
(n, m) = (a.shape[0], b.shape[0])
out = np.zeros((n, m))
for i in range(n):
for j in range(m):
out[i, j] = euclidean(a[i], b[j])
return out | ['def', 'euclidean_matrix_to_matrix(a,', 'b):', '(n,', 'm)', '=', '(a.shape[0],', 'b.shape[0])', 'out', '=', 'np.zeros((n,', 'm))', 'for', 'i', 'in', 'range(n):', 'for', 'j', 'in', 'range(m):', 'out[i,', 'j]', '=', 'euclidean(a[i],', 'b[j])', 'return', 'out'] | 399,052 |
SamHusbands21/thesis | model_building.py | hyperparameter_randomiser_rf | hyperparameter_randomiser_rf | Returns the best hyperparameters from given ranges using a random search algorithm (all searches use uniform distribution): max_depth_range: Range of max_depth max_features_range: Range of maximum features per split min_leaf_range: Range of minimum data points per leaf node n_trees_range: Range of number of trees in a ... | [
"Returns",
"the",
"best",
"hyperparameters",
"from",
"given",
"ranges",
"using",
"a",
"random",
"search",
"algorithm",
"(all",
"searches",
"use",
"uniform",
"distribution):",
"max_depth_range:",
"Range",
"of",
"max_depth",
"max_features_range:",
"Range",
"of",
"maximu... | def hyperparameter_randomiser_rf(max_depth_range, max_features_range, min_leaf_range, n_trees_range, prints=False):
max_depth = randint(max_depth_range[0], max_depth_range[1] + 1).rvs(1).item()
max_features = randint(max_features_range[0], max_features_range[1] + 1).rvs(1).item()
min_leaf = randint(min_leaf... | ['def', 'hyperparameter_randomiser_rf(max_depth_range,', 'max_features_range,', 'min_leaf_range,', 'n_trees_range,', 'prints=False):', 'max_depth', '=', 'randint(max_depth_range[0],', 'max_depth_range[1]', '+', '1).rvs(1).item()', 'max_features', '=', 'randint(max_features_range[0],', 'max_features_range[1]', '+', '1).... | 354,922 |
huawei-noah/xingtian | device_evaluator.py | DeviceEvaluator.valid | valid | Validate the latency in davinci or bolt. | [
"Validate",
"the",
"latency",
"in",
"davinci",
"or",
"bolt."
] | def valid(self):
test_data = os.path.join(self.get_local_worker_path(self.step_name, self.worker_id), 'input.bin')
latency_sum = 0
data_num = 0
global_step = 0
now_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')
job_id = self.step_name + '_' + str(self.worker_id) + '_' + now_time
l... | ['def', 'valid(self):', 'test_data', '=', 'os.path.join(self.get_local_worker_path(self.step_name,', 'self.worker_id),', "'input.bin')", 'latency_sum', '=', '0', 'data_num', '=', '0', 'global_step', '=', '0', 'now_time', '=', "datetime.datetime.now().strftime('%Y%m%d%H%M%S%f')", 'job_id', '=', 'self.step_name', '+', "'... | 962,605 |
cheng052/BRNet | open3d_vis.py | Visualizer.show | show | Visualize the points cloud. | [
"Visualize",
"the",
"points",
"cloud."
] | def show(self, save_path=None):
self.o3d_visualizer.run()
if save_path is not None:
self.o3d_visualizer.capture_screen_image(save_path)
self.o3d_visualizer.destroy_window()
return | ['def', 'show(self,', 'save_path=None):', 'self.o3d_visualizer.run()', 'if', 'save_path', 'is', 'not', 'None:', 'self.o3d_visualizer.capture_screen_image(save_path)', 'self.o3d_visualizer.destroy_window()', 'return'] | 409,785 |
aravindsankar28/Inf-VAE | preprocess.py | normalize_graph_gcn | normalize_graph_gcn | Normalize adjacency matrix following GCN. | [
"Normalize",
"adjacency",
"matrix",
"following",
"GCN."
] | def normalize_graph_gcn(adj):
adj = sp.coo_matrix(adj)
adj_ = adj + sp.eye(adj.shape[0])
row_sum = np.array(adj_.sum(1))
degree_mat_inv_sqrt = sp.diags(np.power(row_sum, -0.5).flatten())
adj_normalized = adj_.dot(degree_mat_inv_sqrt).transpose().dot(degree_mat_inv_sqrt).tocoo()
return sparse_to_... | ['def', 'normalize_graph_gcn(adj):', 'adj', '=', 'sp.coo_matrix(adj)', 'adj_', '=', 'adj', '+', 'sp.eye(adj.shape[0])', 'row_sum', '=', 'np.array(adj_.sum(1))', 'degree_mat_inv_sqrt', '=', 'sp.diags(np.power(row_sum,', '-0.5).flatten())', 'adj_normalized', '=', 'adj_.dot(degree_mat_inv_sqrt).transpose().dot(degree_mat_... | 612,469 |
zxj32/uncertainty-GNN | metrics.py | masked_cross_entropy_dirichlet | masked_cross_entropy_dirichlet | Softmax cross-entropy loss with masking. | [
"Softmax",
"cross-entropy",
"loss",
"with",
"masking."
] | def masked_cross_entropy_dirichlet(preds, labels, mask):
alpha = tf.exp(preds) + 1.0
S = tf.reduce_sum(alpha, axis=1, keepdims=True)
s_digmma = tf.digamma(S)
loss = labels * (s_digmma - tf.digamma(alpha))
loss = tf.reduce_sum(loss, axis=1)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.re... | ['def', 'masked_cross_entropy_dirichlet(preds,', 'labels,', 'mask):', 'alpha', '=', 'tf.exp(preds)', '+', '1.0', 'S', '=', 'tf.reduce_sum(alpha,', 'axis=1,', 'keepdims=True)', 's_digmma', '=', 'tf.digamma(S)', 'loss', '=', 'labels', '*', '(s_digmma', '-', 'tf.digamma(alpha))', 'loss', '=', 'tf.reduce_sum(loss,', 'axis=... | 378,025 |
zhang614/MicroGrid | test_filter_design.py | TestZpk2Tf.test_identity | test_identity | Test the identity transfer function. | [
"Test",
"the",
"identity",
"transfer",
"function."
] | def test_identity(self):
z = []
p = []
k = 1.0
(b, a) = zpk2tf(z, p, k)
b_r = np.array([1.0])
a_r = np.array([1.0])
assert_array_equal(b, b_r)
assert_(isinstance(b, np.ndarray))
assert_array_equal(a, a_r)
assert_(isinstance(a, np.ndarray)) | ['def', 'test_identity(self):', 'z', '=', '[]', 'p', '=', '[]', 'k', '=', '1.0', '(b,', 'a)', '=', 'zpk2tf(z,', 'p,', 'k)', 'b_r', '=', 'np.array([1.0])', 'a_r', '=', 'np.array([1.0])', 'assert_array_equal(b,', 'b_r)', 'assert_(isinstance(b,', 'np.ndarray))', 'assert_array_equal(a,', 'a_r)', 'assert_(isinstance(a,', 'n... | 669,679 |
explosion/spaCy | test_pipe_factories.py | test_pipe_factories_language_specific | test_pipe_factories_language_specific | Test that language sub-classes can have their own factories, with fallbacks to the base factories. | [
"Test",
"that",
"language",
"sub-classes",
"can",
"have",
"their",
"own",
"factories,",
"with",
"fallbacks",
"to",
"the",
"base",
"factories."
] | def test_pipe_factories_language_specific():
name1 = 'specific_component1'
name2 = 'specific_component2'
Language.component(name1, func=lambda : 'base')
English.component(name1, func=lambda : 'en')
German.component(name2, func=lambda : 'de')
assert Language.has_factory(name1)
assert not Lang... | ['def', 'test_pipe_factories_language_specific():', 'name1', '=', "'specific_component1'", 'name2', '=', "'specific_component2'", 'Language.component(name1,', 'func=lambda', ':', "'base')", 'English.component(name1,', 'func=lambda', ':', "'en')", 'German.component(name2,', 'func=lambda', ':', "'de')", 'assert', 'Langua... | 894,297 |
Ruturaj123/Flowchart-Detection | feature_column.py | bucketized_column | bucketized_column | Creates a _BucketizedColumn for discretizing dense input. | [
"Creates",
"a",
"_BucketizedColumn",
"for",
"discretizing",
"dense",
"input."
] | def bucketized_column(source_column, boundaries):
return _BucketizedColumn(source_column, boundaries) | ['def', 'bucketized_column(source_column,', 'boundaries):', 'return', '_BucketizedColumn(source_column,', 'boundaries)'] | 603,636 |
fudan-zvg/SETR | solov2_head.py | SOLOV2Head.get_results | get_results | Get multi-image mask results. | [
"Get",
"multi-image",
"mask",
"results."
] | def get_results(self, mlvl_kernel_preds, mlvl_cls_scores, mask_feats, img_metas, **kwargs):
num_levels = len(mlvl_cls_scores)
assert len(mlvl_kernel_preds) == len(mlvl_cls_scores)
for lvl in range(num_levels):
cls_scores = mlvl_cls_scores[lvl]
cls_scores = cls_scores.sigmoid()
local_... | ['def', 'get_results(self,', 'mlvl_kernel_preds,', 'mlvl_cls_scores,', 'mask_feats,', 'img_metas,', '**kwargs):', 'num_levels', '=', 'len(mlvl_cls_scores)', 'assert', 'len(mlvl_kernel_preds)', '==', 'len(mlvl_cls_scores)', 'for', 'lvl', 'in', 'range(num_levels):', 'cls_scores', '=', 'mlvl_cls_scores[lvl]', 'cls_scores'... | 898,199 |
antriv/Transfer_Learning_Text | layers.py | bidirectional_GRU | bidirectional_GRU | Bidirectional recurrent neural network with GRU cells. | [
"Bidirectional",
"recurrent",
"neural",
"network",
"with",
"GRU",
"cells."
] | def bidirectional_GRU(inputs, inputs_len, cell=None, cell_fn=tf.contrib.rnn.GRUCell, units=Params.attn_size, layers=1, scope='Bidirectional_GRU', output=0, is_training=True, reuse=None):
with tf.variable_scope(scope, reuse=reuse):
if cell is not None:
(cell_fw, cell_bw) = cell
else:
... | ['def', 'bidirectional_GRU(inputs,', 'inputs_len,', 'cell=None,', 'cell_fn=tf.contrib.rnn.GRUCell,', 'units=Params.attn_size,', 'layers=1,', "scope='Bidirectional_GRU',", 'output=0,', 'is_training=True,', 'reuse=None):', 'with', 'tf.variable_scope(scope,', 'reuse=reuse):', 'if', 'cell', 'is', 'not', 'None:', '(cell_fw,... | 964,668 |
clips/pattern | metrics.py | F | F | Returns the weighted harmonic mean of precision and recall, where recall is beta times more important than precision. | [
"Returns",
"the",
"weighted",
"harmonic",
"mean",
"of",
"precision",
"and",
"recall,",
"where",
"recall",
"is",
"beta",
"times",
"more",
"important",
"than",
"precision."
] | def F(classify=lambda document: False, documents=[], beta=1, average=None):
(A, P, R, F1) = test(classify, documents, average)
return (beta ** 2 + 1) * P * R / (beta ** 2 * P + R or 1) | ['def', 'F(classify=lambda', 'document:', 'False,', 'documents=[],', 'beta=1,', 'average=None):', '(A,', 'P,', 'R,', 'F1)', '=', 'test(classify,', 'documents,', 'average)', 'return', '(beta', '**', '2', '+', '1)', '*', 'P', '*', 'R', '/', '(beta', '**', '2', '*', 'P', '+', 'R', 'or', '1)'] | 764,491 |
KalleHallden/InstaAutomator | decorators.py | audio_video_fx | audio_video_fx | Use an audio function on a video/audio clip This decorator tells that the function f (audioclip -> audioclip) can be also used on a video clip, at which case it returns a videoclip with unmodified video and modified audio. | [
"Use",
"an",
"audio",
"function",
"on",
"a",
"video/audio",
"clip",
"This",
"decorator",
"tells",
"that",
"the",
"function",
"f",
"(audioclip",
"->",
"audioclip)",
"can",
"be",
"also",
"used",
"on",
"a",
"video",
"clip,",
"at",
"which",
"case",
"it",
"retu... | def audio_video_fx(f, clip, *a, **k):
if hasattr(clip, 'audio'):
newclip = clip.copy()
if clip.audio is not None:
newclip.audio = f(clip.audio, *a, **k)
return newclip
else:
return f(clip, *a, **k) | ['def', 'audio_video_fx(f,', 'clip,', '*a,', '**k):', 'if', 'hasattr(clip,', "'audio'):", 'newclip', '=', 'clip.copy()', 'if', 'clip.audio', 'is', 'not', 'None:', 'newclip.audio', '=', 'f(clip.audio,', '*a,', '**k)', 'return', 'newclip', 'else:', 'return', 'f(clip,', '*a,', '**k)'] | 230,338 |
ivanmontero/autobot | logging.py | set_verbosity_info | set_verbosity_info | Set the verbosity to the :obj:`INFO` level. | [
"Set",
"the",
"verbosity",
"to",
"the",
":obj:`INFO`",
"level."
] | def set_verbosity_info():
return set_verbosity(INFO) | ['def', 'set_verbosity_info():', 'return', 'set_verbosity(INFO)'] | 418,552 |
PaddlePaddle/PARL | worker_manager.py | WorkerManager.get_hostname | get_hostname | Return the hostname of a worker. | [
"Return",
"the",
"hostname",
"of",
"a",
"worker."
] | def get_hostname(self, worker_address):
with self.lock:
return self.worker_hostname[worker_address] | ['def', 'get_hostname(self,', 'worker_address):', 'with', 'self.lock:', 'return', 'self.worker_hostname[worker_address]'] | 278,145 |
jimtin/Stock_Comparison | ansi_code_processor.py | QtAnsiCodeProcessor.get_color | get_color | Returns a QColor for a given color code, or None if one cannot be constructed. | [
"Returns",
"a",
"QColor",
"for",
"a",
"given",
"color",
"code,",
"or",
"None",
"if",
"one",
"cannot",
"be",
"constructed."
] | def get_color(self, color, intensity=0):
if color is None:
return None
if color < 8 and intensity > 0:
color += 8
constructor = self.color_map.get(color, None)
if isinstance(constructor, string_types):
return QtGui.QColor(constructor)
elif isinstance(constructor, (tuple, list... | ['def', 'get_color(self,', 'color,', 'intensity=0):', 'if', 'color', 'is', 'None:', 'return', 'None', 'if', 'color', '<', '8', 'and', 'intensity', '>', '0:', 'color', '+=', '8', 'constructor', '=', 'self.color_map.get(color,', 'None)', 'if', 'isinstance(constructor,', 'string_types):', 'return', 'QtGui.QColor(construct... | 358,500 |
YanZiQinKevin/object_detection | mask_rcnn_heads.py | mask_rcnn_fcn_head_v0up | mask_rcnn_fcn_head_v0up | v0up design: conv5, deconv 2x2 (no weight sharing with the box head). | [
"v0up",
"design:",
"conv5,",
"deconv",
"2x2",
"(no",
"weight",
"sharing",
"with",
"the",
"box",
"head)."
] | def mask_rcnn_fcn_head_v0up(model, blob_in, dim_in, spatial_scale):
(blob_conv5, dim_conv5) = add_ResNet_roi_conv5_head_for_masks(model, blob_in, dim_in, spatial_scale)
dim_reduced = cfg.MRCNN.DIM_REDUCED
model.ConvTranspose(blob_conv5, 'conv5_mask', dim_conv5, dim_reduced, kernel=2, pad=0, stride=2, weight... | ['def', 'mask_rcnn_fcn_head_v0up(model,', 'blob_in,', 'dim_in,', 'spatial_scale):', '(blob_conv5,', 'dim_conv5)', '=', 'add_ResNet_roi_conv5_head_for_masks(model,', 'blob_in,', 'dim_in,', 'spatial_scale)', 'dim_reduced', '=', 'cfg.MRCNN.DIM_REDUCED', 'model.ConvTranspose(blob_conv5,', "'conv5_mask',", 'dim_conv5,', 'di... | 772,754 |
surafelml/adapt-mnmt | compat.py | tf_any | tf_any | Returns the first supported symbol. | [
"Returns",
"the",
"first",
"supported",
"symbol."
] | def tf_any(*symbols):
for symbol in symbols:
module = _string_to_tf_symbol(symbol)
if module is not None:
return module
return None | ['def', 'tf_any(*symbols):', 'for', 'symbol', 'in', 'symbols:', 'module', '=', '_string_to_tf_symbol(symbol)', 'if', 'module', 'is', 'not', 'None:', 'return', 'module', 'return', 'None'] | 407,844 |
MrZilinXiao/DroneObjectDetection | __init__.py | detect_camera | detect_camera | sending each frame from camera to detect_image of class YOLO. | [
"sending",
"each",
"frame",
"from",
"camera",
"to",
"detect_image",
"of",
"class",
"YOLO."
] | def detect_camera(cam):
import cv2
vid = cv2.VideoCapture(cam)
if not vid.isOpened():
raise IOError("Couldn't open webcam!Please Check cable connection or driver installation!")
accum_time = 0
curr_fps = 0
fps = 'FPS: ??'
prev_time = timer()
while True:
(return_value, fra... | ['def', 'detect_camera(cam):', 'import', 'cv2', 'vid', '=', 'cv2.VideoCapture(cam)', 'if', 'not', 'vid.isOpened():', 'raise', 'IOError("Couldn\'t', 'open', 'webcam!Please', 'Check', 'cable', 'connection', 'or', 'driver', 'installation!")', 'accum_time', '=', '0', 'curr_fps', '=', '0', 'fps', '=', "'FPS:", "??'", 'prev_... | 553,433 |
sek788432/Waymo-2D-Object-Detection | controller_test.py | summaries_with_matching_keyword | summaries_with_matching_keyword | Returns summary protos matching given keyword from event file. | [
"Returns",
"summary",
"protos",
"matching",
"given",
"keyword",
"from",
"event",
"file."
] | def summaries_with_matching_keyword(keyword, summary_dir):
matches = []
event_paths = tf.io.gfile.glob(os.path.join(summary_dir, 'events*'))
for event in tf.compat.v1.train.summary_iterator(event_paths[-1]):
if event.summary is not None:
for value in event.summary.value:
... | ['def', 'summaries_with_matching_keyword(keyword,', 'summary_dir):', 'matches', '=', '[]', 'event_paths', '=', 'tf.io.gfile.glob(os.path.join(summary_dir,', "'events*'))", 'for', 'event', 'in', 'tf.compat.v1.train.summary_iterator(event_paths[-1]):', 'if', 'event.summary', 'is', 'not', 'None:', 'for', 'value', 'in', 'e... | 973,826 |
nicknochnack/RealTimeSignLanguageTFJS | autoaugment_utils.py | sharpness | sharpness | Implements Sharpness function from PIL using TF ops. | [
"Implements",
"Sharpness",
"function",
"from",
"PIL",
"using",
"TF",
"ops."
] | def sharpness(image, factor):
orig_image = image
image = tf.cast(image, tf.float32)
image = tf.expand_dims(image, 0)
kernel = tf.constant([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=tf.float32, shape=[3, 3, 1, 1]) / 13.0
kernel = tf.tile(kernel, [1, 1, 3, 1])
strides = [1, 1, 1, 1]
degenerate =... | ['def', 'sharpness(image,', 'factor):', 'orig_image', '=', 'image', 'image', '=', 'tf.cast(image,', 'tf.float32)', 'image', '=', 'tf.expand_dims(image,', '0)', 'kernel', '=', 'tf.constant([[1,', '1,', '1],', '[1,', '5,', '1],', '[1,', '1,', '1]],', 'dtype=tf.float32,', 'shape=[3,', '3,', '1,', '1])', '/', '13.0', 'kern... | 830,821 |
santhoshkolloju/Abstractive-Summarization-With-Transfer- | replay_memories.py | ReplayMemoryBase.get | get | Pops a memory entry. | [
"Pops",
"a",
"memory",
"entry."
] | def get(self, size):
raise NotImplementedError | ['def', 'get(self,', 'size):', 'raise', 'NotImplementedError'] | 405,992 |
kamathhrishi/PATE | util.py | split | split | Splits the given dataset into training/validation. | [
"Splits",
"the",
"given",
"dataset",
"into",
"training/validation."
] | def split(dataset, batch_size, split=0.2):
index = 0
length = len(dataset)
train_set = []
val_set = []
for (data, target) in dataset:
if index <= length * split:
train_set.append([data, target])
else:
val_set.append([data, target])
index += 1
retur... | ['def', 'split(dataset,', 'batch_size,', 'split=0.2):', 'index', '=', '0', 'length', '=', 'len(dataset)', 'train_set', '=', '[]', 'val_set', '=', '[]', 'for', '(data,', 'target)', 'in', 'dataset:', 'if', 'index', '<=', 'length', '*', 'split:', 'train_set.append([data,', 'target])', 'else:', 'val_set.append([data,', 'ta... | 278,584 |
weimin17/Object-Detection_HelmetDetection | network_units_test.py | LstmNetworkTest.testRuntimeConcatentatedMatrices | testRuntimeConcatentatedMatrices | Test generation of concatenated matrices. | [
"Test",
"generation",
"of",
"concatenated",
"matrices."
] | def testRuntimeConcatentatedMatrices(self):
master = MockMaster(build_runtime_graph=False)
master.spec = spec_pb2.MasterSpec()
text_format.Parse(self.test_spec_1, master.spec)
lstm_network_unit = self.construct_lstm_network_unit(master)
with tf.variable_scope('bi_lstm', reuse=True):
lstm_net... | ['def', 'testRuntimeConcatentatedMatrices(self):', 'master', '=', 'MockMaster(build_runtime_graph=False)', 'master.spec', '=', 'spec_pb2.MasterSpec()', 'text_format.Parse(self.test_spec_1,', 'master.spec)', 'lstm_network_unit', '=', 'self.construct_lstm_network_unit(master)', 'with', "tf.variable_scope('bi_lstm',", 're... | 760,295 |
jimtin/Stock_Comparison | extras.py | HstoreAdapter.get_oids | get_oids | Return the lists of OID of the hstore and hstore[] types. | [
"Return",
"the",
"lists",
"of",
"OID",
"of",
"the",
"hstore",
"and",
"hstore[]",
"types."
] | def get_oids(self, conn_or_curs):
(conn, curs) = _solve_conn_curs(conn_or_curs)
conn_status = conn.status
typarray = conn.server_version >= 80300 and 'typarray' or 'NULL'
(rv0, rv1) = ([], [])
curs.execute("SELECT t.oid, %s\nFROM pg_type t JOIN pg_namespace ns\n ON typnamespace = ns.oid\nWHERE ty... | ['def', 'get_oids(self,', 'conn_or_curs):', '(conn,', 'curs)', '=', '_solve_conn_curs(conn_or_curs)', 'conn_status', '=', 'conn.status', 'typarray', '=', 'conn.server_version', '>=', '80300', 'and', "'typarray'", 'or', "'NULL'", '(rv0,', 'rv1)', '=', '([],', '[])', 'curs.execute("SELECT', 't.oid,', '%s\\nFROM', 'pg_typ... | 389,318 |
KaiyangZhou/Dassl.pytorch | utils.py | load_pretrained_weights | load_pretrained_weights | Loads pretrained weights, and downloads if loading for the first time. | [
"Loads",
"pretrained",
"weights,",
"and",
"downloads",
"if",
"loading",
"for",
"the",
"first",
"time."
] | def load_pretrained_weights(model, model_name, load_fc=True, advprop=False):
url_map_ = url_map_advprop if advprop else url_map
state_dict = model_zoo.load_url(url_map_[model_name])
model.load_state_dict(state_dict, strict=False) | ['def', 'load_pretrained_weights(model,', 'model_name,', 'load_fc=True,', 'advprop=False):', 'url_map_', '=', 'url_map_advprop', 'if', 'advprop', 'else', 'url_map', 'state_dict', '=', 'model_zoo.load_url(url_map_[model_name])', 'model.load_state_dict(state_dict,', 'strict=False)'] | 126,745 |
Erfanafshar/Principles-and-Applications-of---graph-coloring | rcsetup.py | validate_bool_maybe_none | validate_bool_maybe_none | Convert b to a boolean or raise. | [
"Convert",
"b",
"to",
"a",
"boolean",
"or",
"raise."
] | def validate_bool_maybe_none(b):
if isinstance(b, str):
b = b.lower()
if b is None or b == 'none':
return None
if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
return True
elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
return False
else:
rais... | ['def', 'validate_bool_maybe_none(b):', 'if', 'isinstance(b,', 'str):', 'b', '=', 'b.lower()', 'if', 'b', 'is', 'None', 'or', 'b', '==', "'none':", 'return', 'None', 'if', 'b', 'in', "('t',", "'y',", "'yes',", "'on',", "'true',", "'1',", '1,', 'True):', 'return', 'True', 'elif', 'b', 'in', "('f',", "'n',", "'no',", "'o... | 306,960 |
zcablii/LSKNet | transforms.py | hbb2obb_oc | hbb2obb_oc | Convert horizontal bounding boxes to oriented bounding boxes. | [
"Convert",
"horizontal",
"bounding",
"boxes",
"to",
"oriented",
"bounding",
"boxes."
] | def hbb2obb_oc(hbboxes):
x = (hbboxes[..., 0] + hbboxes[..., 2]) * 0.5
y = (hbboxes[..., 1] + hbboxes[..., 3]) * 0.5
w = hbboxes[..., 2] - hbboxes[..., 0]
h = hbboxes[..., 3] - hbboxes[..., 1]
theta = x.new_zeros(*x.shape)
rbboxes = torch.stack([x, y, h, w, theta + np.pi / 2], dim=-1)
return... | ['def', 'hbb2obb_oc(hbboxes):', 'x', '=', '(hbboxes[...,', '0]', '+', 'hbboxes[...,', '2])', '*', '0.5', 'y', '=', '(hbboxes[...,', '1]', '+', 'hbboxes[...,', '3])', '*', '0.5', 'w', '=', 'hbboxes[...,', '2]', '-', 'hbboxes[...,', '0]', 'h', '=', 'hbboxes[...,', '3]', '-', 'hbboxes[...,', '1]', 'theta', '=', 'x.new_zer... | 616,010 |
matsu0228/nlp-jp | connection.py | MWSConnection.get_report_request_list | get_report_request_list | Returns a list of report requests that you can use to get the ReportRequestId for a report. | [
"Returns",
"a",
"list",
"of",
"report",
"requests",
"that",
"you",
"can",
"use",
"to",
"get",
"the",
"ReportRequestId",
"for",
"a",
"report."
] | def get_report_request_list(self, request, response, **kw):
return self._post_request(request, kw, response) | ['def', 'get_report_request_list(self,', 'request,', 'response,', '**kw):', 'return', 'self._post_request(request,', 'kw,', 'response)'] | 784,932 |
enlite-ai/maze | inventory.py | Inventory.size | size | Current size of the inventory. | [
"Current",
"size",
"of",
"the",
"inventory."
] | def size(self) -> int:
return len(self.pieces) | ['def', 'size(self)', '->', 'int:', 'return', 'len(self.pieces)'] | 647,614 |
nosmokingbandit/watcher | client.py | parse_torrent_id | parse_torrent_id | Parse an torrent id or torrent hashString. | [
"Parse",
"an",
"torrent",
"id",
"or",
"torrent",
"hashString."
] | def parse_torrent_id(arg):
torrent_id = None
if isinstance(arg, integer_types):
torrent_id = int(arg)
elif isinstance(arg, float):
torrent_id = int(arg)
if torrent_id != arg:
torrent_id = None
elif isinstance(arg, string_types):
try:
torrent_id = i... | ['def', 'parse_torrent_id(arg):', 'torrent_id', '=', 'None', 'if', 'isinstance(arg,', 'integer_types):', 'torrent_id', '=', 'int(arg)', 'elif', 'isinstance(arg,', 'float):', 'torrent_id', '=', 'int(arg)', 'if', 'torrent_id', '!=', 'arg:', 'torrent_id', '=', 'None', 'elif', 'isinstance(arg,', 'string_types):', 'try:', '... | 381,940 |
GregorKobsik/Octree-Transformer | multi_conv_head_A.py | MultiConvolutionHeadA.forward | forward | Transforms the output of the transformer target value logits. | [
"Transforms",
"the",
"output",
"of",
"the",
"transformer",
"target",
"value",
"logits."
] | def forward(self, x, value, depth, pos):
x = self.deconvolution_1(x)
x = self.deconvolution_0(x)
return self.linear(x) | ['def', 'forward(self,', 'x,', 'value,', 'depth,', 'pos):', 'x', '=', 'self.deconvolution_1(x)', 'x', '=', 'self.deconvolution_0(x)', 'return', 'self.linear(x)'] | 742,048 |
google/deepvariant | make_examples_core.py | RegionProcessor.add_label_to_example | add_label_to_example | Adds label information about the assigned label to our example. | [
"Adds",
"label",
"information",
"about",
"the",
"assigned",
"label",
"to",
"our",
"example."
] | def add_label_to_example(self, example, label):
if not label.is_confident:
raise ValueError('Cannot add a non-confident label to an example', example, label)
alt_alleles_indices = dv_utils.example_alt_alleles_indices(example)
dv_utils.example_set_variant(example, label.variant)
dv_utils.example_... | ['def', 'add_label_to_example(self,', 'example,', 'label):', 'if', 'not', 'label.is_confident:', 'raise', "ValueError('Cannot", 'add', 'a', 'non-confident', 'label', 'to', 'an', "example',", 'example,', 'label)', 'alt_alleles_indices', '=', 'dv_utils.example_alt_alleles_indices(example)', 'dv_utils.example_set_variant(... | 540,333 |
matsu0228/nlp-jp | compiler.py | CodeGenerator.writeline | writeline | Combination of newline and write. | [
"Combination",
"of",
"newline",
"and",
"write."
] | def writeline(self, x, node=None, extra=0):
self.newline(node, extra)
self.write(x) | ['def', 'writeline(self,', 'x,', 'node=None,', 'extra=0):', 'self.newline(node,', 'extra)', 'self.write(x)'] | 787,766 |
matsu0228/nlp-jp | imports.py | Importer.str_import_path | str_import_path | Returns the import path as pure strings instead of `Name`. | [
"Returns",
"the",
"import",
"path",
"as",
"pure",
"strings",
"instead",
"of",
"`Name`."
] | def str_import_path(self):
return tuple((name.value if isinstance(name, tree.Name) else name for name in self.import_path)) | ['def', 'str_import_path(self):', 'return', 'tuple((name.value', 'if', 'isinstance(name,', 'tree.Name)', 'else', 'name', 'for', 'name', 'in', 'self.import_path))'] | 787,708 |
43Carrig/recurrent_neural_networks_practice | control_flow_ops.py | WhileContext.AddOp | AddOp | Add `op` to the current context. | [
"Add",
"`op`",
"to",
"the",
"current",
"context."
] | def AddOp(self, op):
if op.type in {'Shape', 'Size', 'Rank'}:
grad_ctxt = ops.get_default_graph()._get_control_flow_context()
if grad_ctxt:
grad_ctxt = grad_ctxt.GetWhileContext()
if grad_ctxt.grad_state:
op_input_forward_ctxt = _GetWhileContext(op.inputs[0].o... | ['def', 'AddOp(self,', 'op):', 'if', 'op.type', 'in', "{'Shape',", "'Size',", "'Rank'}:", 'grad_ctxt', '=', 'ops.get_default_graph()._get_control_flow_context()', 'if', 'grad_ctxt:', 'grad_ctxt', '=', 'grad_ctxt.GetWhileContext()', 'if', 'grad_ctxt.grad_state:', 'op_input_forward_ctxt', '=', '_GetWhileContext(op.inputs... | 337,183 |
enuguru/artificial_intelligence_and_machine_ | markers.py | default_environment | default_environment | Return copy of default PEP 385 globals dictionary. | [
"Return",
"copy",
"of",
"default",
"PEP",
"385",
"globals",
"dictionary."
] | def default_environment():
return dict(_VARS) | ['def', 'default_environment():', 'return', 'dict(_VARS)'] | 164,343 |
usmancheema89/computer_vision | text_dataflow.py | rotatedPoint | rotatedPoint | Transform polygon with affine transform matrix. | [
"Transform",
"polygon",
"with",
"affine",
"transform",
"matrix."
] | def rotatedPoint(R, point):
x = R[0, 0] * point[0] + R[0, 1] * point[1] + R[0, 2]
y = R[1, 0] * point[0] + R[1, 1] * point[1] + R[1, 2]
return [int(x), int(y)] | ['def', 'rotatedPoint(R,', 'point):', 'x', '=', 'R[0,', '0]', '*', 'point[0]', '+', 'R[0,', '1]', '*', 'point[1]', '+', 'R[0,', '2]', 'y', '=', 'R[1,', '0]', '*', 'point[0]', '+', 'R[1,', '1]', '*', 'point[1]', '+', 'R[1,', '2]', 'return', '[int(x),', 'int(y)]'] | 501,464 |
TonyLianLong/VAI-ReinforcementLearning | mazes.py | MazeWithTargets.regenerate | regenerate | Generates a new maze layout. | [
"Generates",
"a",
"new",
"maze",
"layout."
] | def regenerate(self):
self._maze.regenerate()
logging.debug('GENERATED MAZE:\n%s', self._maze.entity_layer)
self._find_spawn_and_target_positions()
if self._text_maze_regenerated_hook:
self._text_maze_regenerated_hook()
for geom_name in self._texturing_geom_names:
del self._mjcf_root... | ['def', 'regenerate(self):', 'self._maze.regenerate()', "logging.debug('GENERATED", "MAZE:\\n%s',", 'self._maze.entity_layer)', 'self._find_spawn_and_target_positions()', 'if', 'self._text_maze_regenerated_hook:', 'self._text_maze_regenerated_hook()', 'for', 'geom_name', 'in', 'self._texturing_geom_names:', 'del', 'sel... | 439,942 |
nicknochnack/RealTimeSignLanguageTFJS | export_saved_model_tpu_lib.py | parse_pipeline_config | parse_pipeline_config | Returns pipeline config and meta architecture name. | [
"Returns",
"pipeline",
"config",
"and",
"meta",
"architecture",
"name."
] | def parse_pipeline_config(pipeline_config_file):
with tf.gfile.GFile(pipeline_config_file, 'r') as config_file:
config_str = config_file.read()
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
text_format.Merge(config_str, pipeline_config)
meta_arch = pipeline_config.model.WhichOneof('mo... | ['def', 'parse_pipeline_config(pipeline_config_file):', 'with', 'tf.gfile.GFile(pipeline_config_file,', "'r')", 'as', 'config_file:', 'config_str', '=', 'config_file.read()', 'pipeline_config', '=', 'pipeline_pb2.TrainEvalPipelineConfig()', 'text_format.Merge(config_str,', 'pipeline_config)', 'meta_arch', '=', "pipelin... | 852,666 |
rudranil723/mini-main | plot_directive.py | mark_plot_labels | mark_plot_labels | To make plots referenceable, we need to move the reference from the "htmlonly" (or "latexonly") node to the actual figure node itself. | [
"To",
"make",
"plots",
"referenceable,",
"we",
"need",
"to",
"move",
"the",
"reference",
"from",
"the",
"\"htmlonly\"",
"(or",
"\"latexonly\")",
"node",
"to",
"the",
"actual",
"figure",
"node",
"itself."
] | def mark_plot_labels(app, document):
for (name, explicit) in document.nametypes.items():
if not explicit:
continue
labelid = document.nameids[name]
if labelid is None:
continue
node = document.ids[labelid]
if node.tagname in ('html_only', 'latex_only')... | ['def', 'mark_plot_labels(app,', 'document):', 'for', '(name,', 'explicit)', 'in', 'document.nametypes.items():', 'if', 'not', 'explicit:', 'continue', 'labelid', '=', 'document.nameids[name]', 'if', 'labelid', 'is', 'None:', 'continue', 'node', '=', 'document.ids[labelid]', 'if', 'node.tagname', 'in', "('html_only',",... | 320,126 |
kevinzakka/form2fit | pointcloud.py | transform_xyz | transform_xyz | Applies a rigid transform to a pointcloud. | [
"Applies",
"a",
"rigid",
"transform",
"to",
"a",
"pointcloud."
] | def transform_xyz(xyz, transform):
xyz_h = np.hstack([xyz, np.ones((xyz.shape[0], 1))])
xyz_t = (transform @ xyz_h.T).T
xyz_t = xyz_t[:, :3]
return xyz_t | ['def', 'transform_xyz(xyz,', 'transform):', 'xyz_h', '=', 'np.hstack([xyz,', 'np.ones((xyz.shape[0],', '1))])', 'xyz_t', '=', '(transform', '@', 'xyz_h.T).T', 'xyz_t', '=', 'xyz_t[:,', ':3]', 'return', 'xyz_t'] | 213,226 |
PaddlePaddle/PARL | algorithm_base.py | AlgorithmBase.sample | sample | define sampling process, such as using policy model to sample actions when given observations. | [
"define",
"sampling",
"process,",
"such",
"as",
"using",
"policy",
"model",
"to",
"sample",
"actions",
"when",
"given",
"observations."
] | def sample(self, *args, **kwargs):
raise NotImplementedError | ['def', 'sample(self,', '*args,', '**kwargs):', 'raise', 'NotImplementedError'] | 277,948 |
pandeyankit83/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | nets_factory.py | get_network_fn | get_network_fn | Returns a network_fn such as `logits, end_points = network_fn(images)`. | [
"Returns",
"a",
"network_fn",
"such",
"as",
"`logits,",
"end_points",
"=",
"network_fn(images)`."
] | def get_network_fn(name, num_classes, weight_decay=0.0, is_training=False):
if name not in networks_map:
raise ValueError('Name of network unknown %s' % name)
func = networks_map[name]
@functools.wraps(func)
def network_fn(images, **kwargs):
arg_scope = arg_scopes_map[name](weight_decay... | ['def', 'get_network_fn(name,', 'num_classes,', 'weight_decay=0.0,', 'is_training=False):', 'if', 'name', 'not', 'in', 'networks_map:', 'raise', "ValueError('Name", 'of', 'network', 'unknown', "%s'", '%', 'name)', 'func', '=', 'networks_map[name]', '@functools.wraps(func)', 'def', 'network_fn(images,', '**kwargs):', 'a... | 110,053 |
microsoft/maro | abs_core.py | AbsEnv.step | step | Push the environment to next step with action. | [
"Push",
"the",
"environment",
"to",
"next",
"step",
"with",
"action."
] | def step(self, action) -> Tuple[Optional[dict], Optional[list], bool]:
raise NotImplementedError | ['def', 'step(self,', 'action)', '->', 'Tuple[Optional[dict],', 'Optional[list],', 'bool]:', 'raise', 'NotImplementedError'] | 628,576 |
TJU-DRL-LAB/AI-Optimizer | stack.py | StackedObservation.clear | clear | Clear stacked observation by filling 0. | [
"Clear",
"stacked",
"observation",
"by",
"filling",
"0."
] | def clear(self) -> None:
self._stack.fill(0) | ['def', 'clear(self)', '->', 'None:', 'self._stack.fill(0)'] | 95,217 |
tensorly/quantum | tfq_ps_util_ops_test.py | PSSymbolReplaceTest.test_weight_coefficient | test_weight_coefficient | Test that scalar multiples of trivial case work. | [
"Test",
"that",
"scalar",
"multiples",
"of",
"trivial",
"case",
"work."
] | def test_weight_coefficient(self):
bit = cirq.GridQubit(0, 0)
circuit = cirq.Circuit(cirq.X(bit) ** (sympy.Symbol('alpha') * 2.4), cirq.Y(bit) ** (sympy.Symbol('alpha') * 3.4), cirq.Z(bit) ** (sympy.Symbol('alpha') * 4.4))
inputs = util.convert_to_tensor([circuit])
symbols = tf.convert_to_tensor(['alpha... | ['def', 'test_weight_coefficient(self):', 'bit', '=', 'cirq.GridQubit(0,', '0)', 'circuit', '=', 'cirq.Circuit(cirq.X(bit)', '**', "(sympy.Symbol('alpha')", '*', '2.4),', 'cirq.Y(bit)', '**', "(sympy.Symbol('alpha')", '*', '3.4),', 'cirq.Z(bit)', '**', "(sympy.Symbol('alpha')", '*', '4.4))', 'inputs', '=', 'util.conver... | 834,689 |
blakeblackshear/frigate | test_camera_pw.py | TestUserPassCleanup.test_special_char_password | test_special_char_password | Test that special characters in pw are escaped, but not others. | [
"Test",
"that",
"special",
"characters",
"in",
"pw",
"are",
"escaped,",
"but",
"not",
"others."
] | def test_special_char_password(self):
escaped = escape_special_characters(self.rtsp_with_special_pass)
assert escaped == 'rtsp://user:password%60~%21%40%23%24%25%5E%26%2A%28%29-_%3B%27%2C.%3C%3E%3A%22%5C%7B%5C%7D%5C%5B%5C%5D%40@192.168.0.2:554/live' | ['def', 'test_special_char_password(self):', 'escaped', '=', 'escape_special_characters(self.rtsp_with_special_pass)', 'assert', 'escaped', '==', "'rtsp://user:password%60~%21%40%23%24%25%5E%26%2A%28%29-_%3B%27%2C.%3C%3E%3A%22%5C%7B%5C%7D%5C%5B%5C%5D%40@192.168.0.2:554/live'"] | 564,495 |
meowoodie/Unsupervised-Learning-in-Tensorflow | denoising_autoencoders.py | SdA.get_reconstructed_x | get_reconstructed_x | Calculate reconstructed x (x_hat) given input x. | [
"Calculate",
"reconstructed",
"x",
"(x_hat)",
"given",
"input",
"x."
] | def get_reconstructed_x(self, sess, x):
return sess.run(self.x_hat, feed_dict={self.x: x}) | ['def', 'get_reconstructed_x(self,', 'sess,', 'x):', 'return', 'sess.run(self.x_hat,', 'feed_dict={self.x:', 'x})'] | 379,007 |
lloydwindrim/hyperspectral-autoencoders | network_ops.py | create_variable | create_variable | Setup a trainable variable (collection of parameters) of a particular shape. | [
"Setup",
"a",
"trainable",
"variable",
"(collection",
"of",
"parameters)",
"of",
"a",
"particular",
"shape."
] | def create_variable(shape, method='gaussian', wd=False):
return tf.Variable(init_weight(method, shape, wd=wd)) | ['def', 'create_variable(shape,', "method='gaussian',", 'wd=False):', 'return', 'tf.Variable(init_weight(method,', 'shape,', 'wd=wd))'] | 228,164 |
TarrySingh/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | resnet_model.py | batch_norm_relu | batch_norm_relu | Performs a batch normalization followed by a ReLU. | [
"Performs",
"a",
"batch",
"normalization",
"followed",
"by",
"a",
"ReLU."
] | def batch_norm_relu(inputs, is_training, data_format):
inputs = tf.layers.batch_normalization(inputs=inputs, axis=1 if data_format == 'channels_first' else 3, momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True, scale=True, training=is_training, fused=True)
inputs = tf.nn.relu(inputs)
retur... | ['def', 'batch_norm_relu(inputs,', 'is_training,', 'data_format):', 'inputs', '=', 'tf.layers.batch_normalization(inputs=inputs,', 'axis=1', 'if', 'data_format', '==', "'channels_first'", 'else', '3,', 'momentum=_BATCH_NORM_DECAY,', 'epsilon=_BATCH_NORM_EPSILON,', 'center=True,', 'scale=True,', 'training=is_training,',... | 20,148 |
prouast/deep-intake-detection | oreba_main.py | run_oreba | run_oreba | Run OREBA model training and eval loop. | [
"Run",
"OREBA",
"model",
"training",
"and",
"eval",
"loop."
] | def run_oreba(flags_obj):
flags = tf.contrib.training.HParams(base_learning_rate=FLAGS.base_learning_rate, batch_size=FLAGS.batch_size, dtype=get_tf_dtype(FLAGS.dtype), eval_dir=FLAGS.eval_dir, finetune_only=FLAGS.finetune_only, label_category=get_label_category(FLAGS.label_category), mode=FLAGS.mode, model_dir=FLA... | ['def', 'run_oreba(flags_obj):', 'flags', '=', 'tf.contrib.training.HParams(base_learning_rate=FLAGS.base_learning_rate,', 'batch_size=FLAGS.batch_size,', 'dtype=get_tf_dtype(FLAGS.dtype),', 'eval_dir=FLAGS.eval_dir,', 'finetune_only=FLAGS.finetune_only,', 'label_category=get_label_category(FLAGS.label_category),', 'mo... | 517,233 |
opendilab/DI-star | maps_test.py | get_maps | get_maps | Test only a few random maps to minimize time. | [
"Test",
"only",
"a",
"few",
"random",
"maps",
"to",
"minimize",
"time."
] | def get_maps(count=None, filter_fn=None):
all_maps = {k: v for (k, v) in maps.get_maps().items() if filter_fn is None or filter_fn(v)}
count = count or len(all_maps)
return sorted(random.sample(all_maps.keys(), min(count, len(all_maps)))) | ['def', 'get_maps(count=None,', 'filter_fn=None):', 'all_maps', '=', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'maps.get_maps().items()', 'if', 'filter_fn', 'is', 'None', 'or', 'filter_fn(v)}', 'count', '=', 'count', 'or', 'len(all_maps)', 'return', 'sorted(random.sample(all_maps.keys(),', 'min(count,', 'len(all_maps))))'] | 184,830 |
sunfanyunn/InfoGraph | dim_losses.py | multi_nce_loss | multi_nce_loss | Used for multiple globals. | [
"Used",
"for",
"multiple",
"globals."
] | def multi_nce_loss(l, m):
(N, units, n_locals) = l.size()
(_, _, n_multis) = m.size()
l = l.view(N, units, n_locals)
m = m.view(N, units, n_multis)
l_p = l.permute(0, 2, 1)
m_p = m.permute(0, 2, 1)
u_p = torch.matmul(l_p, m).unsqueeze(2)
l_n = l_p.reshape(-1, units)
m_n = m_p.reshape... | ['def', 'multi_nce_loss(l,', 'm):', '(N,', 'units,', 'n_locals)', '=', 'l.size()', '(_,', '_,', 'n_multis)', '=', 'm.size()', 'l', '=', 'l.view(N,', 'units,', 'n_locals)', 'm', '=', 'm.view(N,', 'units,', 'n_multis)', 'l_p', '=', 'l.permute(0,', '2,', '1)', 'm_p', '=', 'm.permute(0,', '2,', '1)', 'u_p', '=', 'torch.mat... | 229,819 |
weimin17/Object-Detection_HelmetDetection | benchmark_uploader.py | BigQueryUploader.upload_benchmark_run_file | upload_benchmark_run_file | Upload benchmark run information to Bigquery from input json file. | [
"Upload",
"benchmark",
"run",
"information",
"to",
"Bigquery",
"from",
"input",
"json",
"file."
] | def upload_benchmark_run_file(self, dataset_name, table_name, run_id, run_json_file):
with tf.gfile.GFile(run_json_file) as f:
benchmark_json = json.load(f)
self.upload_benchmark_run_json(dataset_name, table_name, run_id, benchmark_json) | ['def', 'upload_benchmark_run_file(self,', 'dataset_name,', 'table_name,', 'run_id,', 'run_json_file):', 'with', 'tf.gfile.GFile(run_json_file)', 'as', 'f:', 'benchmark_json', '=', 'json.load(f)', 'self.upload_benchmark_run_json(dataset_name,', 'table_name,', 'run_id,', 'benchmark_json)'] | 748,538 |
devashish-patel/webcam-motion-detector | buffer.py | Buffer.save_to_undo_stack | save_to_undo_stack | Safe current state (input text and cursor position), so that we can restore it by calling undo. | [
"Safe",
"current",
"state",
"(input",
"text",
"and",
"cursor",
"position),",
"so",
"that",
"we",
"can",
"restore",
"it",
"by",
"calling",
"undo."
] | def save_to_undo_stack(self, clear_redo_stack=True):
if self._undo_stack and self._undo_stack[-1][0] == self.text:
self._undo_stack[-1] = (self._undo_stack[-1][0], self.cursor_position)
else:
self._undo_stack.append((self.text, self.cursor_position))
if clear_redo_stack:
self._redo_s... | ['def', 'save_to_undo_stack(self,', 'clear_redo_stack=True):', 'if', 'self._undo_stack', 'and', 'self._undo_stack[-1][0]', '==', 'self.text:', 'self._undo_stack[-1]', '=', '(self._undo_stack[-1][0],', 'self.cursor_position)', 'else:', 'self._undo_stack.append((self.text,', 'self.cursor_position))', 'if', 'clear_redo_st... | 983,652 |
Ruturaj123/Flowchart-Detection | variables.py | Variable.device | device | The device of this variable. | [
"The",
"device",
"of",
"this",
"variable."
] | def device(self):
return self._variable.device | ['def', 'device(self):', 'return', 'self._variable.device'] | 606,186 |
locationlabs/mockredis | client.py | MockRedis.getbit | getbit | Returns the bit value at ``offset`` in ``key``. | [
"Returns",
"the",
"bit",
"value",
"at",
"``offset``",
"in",
"``key``."
] | def getbit(self, key, offset):
key = self._encode(key)
(index, bits, mask) = self._get_bits_and_offset(key, offset)
if index >= len(bits):
return 0
return 1 if bits[index] & mask else 0 | ['def', 'getbit(self,', 'key,', 'offset):', 'key', '=', 'self._encode(key)', '(index,', 'bits,', 'mask)', '=', 'self._get_bits_and_offset(key,', 'offset)', 'if', 'index', '>=', 'len(bits):', 'return', '0', 'return', '1', 'if', 'bits[index]', '&', 'mask', 'else', '0'] | 240,627 |
sony/nnabla-rl | test_xql.py | TestXQL.test_run_offline_training | test_run_offline_training | Check that no error occurs when calling offline training. | [
"Check",
"that",
"no",
"error",
"occurs",
"when",
"calling",
"offline",
"training."
] | def test_run_offline_training(self):
batch_size = 5
dummy_env = E.DummyContinuous()
config = A.XQLConfig(batch_size=batch_size)
xql = A.XQL(dummy_env, config=config)
experiences = generate_dummy_experiences(dummy_env, batch_size)
buffer = ReplayBuffer()
buffer.append_all(experiences)
xql... | ['def', 'test_run_offline_training(self):', 'batch_size', '=', '5', 'dummy_env', '=', 'E.DummyContinuous()', 'config', '=', 'A.XQLConfig(batch_size=batch_size)', 'xql', '=', 'A.XQL(dummy_env,', 'config=config)', 'experiences', '=', 'generate_dummy_experiences(dummy_env,', 'batch_size)', 'buffer', '=', 'ReplayBuffer()',... | 727,470 |
jogisuda/QuantumSentenceTransformer | QuantumSentenceTransformer.py | H_layer | H_layer | Layer of single-qubit Hadamard gates. | [
"Layer",
"of",
"single-qubit",
"Hadamard",
"gates."
] | def H_layer(nqubits):
for idx in range(nqubits):
qml.Hadamard(wires=idx) | ['def', 'H_layer(nqubits):', 'for', 'idx', 'in', 'range(nqubits):', 'qml.Hadamard(wires=idx)'] | 835,531 |
agoragames/haigha | channel.py | Channel.synchronous | synchronous | Return if this channel is acting synchronous, of its own accord or because the connection is synchronous. | [
"Return",
"if",
"this",
"channel",
"is",
"acting",
"synchronous,",
"of",
"its",
"own",
"accord",
"or",
"because",
"the",
"connection",
"is",
"synchronous."
] | def synchronous(self):
return self._synchronous or self._connection.synchronous | ['def', 'synchronous(self):', 'return', 'self._synchronous', 'or', 'self._connection.synchronous'] | 234,528 |
opendilab/DI-star | renderer_human.py | RendererHuman.render_thread | render_thread | A render loop that pulls observations off the queue to render. | [
"A",
"render",
"loop",
"that",
"pulls",
"observations",
"off",
"the",
"queue",
"to",
"render."
] | def render_thread(self):
obs = True
while obs:
obs = self._obs_queue.get()
if obs:
for alert in obs.observation.alerts:
self._alerts[sc_pb.Alert.Name(alert)] = time.time()
for err in obs.action_errors:
if err.result != sc_err.Success:
... | ['def', 'render_thread(self):', 'obs', '=', 'True', 'while', 'obs:', 'obs', '=', 'self._obs_queue.get()', 'if', 'obs:', 'for', 'alert', 'in', 'obs.observation.alerts:', 'self._alerts[sc_pb.Alert.Name(alert)]', '=', 'time.time()', 'for', 'err', 'in', 'obs.action_errors:', 'if', 'err.result', '!=', 'sc_err.Success:', 'se... | 184,800 |
blakeblackshear/frigate | test_birdseye.py | TestBirdseye.test_4x3 | test_4x3 | Test 4x3 aspect ratio works as expected for birdseye. | [
"Test",
"4x3",
"aspect",
"ratio",
"works",
"as",
"expected",
"for",
"birdseye."
] | def test_4x3(self):
width = 1280
height = 960
(canvas_width, canvas_height) = get_canvas_shape(width, height)
assert canvas_width == width
assert canvas_height == height | ['def', 'test_4x3(self):', 'width', '=', '1280', 'height', '=', '960', '(canvas_width,', 'canvas_height)', '=', 'get_canvas_shape(width,', 'height)', 'assert', 'canvas_width', '==', 'width', 'assert', 'canvas_height', '==', 'height'] | 564,489 |
weimin17/Object-Detection_HelmetDetection | graph_builder_test.py | GraphBuilderTest.assertEmpty | assertEmpty | Assert that an object has zero length. | [
"Assert",
"that",
"an",
"object",
"has",
"zero",
"length."
] | def assertEmpty(self, container, msg=None):
if not isinstance(container, collections.Sized):
self.fail('Expected a Sized object, got: {!r}'.format(type(container).__name__), msg)
if len(container):
self.fail('{!r} has length of {}.'.format(container, len(container)), msg) | ['def', 'assertEmpty(self,', 'container,', 'msg=None):', 'if', 'not', 'isinstance(container,', 'collections.Sized):', "self.fail('Expected", 'a', 'Sized', 'object,', 'got:', "{!r}'.format(type(container).__name__),", 'msg)', 'if', 'len(container):', "self.fail('{!r}", 'has', 'length', 'of', "{}.'.format(container,", 'l... | 753,321 |
ludwig-ai/ludwig | test_preprocessing.py | test_seq_features_max_sequence_length | test_seq_features_max_sequence_length | Tests that a sequence feature has the correct max_sequence_length in metadata and prepocessed data. | [
"Tests",
"that",
"a",
"sequence",
"feature",
"has",
"the",
"correct",
"max_sequence_length",
"in",
"metadata",
"and",
"prepocessed",
"data."
] | def test_seq_features_max_sequence_length(csv_filename, tmpdir, feature_type, max_len, sequence_length, max_sequence_length, sequence_length_expected):
feat = feature_type(encoder={'max_len': max_len}, preprocessing={'sequence_length': sequence_length, 'max_sequence_length': max_sequence_length})
input_features... | ['def', 'test_seq_features_max_sequence_length(csv_filename,', 'tmpdir,', 'feature_type,', 'max_len,', 'sequence_length,', 'max_sequence_length,', 'sequence_length_expected):', 'feat', '=', "feature_type(encoder={'max_len':", 'max_len},', "preprocessing={'sequence_length':", 'sequence_length,', "'max_sequence_length':"... | 617,273 |
deepmind/dm_control | lqr.py | lqr_6_2 | lqr_6_2 | Returns an LQR environment with 6 bodies of which first 2 are actuated. | [
"Returns",
"an",
"LQR",
"environment",
"with",
"6",
"bodies",
"of",
"which",
"first",
"2",
"are",
"actuated."
] | def lqr_6_2(time_limit=_DEFAULT_TIME_LIMIT, random=None, environment_kwargs=None):
return _make_lqr(n_bodies=6, n_actuators=2, control_cost_coef=_CONTROL_COST_COEF, time_limit=time_limit, random=random, environment_kwargs=environment_kwargs) | ['def', 'lqr_6_2(time_limit=_DEFAULT_TIME_LIMIT,', 'random=None,', 'environment_kwargs=None):', 'return', '_make_lqr(n_bodies=6,', 'n_actuators=2,', 'control_cost_coef=_CONTROL_COST_COEF,', 'time_limit=time_limit,', 'random=random,', 'environment_kwargs=environment_kwargs)'] | 166,401 |
openvinotoolkit/training_extensions | argument_checks.py | check_dictionary_keys_values_type | check_dictionary_keys_values_type | Function raises ValueError exception if dictionary key or value has unexpected type. | [
"Function",
"raises",
"ValueError",
"exception",
"if",
"dictionary",
"key",
"or",
"value",
"has",
"unexpected",
"type."
] | def check_dictionary_keys_values_type(parameter, parameter_name, expected_key_class, expected_value_class):
for (key, value) in parameter.items():
check_parameter_type(parameter=key, parameter_name=f'key in {parameter_name}', expected_type=expected_key_class)
check_parameter_type(parameter=value, pa... | ['def', 'check_dictionary_keys_values_type(parameter,', 'parameter_name,', 'expected_key_class,', 'expected_value_class):', 'for', '(key,', 'value)', 'in', 'parameter.items():', 'check_parameter_type(parameter=key,', "parameter_name=f'key", 'in', "{parameter_name}',", 'expected_type=expected_key_class)', 'check_paramet... | 918,845 |
Dsajeet/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | model.py | Model.create_base | create_base | Creates a base part of the Model (no gradients, losses or summaries). | [
"Creates",
"a",
"base",
"part",
"of",
"the",
"Model",
"(no",
"gradients,",
"losses",
"or",
"summaries)."
] | def create_base(self, images, labels_one_hot, scope='AttentionOcr_v1', reuse=None):
logging.debug('images: %s', images)
is_training = labels_one_hot is not None
with tf.variable_scope(scope, reuse=reuse):
views = tf.split(value=images, num_or_size_splits=self._params.num_views, axis=2)
loggi... | ['def', 'create_base(self,', 'images,', 'labels_one_hot,', "scope='AttentionOcr_v1',", 'reuse=None):', "logging.debug('images:", "%s',", 'images)', 'is_training', '=', 'labels_one_hot', 'is', 'not', 'None', 'with', 'tf.variable_scope(scope,', 'reuse=reuse):', 'views', '=', 'tf.split(value=images,', 'num_or_size_splits=... | 14,583 |
deepmind/acme | learning.py | BCLearner.state | state | Returns the stateful parts of the learner for checkpointing. | [
"Returns",
"the",
"stateful",
"parts",
"of",
"the",
"learner",
"for",
"checkpointing."
] | def state(self):
return {'network': self._network, 'optimizer': self._optimizer, 'num_steps': self._num_steps} | ['def', 'state(self):', 'return', "{'network':", 'self._network,', "'optimizer':", 'self._optimizer,', "'num_steps':", 'self._num_steps}'] | 7,675 |
datature/portal | global_store.py | GlobalStore.query_autosave | query_autosave | Query the autosave flag during runtime. | [
"Query",
"the",
"autosave",
"flag",
"during",
"runtime."
] | def query_autosave(self):
return '1' if self.caching_system else '0' | ['def', 'query_autosave(self):', 'return', "'1'", 'if', 'self.caching_system', 'else', "'0'"] | 820,944 |
TarrySingh/Artificial-Intelligence-Deep-Learning---Tutorials | utils.py | rms_scaling | rms_scaling | Vectorizes and scales a tensor of gradients. | [
"Vectorizes",
"and",
"scales",
"a",
"tensor",
"of",
"gradients."
] | def rms_scaling(gradient, decay, ms, update_ms=True):
grad_vec = tf.reshape(gradient, [-1, 1])
if update_ms:
ms = new_mean_squared(grad_vec, decay, ms)
scaled_gradient = asinh(grad_vec / tf.sqrt(ms + 1e-16))
return (scaled_gradient, ms) | ['def', 'rms_scaling(gradient,', 'decay,', 'ms,', 'update_ms=True):', 'grad_vec', '=', 'tf.reshape(gradient,', '[-1,', '1])', 'if', 'update_ms:', 'ms', '=', 'new_mean_squared(grad_vec,', 'decay,', 'ms)', 'scaled_gradient', '=', 'asinh(grad_vec', '/', 'tf.sqrt(ms', '+', '1e-16))', 'return', '(scaled_gradient,', 'ms)'] | 55,543 |
bnpy/bnpy | TestFiniteTopicModel_Shared.py | Test.run_speed_benchmark | run_speed_benchmark | Compare speed of different algorithms. | [
"Compare",
"speed",
"of",
"different",
"algorithms."
] | def run_speed_benchmark(self, method='all', nRepeat=3):
if method == 'all':
Results = self.run_all_with_timer(nRepeat=nRepeat)
elif method == 'parallel':
ptime = self.run_with_timer('run_parallel', nRepeat=nRepeat)
Results = dict(parallel_time=ptime)
elif method == 'serial':
... | ['def', 'run_speed_benchmark(self,', "method='all',", 'nRepeat=3):', 'if', 'method', '==', "'all':", 'Results', '=', 'self.run_all_with_timer(nRepeat=nRepeat)', 'elif', 'method', '==', "'parallel':", 'ptime', '=', "self.run_with_timer('run_parallel',", 'nRepeat=nRepeat)', 'Results', '=', 'dict(parallel_time=ptime)', 'e... | 465,609 |
MatthewWilletts/GM-DGM | dgm.py | discreteUniformKL_np_probs | discreteUniformKL_np_probs | KL divergence for discrete/categorical probabilties returns KL(q||p) where q is a np array of probabilities and p, not given, is uniform. | [
"KL",
"divergence",
"for",
"discrete/categorical",
"probabilties",
"returns",
"KL(q||p)",
"where",
"q",
"is",
"a",
"np",
"array",
"of",
"probabilities",
"and",
"p,",
"not",
"given,",
"is",
"uniform."
] | def discreteUniformKL_np_probs(probs, n_size, dim=-1):
return np.sum(probs * np.log(probs + 1e-09), axis=dim) + np.log(n_size) | ['def', 'discreteUniformKL_np_probs(probs,', 'n_size,', 'dim=-1):', 'return', 'np.sum(probs', '*', 'np.log(probs', '+', '1e-09),', 'axis=dim)', '+', 'np.log(n_size)'] | 202,507 |
PJLab-ADG/LoGoNet | gaussian_target.py | gaussian2D | gaussian2D | Generate 2D gaussian kernel. | [
"Generate",
"2D",
"gaussian",
"kernel."
] | def gaussian2D(radius, sigma=1, dtype=torch.float32, device='cpu'):
x = torch.arange(-radius, radius + 1, dtype=dtype, device=device).view(1, -1)
y = torch.arange(-radius, radius + 1, dtype=dtype, device=device).view(-1, 1)
h = (-(x * x + y * y) / (2 * sigma * sigma)).exp()
h[h < torch.finfo(h.dtype).ep... | ['def', 'gaussian2D(radius,', 'sigma=1,', 'dtype=torch.float32,', "device='cpu'):", 'x', '=', 'torch.arange(-radius,', 'radius', '+', '1,', 'dtype=dtype,', 'device=device).view(1,', '-1)', 'y', '=', 'torch.arange(-radius,', 'radius', '+', '1,', 'dtype=dtype,', 'device=device).view(-1,', '1)', 'h', '=', '(-(x', '*', 'x'... | 615,437 |
jimtin/Stock_Comparison | gen.py | Runner.register_callback | register_callback | Adds ``key`` to the list of callbacks. | [
"Adds",
"``key``",
"to",
"the",
"list",
"of",
"callbacks."
] | def register_callback(self, key):
if self.pending_callbacks is None:
self.pending_callbacks = set()
self.results = {}
if key in self.pending_callbacks:
raise KeyReuseError('key %r is already pending' % (key,))
self.pending_callbacks.add(key) | ['def', 'register_callback(self,', 'key):', 'if', 'self.pending_callbacks', 'is', 'None:', 'self.pending_callbacks', '=', 'set()', 'self.results', '=', '{}', 'if', 'key', 'in', 'self.pending_callbacks:', 'raise', "KeyReuseError('key", '%r', 'is', 'already', "pending'", '%', '(key,))', 'self.pending_callbacks.add(key)'] | 359,031 |
PIYUSH0812/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | util.py | RecursivelyConvertToLuatable | RecursivelyConvertToLuatable | Converts a dictionary to a LuaTable-like T object. | [
"Converts",
"a",
"dictionary",
"to",
"a",
"LuaTable-like",
"T",
"object."
] | def RecursivelyConvertToLuatable(yaml_dict):
if isinstance(yaml_dict, dict):
yaml_dict = T(yaml_dict)
for (key, item) in yaml_dict.iteritems():
if isinstance(item, dict):
yaml_dict[key] = RecursivelyConvertToLuatable(item)
return yaml_dict | ['def', 'RecursivelyConvertToLuatable(yaml_dict):', 'if', 'isinstance(yaml_dict,', 'dict):', 'yaml_dict', '=', 'T(yaml_dict)', 'for', '(key,', 'item)', 'in', 'yaml_dict.iteritems():', 'if', 'isinstance(item,', 'dict):', 'yaml_dict[key]', '=', 'RecursivelyConvertToLuatable(item)', 'return', 'yaml_dict'] | 112,637 |
intel/neural-compressor | util.py | auto_copy | auto_copy | Get an IPEX prepared model and return a fp32 model. | [
"Get",
"an",
"IPEX",
"prepared",
"model",
"and",
"return",
"a",
"fp32",
"model."
] | def auto_copy(module):
from intel_extension_for_pytorch.quantization._quantization_state import AutoQuantizationStateModuleDict
def _nn_sequential_patched_forward(cls, x):
for module in cls:
if not isinstance(module, AutoQuantizationStateModuleDict):
x = module(x)
re... | ['def', 'auto_copy(module):', 'from', 'intel_extension_for_pytorch.quantization._quantization_state', 'import', 'AutoQuantizationStateModuleDict', 'def', '_nn_sequential_patched_forward(cls,', 'x):', 'for', 'module', 'in', 'cls:', 'if', 'not', 'isinstance(module,', 'AutoQuantizationStateModuleDict):', 'x', '=', 'module... | 737,902 |
deepmind/dm_control | tracking.py | ReferencePosesTask.get_reference_ego_bodies_quats | get_reference_ego_bodies_quats | Body quat of the reference relative to the reference root quat. | [
"Body",
"quat",
"of",
"the",
"reference",
"relative",
"to",
"the",
"reference",
"root",
"quat."
] | def get_reference_ego_bodies_quats(self, unused_physics: 'mjcf.Physics'):
time_steps = self._time_step + self._ref_steps
obs = []
quats_for_clip = self._reference_ego_bodies_quats[self._current_clip_index]
for t in time_steps:
if t not in quats_for_clip:
root_quat = self._clip_refere... | ['def', 'get_reference_ego_bodies_quats(self,', 'unused_physics:', "'mjcf.Physics'):", 'time_steps', '=', 'self._time_step', '+', 'self._ref_steps', 'obs', '=', '[]', 'quats_for_clip', '=', 'self._reference_ego_bodies_quats[self._current_clip_index]', 'for', 't', 'in', 'time_steps:', 'if', 't', 'not', 'in', 'quats_for_... | 165,105 |
gunthercox/ChatterBot | api.py | ModelI.choose_random_word | choose_random_word | Randomly select a word that is likely to appear in this context. | [
"Randomly",
"select",
"a",
"word",
"that",
"is",
"likely",
"to",
"appear",
"in",
"this",
"context."
] | def choose_random_word(self, context):
raise NotImplementedError() | ['def', 'choose_random_word(self,', 'context):', 'raise', 'NotImplementedError()'] | 485,492 |
treigerm/WaterNet | model.py | normalise_input | normalise_input | Normalise the features such that all values are in the range [0,1]. | [
"Normalise",
"the",
"features",
"such",
"that",
"all",
"values",
"are",
"in",
"the",
"range",
"[0,1]."
] | def normalise_input(features):
features = features.astype(np.float32)
return np.multiply(features, 1.0 / 255.0) | ['def', 'normalise_input(features):', 'features', '=', 'features.astype(np.float32)', 'return', 'np.multiply(features,', '1.0', '/', '255.0)'] | 372,929 |
Farama-Foundation/Shimmy | test_dm_lab.py | test_check_env | test_check_env | Check that environment pass the gym check_env. | [
"Check",
"that",
"environment",
"pass",
"the",
"gym",
"check_env."
] | def test_check_env(level_name):
observations = ['RGBD']
config = {'width': '640', 'height': '480', 'botCount': '2'}
renderer = 'hardware'
env = deepmind_lab.Lab(level_name, observations, config=config, renderer=renderer)
env = DmLabCompatibilityV0(env)
check_env(env)
env.close() | ['def', 'test_check_env(level_name):', 'observations', '=', "['RGBD']", 'config', '=', "{'width':", "'640',", "'height':", "'480',", "'botCount':", "'2'}", 'renderer', '=', "'hardware'", 'env', '=', 'deepmind_lab.Lab(level_name,', 'observations,', 'config=config,', 'renderer=renderer)', 'env', '=', 'DmLabCompatibilityV... | 901,063 |
pytorch/rl | checkpoint.py | Checkpoint.restore | restore | Restore from latest checkpoint Returns: restored: boolean, True if restored from a checkpoint, False otherwise. | [
"Restore",
"from",
"latest",
"checkpoint",
"Returns:",
"restored:",
"boolean,",
"True",
"if",
"restored",
"from",
"a",
"checkpoint,",
"False",
"otherwise."
] | def restore(self):
latest_checkpoint = tf.train.latest_checkpoint(self._run_dir)
if latest_checkpoint is None:
if self._hparams.test_only:
raise FileNotFoundError('no checkpoint found in %s' % self._run_dir)
return False
self._saver.restore(self._sess, latest_checkpoint)
with... | ['def', 'restore(self):', 'latest_checkpoint', '=', 'tf.train.latest_checkpoint(self._run_dir)', 'if', 'latest_checkpoint', 'is', 'None:', 'if', 'self._hparams.test_only:', 'raise', "FileNotFoundError('no", 'checkpoint', 'found', 'in', "%s'", '%', 'self._run_dir)', 'return', 'False', 'self._saver.restore(self._sess,', ... | 860,702 |
BioGeek/aima | text.py | ShiftDecoder.score | score | Return a score for text based on how common letters pairs are. | [
"Return",
"a",
"score",
"for",
"text",
"based",
"on",
"how",
"common",
"letters",
"pairs",
"are."
] | def score(self, plaintext):
s = 1.0
for bi in bigrams(plaintext):
s = s * self.P2[bi]
return s | ['def', 'score(self,', 'plaintext):', 's', '=', '1.0', 'for', 'bi', 'in', 'bigrams(plaintext):', 's', '=', 's', '*', 'self.P2[bi]', 'return', 's'] | 86,166 |
mj-will/nessai | test_model.py | test_configure_pool_with_pool_user_n_pool | test_configure_pool_with_pool_user_n_pool | Test configuring the pool when pool is specified but n_pool cannot be determined but the user has specified the value. | [
"Test",
"configuring",
"the",
"pool",
"when",
"pool",
"is",
"specified",
"but",
"n_pool",
"cannot",
"be",
"determined",
"but",
"the",
"user",
"has",
"specified",
"the",
"value."
] | def test_configure_pool_with_pool_user_n_pool(model):
model.allow_vectorised = True
pool = MagicMock()
with patch('nessai.model.get_n_pool', return_value=None) as mock:
Model.configure_pool(model, pool=pool, n_pool=1)
mock.assert_called_once_with(pool)
assert model.pool is pool
assert mo... | ['def', 'test_configure_pool_with_pool_user_n_pool(model):', 'model.allow_vectorised', '=', 'True', 'pool', '=', 'MagicMock()', 'with', "patch('nessai.model.get_n_pool',", 'return_value=None)', 'as', 'mock:', 'Model.configure_pool(model,', 'pool=pool,', 'n_pool=1)', 'mock.assert_called_once_with(pool)', 'assert', 'mode... | 292,334 |
microsoft/nni | public.py | canonical_gpu_indices | canonical_gpu_indices | If ``indices`` is not None, cast it to list of int. | [
"If",
"``indices``",
"is",
"not",
"None,",
"cast",
"it",
"to",
"list",
"of",
"int."
] | def canonical_gpu_indices(indices):
if isinstance(indices, str):
return [int(idx) for idx in indices.split(',')]
if isinstance(indices, int):
return [indices]
return indices | ['def', 'canonical_gpu_indices(indices):', 'if', 'isinstance(indices,', 'str):', 'return', '[int(idx)', 'for', 'idx', 'in', "indices.split(',')]", 'if', 'isinstance(indices,', 'int):', 'return', '[indices]', 'return', 'indices'] | 728,620 |
jbwang1997/CrossKD | boxinst_head.py | BoxInstMaskHead.get_pairwise_affinity | get_pairwise_affinity | Compute the pairwise affinity for each pixel. | [
"Compute",
"the",
"pairwise",
"affinity",
"for",
"each",
"pixel."
] | def get_pairwise_affinity(self, mask_logits: Tensor) -> Tensor:
log_fg_prob = F.logsigmoid(mask_logits).unsqueeze(1)
log_bg_prob = F.logsigmoid(-mask_logits).unsqueeze(1)
log_fg_prob_unfold = unfold_wo_center(log_fg_prob, kernel_size=self.pairwise_size, dilation=self.pairwise_dilation)
log_bg_prob_unfol... | ['def', 'get_pairwise_affinity(self,', 'mask_logits:', 'Tensor)', '->', 'Tensor:', 'log_fg_prob', '=', 'F.logsigmoid(mask_logits).unsqueeze(1)', 'log_bg_prob', '=', 'F.logsigmoid(-mask_logits).unsqueeze(1)', 'log_fg_prob_unfold', '=', 'unfold_wo_center(log_fg_prob,', 'kernel_size=self.pairwise_size,', 'dilation=self.pa... | 490,967 |
danamyu/hedgehog_detector | bulk_component.py | BulkFeatureExtractorComponentBuilder.build_greedy_training | build_greedy_training | Extracts features and advances a batch using the oracle path. | [
"Extracts",
"features",
"and",
"advances",
"a",
"batch",
"using",
"the",
"oracle",
"path."
] | def build_greedy_training(self, state, network_states):
logging.info('Building component: %s', self.spec.name)
stride = state.current_batch_size * self.training_beam_size
with tf.variable_scope(self.name, reuse=True):
(state.handle, fixed_embeddings) = fetch_differentiable_fixed_embeddings(self, sta... | ['def', 'build_greedy_training(self,', 'state,', 'network_states):', "logging.info('Building", 'component:', "%s',", 'self.spec.name)', 'stride', '=', 'state.current_batch_size', '*', 'self.training_beam_size', 'with', 'tf.variable_scope(self.name,', 'reuse=True):', '(state.handle,', 'fixed_embeddings)', '=', 'fetch_di... | 590,542 |
rlworkgroup/garage | differentiable_sgd.py | DifferentiableSGD.zero_grad | zero_grad | Sets gradients of all model parameters to zero. | [
"Sets",
"gradients",
"of",
"all",
"model",
"parameters",
"to",
"zero."
] | def zero_grad(self):
for param in self.module.parameters():
if param.grad is not None:
param.grad.detach_()
param.grad.zero_() | ['def', 'zero_grad(self):', 'for', 'param', 'in', 'self.module.parameters():', 'if', 'param.grad', 'is', 'not', 'None:', 'param.grad.detach_()', 'param.grad.zero_()'] | 200,801 |
microsoft/maro | event_buffer.py | EventBuffer.gen_cascade_event | gen_cascade_event | Generate an cascade event that used to hold immediate events that run right after current event. | [
"Generate",
"an",
"cascade",
"event",
"that",
"used",
"to",
"hold",
"immediate",
"events",
"that",
"run",
"right",
"after",
"current",
"event."
] | def gen_cascade_event(self, tick: int, event_type: object, payload: object) -> CascadeEvent:
return cast(CascadeEvent, self._event_pool.gen(tick, event_type, payload, is_cascade=True)) | ['def', 'gen_cascade_event(self,', 'tick:', 'int,', 'event_type:', 'object,', 'payload:', 'object)', '->', 'CascadeEvent:', 'return', 'cast(CascadeEvent,', 'self._event_pool.gen(tick,', 'event_type,', 'payload,', 'is_cascade=True))'] | 628,446 |
algoterranean/3dgan | summaries.py | summarize_collection | summarize_collection | Add a scalar summary for every tensor in a collection. | [
"Add",
"a",
"scalar",
"summary",
"for",
"every",
"tensor",
"in",
"a",
"collection."
] | def summarize_collection(name, scope):
collection = tf.get_collection(name, scope)
for x in collection:
tf.summary.scalar(hem.tensor_name(x), x)
return collection | ['def', 'summarize_collection(name,', 'scope):', 'collection', '=', 'tf.get_collection(name,', 'scope)', 'for', 'x', 'in', 'collection:', 'tf.summary.scalar(hem.tensor_name(x),', 'x)', 'return', 'collection'] | 404,893 |
tamerthamoqa/facenet-realtime-face-recognition | utils.py | allowed_file | allowed_file | Checks if filename extension is one of the allowed filename extensions for upload. | [
"Checks",
"if",
"filename",
"extension",
"is",
"one",
"of",
"the",
"allowed",
"filename",
"extensions",
"for",
"upload."
] | def allowed_file(filename, allowed_set):
check = '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_set
return check | ['def', 'allowed_file(filename,', 'allowed_set):', 'check', '=', "'.'", 'in', 'filename', 'and', "filename.rsplit('.',", '1)[1].lower()', 'in', 'allowed_set', 'return', 'check'] | 178,891 |
Eric3911/OpenAGI | data_simulation_utils.py | get_background_noise | get_background_noise | Augment with background noise (inserting ambient background noise up to the desired SNR for the full clip). | [
"Augment",
"with",
"background",
"noise",
"(inserting",
"ambient",
"background",
"noise",
"up",
"to",
"the",
"desired",
"SNR",
"for",
"the",
"full",
"clip)."
] | def get_background_noise(len_array: int, power_array: float, noise_samples: list, audio_read_buffer_dict: dict, snr_min: float, snr_max: float, background_noise_snr: float, seed: int, device: torch.device):
np.random.seed(seed)
bg_array = torch.zeros(len_array).to(device)
(desired_avg_power_noise, desired_s... | ['def', 'get_background_noise(len_array:', 'int,', 'power_array:', 'float,', 'noise_samples:', 'list,', 'audio_read_buffer_dict:', 'dict,', 'snr_min:', 'float,', 'snr_max:', 'float,', 'background_noise_snr:', 'float,', 'seed:', 'int,', 'device:', 'torch.device):', 'np.random.seed(seed)', 'bg_array', '=', 'torch.zeros(l... | 272,845 |
sek788432/Waymo-2D-Object-Detection | data_download.py | download_and_extract | download_and_extract | Extract files from downloaded compressed archive file. | [
"Extract",
"files",
"from",
"downloaded",
"compressed",
"archive",
"file."
] | def download_and_extract(path, url, input_filename, target_filename):
input_file = find_file(path, input_filename)
target_file = find_file(path, target_filename)
if input_file and target_file:
logging.info('Already downloaded and extracted %s.', url)
return (input_file, target_file)
comp... | ['def', 'download_and_extract(path,', 'url,', 'input_filename,', 'target_filename):', 'input_file', '=', 'find_file(path,', 'input_filename)', 'target_file', '=', 'find_file(path,', 'target_filename)', 'if', 'input_file', 'and', 'target_file:', "logging.info('Already", 'downloaded', 'and', 'extracted', "%s.',", 'url)',... | 972,834 |
lakraj/Udacity-Artificial-Intelligence-Nanodegree-Projects | game_agent.py | MinimaxPlayer.min_value | min_value | Return the value for a win (+1) if the game is over, otherwise return the minimum value over all legal child nodes. | [
"Return",
"the",
"value",
"for",
"a",
"win",
"(+1)",
"if",
"the",
"game",
"is",
"over,",
"otherwise",
"return",
"the",
"minimum",
"value",
"over",
"all",
"legal",
"child",
"nodes."
] | def min_value(self, game, depth):
if self.time_left() < self.TIMER_THRESHOLD:
raise SearchTimeout()
if self.terminal_test(game):
return 1
if depth <= 0:
return self.score(game, self)
v = float('inf')
for m in game.get_legal_moves():
v = min(v, self.max_value(game.fore... | ['def', 'min_value(self,', 'game,', 'depth):', 'if', 'self.time_left()', '<', 'self.TIMER_THRESHOLD:', 'raise', 'SearchTimeout()', 'if', 'self.terminal_test(game):', 'return', '1', 'if', 'depth', '<=', '0:', 'return', 'self.score(game,', 'self)', 'v', '=', "float('inf')", 'for', 'm', 'in', 'game.get_legal_moves():', 'v... | 427,949 |
aqeelanwar/PEDRA | transformations.py | Arcball.constrain | constrain | Return state of constrain to axis mode. | [
"Return",
"state",
"of",
"constrain",
"to",
"axis",
"mode."
] | def constrain(self):
return self._constrain | ['def', 'constrain(self):', 'return', 'self._constrain'] | 279,683 |
matsu0228/nlp-jp | backend_bases.py | FigureCanvasBase.draw_event | draw_event | Pass a `DrawEvent` to all functions connected to ``draw_event``. | [
"Pass",
"a",
"`DrawEvent`",
"to",
"all",
"functions",
"connected",
"to",
"``draw_event``."
] | def draw_event(self, renderer):
s = 'draw_event'
event = DrawEvent(s, self, renderer)
self.callbacks.process(s, event) | ['def', 'draw_event(self,', 'renderer):', 's', '=', "'draw_event'", 'event', '=', 'DrawEvent(s,', 'self,', 'renderer)', 'self.callbacks.process(s,', 'event)'] | 788,423 |
myothida/Supervised-Machine-Learning | test_calibration.py | test_calibrated_classifier_error_base_estimator | test_calibrated_classifier_error_base_estimator | Check that we raise an error is a user set both `base_estimator` and `estimator`. | [
"Check",
"that",
"we",
"raise",
"an",
"error",
"is",
"a",
"user",
"set",
"both",
"`base_estimator`",
"and",
"`estimator`."
] | def test_calibrated_classifier_error_base_estimator(data):
calibrated_classifier = CalibratedClassifierCV(base_estimator=LogisticRegression(), estimator=LogisticRegression())
with pytest.raises(ValueError, match='Both `base_estimator` and `estimator`'):
calibrated_classifier.fit(*data) | ['def', 'test_calibrated_classifier_error_base_estimator(data):', 'calibrated_classifier', '=', 'CalibratedClassifierCV(base_estimator=LogisticRegression(),', 'estimator=LogisticRegression())', 'with', 'pytest.raises(ValueError,', "match='Both", '`base_estimator`', 'and', "`estimator`'):", 'calibrated_classifier.fit(*d... | 364,630 |
voxel51/fiftyone | utils.py | create_implied_field | create_implied_field | Creates the field for the given value. | [
"Creates",
"the",
"field",
"for",
"the",
"given",
"value."
] | def create_implied_field(path, value, dynamic=False):
field_name = path.rsplit('.', 1)[-1]
kwargs = get_implied_field_kwargs(value, dynamic=dynamic)
return create_field(field_name, **kwargs) | ['def', 'create_implied_field(path,', 'value,', 'dynamic=False):', 'field_name', '=', "path.rsplit('.',", '1)[-1]', 'kwargs', '=', 'get_implied_field_kwargs(value,', 'dynamic=dynamic)', 'return', 'create_field(field_name,', '**kwargs)'] | 583,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.