uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
6a4e2b0c3c3228ec5792bf14
train
class
class BatchNorm(KL.BatchNormalization): """Extends the Keras BatchNormalization class to allow a central place to make changes if needed. Batch normalization has a negative effect on training if batches are small so this layer is often frozen (via setting in Config class) and functions as lin...
class BatchNorm(KL.BatchNormalization):
"""Extends the Keras BatchNormalization class to allow a central place to make changes if needed. Batch normalization has a negative effect on training if batches are small so this layer is often frozen (via setting in Config class) and functions as linear layer. """ def call(self, i...
.5f} max: {:10.5f}".format(array.min(),array.max())) else: text += ("min: {:10} max: {:10}".format("","")) text += " {}".format(array.dtype) print(text) class BatchNorm(KL.BatchNormalization):
64
64
150
8
56
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
BatchNorm
BatchNorm
53
68
53
53
8087851c867f2a88b7a566e5ef9d758dd1a0adb0
bigcode/the-stack
train
ce2c739fa27035e14bf544ef
train
function
def compute_backbone_shapes(config, image_shape): """Computes the width and height of each stage of the backbone network. Returns: [N, (height, width)]. Where N is the number of stages """ if callable(config.BACKBONE): return config.COMPUTE_BACKBONE_SHAPE(image_shape) # Cu...
def compute_backbone_shapes(config, image_shape):
"""Computes the width and height of each stage of the backbone network. Returns: [N, (height, width)]. Where N is the number of stages """ if callable(config.BACKBONE): return config.COMPUTE_BACKBONE_SHAPE(image_shape) # Currently supports ResNet only assert config.BAC...
the normal mode False: Freeze BN layers. Good when batch size is small True: (don't use). Set layer in training mode even when making inferences """ return super(self.__class__, self).call(inputs, training=training) def compute_backbone_shapes(config, image_shape):
64
64
140
10
54
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
compute_backbone_shapes
compute_backbone_shapes
71
85
71
71
c451ac4f64e9d4cc9b38ca7cecf227b6cf9942dd
bigcode/the-stack
train
83a887900b2a92a80e70d817
train
function
def compose_image_meta(image_id, original_image_shape, image_shape, window, scale, active_class_ids): """Takes attributes of an image and puts them in one 1D array. image_id: An int ID of the image. Useful for debugging. original_image_shape: [H, W, C] before resizing or padding...
def compose_image_meta(image_id, original_image_shape, image_shape, window, scale, active_class_ids):
"""Takes attributes of an image and puts them in one 1D array. image_id: An int ID of the image. Useful for debugging. original_image_shape: [H, W, C] before resizing or padding. image_shape: [H, W, C] after resizing and padding window: (y1, x1, y2, x2) in pixels. The area of the image where t...
and log the results. outputs_np = OrderedDict([(k, v) for k, v in zip(outputs.keys(), outputs_np)]) for k, v in outputs_np.items(): log(k, v) return outputs_np ############################################################ # Data Formattin...
85
85
285
23
61
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
compose_image_meta
compose_image_meta
2,732
2,754
2,732
2,733
6a2d31a966eefbd106ed6d267b52ff114a676545
bigcode/the-stack
train
b0af9c33a42c51679af75dd8
train
function
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), use_bias=True, train_bn=True): """conv_block is the block that has a conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at ...
def conv_block(input_tensor, kernel_size, filters, stage, block, strides=(2, 2), use_bias=True, train_bn=True):
"""conv_block is the block that has a conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the nb_filters of 3 conv layer at main path stage: integer, current stage ...
use_bias)(x) x = BatchNorm(name=bn_name_base + '2b')(x, training=train_bn) x = KL.Activation('relu')(x) x = KL.Conv2D(nb_filter3, (1, 1), name=conv_name_base + '2c', use_bias=use_bias)(x) x = BatchNorm(name=bn_name_base + '2c')(x, training=train_bn) x = KL.Add()([x, input...
166
166
555
31
134
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
conv_block
conv_block
130
168
130
131
96a53bb13d9d37d544527c5c6287b7900557ff02
bigcode/the-stack
train
88e89ea84690059350820fc5
train
function
def batch_pack_graph(x, counts, num_rows): """Picks different number of values from each row in x depending on the values in counts. """ outputs = [] for i in range(num_rows): outputs.append(x[i, :counts[i]]) return tf.concat(outputs, axis=0)
def batch_pack_graph(x, counts, num_rows):
"""Picks different number of values from each row in x depending on the values in counts. """ outputs = [] for i in range(num_rows): outputs.append(x[i, :counts[i]]) return tf.concat(outputs, axis=0)
the rows to keep """ non_zeros = tf.cast(tf.reduce_sum(tf.abs(boxes), axis=1), tf.bool) boxes = tf.boolean_mask(boxes, non_zeros, name=name) return boxes, non_zeros def batch_pack_graph(x, counts, num_rows):
64
64
68
11
52
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
batch_pack_graph
batch_pack_graph
2,834
2,841
2,834
2,834
b8dab53c84f72a2efb09b8528755f820cb140d5b
bigcode/the-stack
train
1a75c873006e446727d6b108
train
function
def build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, gt_masks, config): """Generate targets for training Stage 2 classifier and mask heads. This is not used in normal training. It's useful for debugging or to train the Mask RCNN heads without using the RPN head. Inputs: rpn_rois: [N,...
def build_detection_targets(rpn_rois, gt_class_ids, gt_boxes, gt_masks, config):
"""Generate targets for training Stage 2 classifier and mask heads. This is not used in normal training. It's useful for debugging or to train the Mask RCNN heads without using the RPN head. Inputs: rpn_rois: [N, (y1, x1, y2, x2)] proposal boxes. gt_class_ids: [instance count] Integer cla...
0 mask = mask[:, :, _idx] class_ids = class_ids[_idx] # Bounding boxes. Note that some boxes might be all zeros # if the corresponding mask got cropped out. # bbox: [num_instances, (y1, x1, y2, x2)] bbox = utils.extract_bboxes(mask) # Active classes # Different datasets have d...
256
256
1,886
21
234
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
build_detection_targets
build_detection_targets
1,290
1,443
1,290
1,290
8fa0164b9791f136bcbaa8086848cd85dbe411d1
bigcode/the-stack
train
908058fd6baf7f17de5bfdf8
train
function
def build_rpn_model(anchor_stride, anchors_per_location, depth): """Builds a Keras model of the Region Proposal Network. It wraps the RPN graph so it can be used multiple times with shared weights. anchors_per_location: number of anchors per pixel in the feature map anchor_stride: Controls th...
def build_rpn_model(anchor_stride, anchors_per_location, depth):
"""Builds a Keras model of the Region Proposal Network. It wraps the RPN graph so it can be used multiple times with shared weights. anchors_per_location: number of anchors per pixel in the feature map anchor_stride: Controls the density of anchors. Typically 1 (anchors for ...
pn_bbox_pred')(shared) # Reshape to [batch, anchors, 4] rpn_bbox = KL.Lambda(lambda t: tf.reshape(t, [tf.shape(t)[0], -1, 4]))(x) return [rpn_class_logits, rpn_probs, rpn_bbox] def build_rpn_model(anchor_stride, anchors_per_location, depth):
80
81
273
14
66
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
build_rpn_model
build_rpn_model
875
894
875
875
3926ca194be7518e5eb2871b15a2a444ba884f91
bigcode/the-stack
train
52e9ee03a45b1e30200898be
train
class
class PyramidROIAlign(KE.Layer): """Implements ROI Pooling on multiple levels of the feature pyramid. Params: - pool_shape: [pool_height, pool_width] of the output pooled regions. Usually [7, 7] Inputs: - boxes: [batch, num_boxes, (y1, x1, y2, x2)] in normalized coordinates. P...
class PyramidROIAlign(KE.Layer):
"""Implements ROI Pooling on multiple levels of the feature pyramid. Params: - pool_shape: [pool_height, pool_width] of the output pooled regions. Usually [7, 7] Inputs: - boxes: [batch, num_boxes, (y1, x1, y2, x2)] in normalized coordinates. Possibly padded with zeros if not e...
_clipped"]) # Filter out small boxes # According to Xinlei Chen's paper, this reduces detection accuracy # for small objects, so we're skipping it. # Non-max suppression def nms(boxes, scores): indices = tf.image.non_max_suppression( boxes, ...
256
256
1,159
8
248
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
PyramidROIAlign
PyramidROIAlign
344
450
344
344
8ac3fdb928fde42c0850719dfab0666e35ac6e8b
bigcode/the-stack
train
89bcec0ac24730ff59b8d1e1
train
function
def apply_box_deltas_graph(boxes, deltas): """Applies the given deltas to the given boxes. boxes: [N, (y1, x1, y2, x2)] boxes to update deltas: [N, (dy, dx, log(dh), log(dw))] refinements to apply """ # Convert to y, x, h, w height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - box...
def apply_box_deltas_graph(boxes, deltas):
"""Applies the given deltas to the given boxes. boxes: [N, (y1, x1, y2, x2)] boxes to update deltas: [N, (dy, dx, log(dh), log(dw))] refinements to apply """ # Convert to y, x, h, w height = boxes[:, 2] - boxes[:, 0] width = boxes[:, 3] - boxes[:, 1] center_y = boxes[:, 0] + 0.5 *...
=train_bn) C5 = x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', train_bn=train_bn) else: C5 = None return [C1, C2, C3, C4, C5] ############################################################ # Proposal Layer ############################################################ def...
90
90
300
12
77
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
apply_box_deltas_graph
apply_box_deltas_graph
213
234
213
213
dab58225716a3e00315917ca05d694b3e72d3a7d
bigcode/the-stack
train
009004c2d903fc3e25561066
train
function
def generate_random_rois(image_shape, count, gt_class_ids, gt_boxes): """Generates ROI proposals similar to what a region proposal network would generate. image_shape: [Height, Width, Depth] count: Number of ROIs to generate gt_class_ids: [N] Integer ground truth class IDs gt_boxes: [N, ...
def generate_random_rois(image_shape, count, gt_class_ids, gt_boxes):
"""Generates ROI proposals similar to what a region proposal network would generate. image_shape: [Height, Width, Depth] count: Number of ROIs to generate gt_class_ids: [N] Integer ground truth class IDs gt_boxes: [N, (y1, x1, y2, x2)] Ground truth boxes in pixels. Returns: [count,...
height. # GT Box gt_h = gt[2] - gt[0] gt_w = gt[3] - gt[1] gt_center_y = gt[0] + 0.5 * gt_h gt_center_x = gt[1] + 0.5 * gt_w # Anchor a_h = a[2] - a[0] a_w = a[3] - a[1] a_center_y = a[0] + 0.5 * a_h a_center_x = a[1] + 0.5 * a_w ...
256
256
1,060
17
238
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
generate_random_rois
generate_random_rois
1,557
1,628
1,557
1,557
b9359928d3668bf29fbc831ea712eb563d437101
bigcode/the-stack
train
b628455418edb32ad53c6938
train
class
class DetectionTargetLayer(KE.Layer): """Subsamples proposals and generates target box refinement, class_ids, and masks for each. Inputs: proposals: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might be zero padded if there are not enough proposals. gt_class_ids: [b...
class DetectionTargetLayer(KE.Layer):
"""Subsamples proposals and generates target box refinement, class_ids, and masks for each. Inputs: proposals: [batch, N, (y1, x1, y2, x2)] in normalized coordinates. Might be zero padded if there are not enough proposals. gt_class_ids: [batch, MAX_GT_INSTANCES] Integer class I...
0) N = tf.shape(negative_rois)[0] P = tf.maximum(config.TRAIN_ROIS_PER_IMAGE - tf.shape(rois)[0], 0) rois = tf.pad(rois, [(0, P), (0, 0)]) roi_gt_boxes = tf.pad(roi_gt_boxes, [(0, N + P), (0, 0)]) roi_gt_class_ids = tf.pad(roi_gt_class_ids, [(0, N + P)]) deltas = tf.pad(deltas, [(0, N + P)...
180
180
600
8
171
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
DetectionTargetLayer
DetectionTargetLayer
622
677
622
622
1f9b71b0c7aed027ed37dde7c2a69468f8325e02
bigcode/the-stack
train
33d741fbda8f0aa3b2b443a1
train
function
def parse_image_meta_graph(meta): """Parses a tensor that contains image attributes to its components. See compose_image_meta() for more details. meta: [batch, meta length] where meta length depends on NUM_CLASSES Returns a dict of the parsed tensors. """ image_id = meta[:, 0] ori...
def parse_image_meta_graph(meta):
"""Parses a tensor that contains image attributes to its components. See compose_image_meta() for more details. meta: [batch, meta length] where meta length depends on NUM_CLASSES Returns a dict of the parsed tensors. """ image_id = meta[:, 0] original_image_shape = meta[:, 1:4] ...
": original_image_shape.astype(np.int32), "image_shape": image_shape.astype(np.int32), "window": window.astype(np.int32), "scale": scale.astype(np.float32), "active_class_ids": active_class_ids.astype(np.int32), } def parse_image_meta_graph(meta):
64
64
195
7
57
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
parse_image_meta_graph
parse_image_meta_graph
2,781
2,802
2,781
2,781
68d49e59f8ab57a4e44d64948ea8a0eb87bd61c5
bigcode/the-stack
train
3695bbd30e387fd670042143
train
function
def identity_block(input_tensor, kernel_size, filters, stage, block, use_bias=True, train_bn=True): """The identity_block is the block that has no conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at...
def identity_block(input_tensor, kernel_size, filters, stage, block, use_bias=True, train_bn=True):
"""The identity_block is the block that has no conv layer at shortcut # Arguments input_tensor: input tensor kernel_size: default 3, the kernel size of middle conv layer at main path filters: list of integers, the nb_filters of 3 conv layer at main path stage: integer, curre...
_shape) # Currently supports ResNet only assert config.BACKBONE in ["resnet50", "resnet101"] return np.array( [[int(math.ceil(image_shape[0] / stride)), int(math.ceil(image_shape[1] / stride))] for stride in config.BACKBONE_STRIDES]) #############################...
133
133
446
24
108
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
identity_block
identity_block
95
127
95
96
29f722bb5377e52a7a704afe3c1e4faeff27b122
bigcode/the-stack
train
e096db4f731a8e625646fa69
train
function
def mrcnn_class_loss_graph(target_class_ids, pred_class_logits, active_class_ids): """Loss for the classifier head of Mask RCNN. target_class_ids: [batch, num_rois]. Integer class IDs. Uses zero padding to fill in the array. pred_class_logits: [batch, num_rois, num_...
def mrcnn_class_loss_graph(target_class_ids, pred_class_logits, active_class_ids):
"""Loss for the classifier head of Mask RCNN. target_class_ids: [batch, num_rois]. Integer class IDs. Uses zero padding to fill in the array. pred_class_logits: [batch, num_rois, num_classes] active_class_ids: [batch, num_classes]. Has a value of 1 for classes that are in the data...
batch_counts = K.sum(K.cast(K.equal(rpn_match, 1), tf.int32), axis=1) target_bbox = batch_pack_graph(target_bbox, batch_counts, config.IMAGES_PER_GPU) loss = smooth_l1_loss(target_bbox, rpn_bbox) loss = K.switch(tf.size(loss) > 0, K.mean(loss), tf.constant(0.0...
107
107
358
20
86
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
mrcnn_class_loss_graph
mrcnn_class_loss_graph
1,077
1,110
1,077
1,078
3e295e70744c5bd9e6ce892f6663ffdce8df3a4c
bigcode/the-stack
train
d19201650b70ef8476b2f1e6
train
class
class MaskRCNN(): """Encapsulates the Mask RCNN model functionality. The actual Keras model is in the keras_model property. """ def __init__(self, mode, config, model_dir): """ mode: Either "training" or "inference" config: A Sub-class of the Config class mode...
class MaskRCNN():
"""Encapsulates the Mask RCNN model functionality. The actual Keras model is in the keras_model property. """ def __init__(self, mode, config, model_dir): """ mode: Either "training" or "inference" config: A Sub-class of the Config class model_dir: Directory to...
[b] = mrcnn_mask b += 1 # Batch full? if b >= batch_size: inputs = [batch_images, batch_image_meta, batch_rpn_match, batch_rpn_bbox, batch_gt_class_ids, batch_gt_boxes, batch_gt_masks] outputs = [] i...
256
256
9,580
5
250
Medicmind/Mask-RCNN-TF2
mrcnn/model_temp.py
Python
MaskRCNN
MaskRCNN
1,821
2,725
1,821
1,821
6941d640db53a18a583b23da15ed0e33bfd88639
bigcode/the-stack
train
6feef4506bae6dc8691ae5c8
train
class
class Solution: def numJewelsInStones(self, jewels: str, stones: str) -> int: return sum([stones.count(jewel) for jewel in jewels])
class Solution:
def numJewelsInStones(self, jewels: str, stones: str) -> int: return sum([stones.count(jewel) for jewel in jewels])
class Solution:
3
64
38
3
0
hyeseonko/LeetCode
771-jewels-and-stones/771-jewels-and-stones.py
Python
Solution
Solution
1
3
1
1
c57d4c1666edcd5b9de7f2bd7efbb182b37365c0
bigcode/the-stack
train
25880d14e139735f0ac8489e
train
function
def save_file(items, path): # Сохраняем новости в электронной таблице with open(path, 'w', newline='') as file: writer = csv.writer(file, delimiter=';') writer.writerow(['Тема', 'Ссылка']) for item in items: writer.writerow([item['title'], item['link']])
def save_file(items, path): # Сохраняем новости в электронной таблице
with open(path, 'w', newline='') as file: writer = csv.writer(file, delimiter=';') writer.writerow(['Тема', 'Ссылка']) for item in items: writer.writerow([item['title'], item['link']])
color-font-hover-only').get('href'), # получаем ссылку на # новости. #'time': item.find('div', class_='list-item__date').get_text() }) return news def save_file(items, path): # Сохраняем новости в электронной таблице
64
64
73
18
45
kudryavtsev69/parser
parser.py
Python
save_file
save_file
31
36
31
31
3103c0e1a6a128cb74571d525c18afa4f65d6454
bigcode/the-stack
train
c7412d2dbc5289c2c24adc5e
train
function
def get_html(url, params=None): # Запрос r = requests.get(url, headers=HEADERS, params=params) return r
def get_html(url, params=None): # Запрос
r = requests.get(url, headers=HEADERS, params=params) return r
Chrome/93.0.4577.82 ' 'YaBrowser/21.9.1.600 (beta) Yowser/2.5 Safari/537.36', 'accept': '*/*'} FILE = 'news.csv' def get_html(url, params=None): # Запрос
64
64
32
12
52
kudryavtsev69/parser
parser.py
Python
get_html
get_html
12
14
12
12
3ba1a7531ddf39a3f1dbb661f92f9cb463b4e001
bigcode/the-stack
train
959b4893c58a4bfafb280e5f
train
function
def get_content(html): # Получение контента soup = BeautifulSoup(html, 'html.parser') items = soup.find_all('div', class_='list-item__content') news = [] for item in items: news.append({ 'title': item.find('a', class_='list-item__title color-font-hover-only').get_text(strip=True), ...
def get_content(html): # Получение контента
soup = BeautifulSoup(html, 'html.parser') items = soup.find_all('div', class_='list-item__content') news = [] for item in items: news.append({ 'title': item.find('a', class_='list-item__title color-font-hover-only').get_text(strip=True), # Получаем главные новости. ...
.5 Safari/537.36', 'accept': '*/*'} FILE = 'news.csv' def get_html(url, params=None): # Запрос r = requests.get(url, headers=HEADERS, params=params) return r def get_content(html): # Получение контента
64
64
149
11
52
kudryavtsev69/parser
parser.py
Python
get_content
get_content
16
29
16
16
40f6899479990fa5b2e3e9be2b6a3a3401bf0f8c
bigcode/the-stack
train
ed3a0970ccc828285845d978
train
function
def parse(): # Парсинг сайта новостей html = get_html(URL) if html.status_code == 200: print(get_content(html.text)) news = get_content(html.text) save_file(news, FILE) else: print('Error')
def parse(): # Парсинг сайта новостей
html = get_html(URL) if html.status_code == 200: print(get_content(html.text)) news = get_content(html.text) save_file(news, FILE) else: print('Error')
, 'w', newline='') as file: writer = csv.writer(file, delimiter=';') writer.writerow(['Тема', 'Ссылка']) for item in items: writer.writerow([item['title'], item['link']]) def parse(): # Парсинг сайта новостей
64
64
59
13
51
kudryavtsev69/parser
parser.py
Python
parse
parse
38
47
38
38
a422e42c6fad51e9c577ce8eb7df5b4002da87ac
bigcode/the-stack
train
4538f4453f730c94b0ede501
train
class
class PushedModel(_TfxArtifact): TYPE_NAME = 'PushedModel'
class PushedModel(_TfxArtifact):
TYPE_NAME = 'PushedModel'
_NAME = 'Model' class ModelRun(_TfxArtifact): TYPE_NAME = 'ModelRun' class ModelBlessing(_TfxArtifact): TYPE_NAME = 'ModelBlessing' class ModelEvaluation(_TfxArtifact): TYPE_NAME = 'ModelEvaluation' class PushedModel(_TfxArtifact):
64
64
18
9
55
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
PushedModel
PushedModel
136
137
136
136
fbd9f60e4af5211378f3455e1d6e6609fdf04c1a
bigcode/the-stack
train
7ed666b3c4dc09066efc3820
train
class
class TransformCache(_TfxArtifact): TYPE_NAME = 'TransformCache'
class TransformCache(_TfxArtifact):
TYPE_NAME = 'TransformCache'
TYPE_NAME = 'ModelBlessing' class ModelEvaluation(_TfxArtifact): TYPE_NAME = 'ModelEvaluation' class PushedModel(_TfxArtifact): TYPE_NAME = 'PushedModel' class Schema(_TfxArtifact): TYPE_NAME = 'Schema' class TransformCache(_TfxArtifact):
64
64
16
8
56
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
TransformCache
TransformCache
144
145
144
144
17e33abcc3a43dbbf2a00ada84a507e307e910df
bigcode/the-stack
train
6571cb3d8a01c2bc56fb0fc8
train
class
class Schema(_TfxArtifact): TYPE_NAME = 'Schema'
class Schema(_TfxArtifact):
TYPE_NAME = 'Schema'
= 'ModelRun' class ModelBlessing(_TfxArtifact): TYPE_NAME = 'ModelBlessing' class ModelEvaluation(_TfxArtifact): TYPE_NAME = 'ModelEvaluation' class PushedModel(_TfxArtifact): TYPE_NAME = 'PushedModel' class Schema(_TfxArtifact):
64
64
14
7
57
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
Schema
Schema
140
141
140
140
45968b375b6eae7d64f1cca2c254ca7cce7fa539
bigcode/the-stack
train
d45a65f53e6347ec8cff8d57
train
class
class InfraBlessing(_TfxArtifact): TYPE_NAME = 'InfraBlessing'
class InfraBlessing(_TfxArtifact):
TYPE_NAME = 'InfraBlessing'
': SPLIT_NAMES_PROPERTY, } # TODO(b/158334890): deprecate ExternalArtifact. class ExternalArtifact(_TfxArtifact): TYPE_NAME = 'ExternalArtifact' class InferenceResult(_TfxArtifact): TYPE_NAME = 'InferenceResult' class InfraBlessing(_TfxArtifact):
64
64
18
9
55
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
InfraBlessing
InfraBlessing
116
117
116
116
edf30895c8d2946bc4d0ff4ab3f04227e24bfe99
bigcode/the-stack
train
2ec2c4b062b069987f89f158
train
class
class String(ValueArtifact): """String-typed artifact.""" TYPE_NAME = 'String' # Note, currently we enforce unicode-encoded string. def encode(self, value: Text) -> bytes: if not isinstance(value, Text): raise TypeError('Expecting Text but got value %s of type %s' % (str(value),...
class String(ValueArtifact):
"""String-typed artifact.""" TYPE_NAME = 'String' # Note, currently we enforce unicode-encoded string. def encode(self, value: Text) -> bytes: if not isinstance(value, Text): raise TypeError('Expecting Text but got value %s of type %s' % (str(value), type(value))) return val...
, value: bytes): if not isinstance(value, bytes): raise TypeError('Expecting bytes but got value %s of type %s' % (str(value), type(value))) return value def decode(self, serialized_value: bytes): return serialized_value class String(ValueArtifact):
64
64
110
5
58
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
String
String
162
174
162
162
9e0f583c58820bd64aa2f0959a7ec4097911557b
bigcode/the-stack
train
05d7260df11405656f9dea59
train
class
class ModelBlessing(_TfxArtifact): TYPE_NAME = 'ModelBlessing'
class ModelBlessing(_TfxArtifact):
TYPE_NAME = 'ModelBlessing'
TYPE_NAME = 'InferenceResult' class InfraBlessing(_TfxArtifact): TYPE_NAME = 'InfraBlessing' class Model(_TfxArtifact): TYPE_NAME = 'Model' class ModelRun(_TfxArtifact): TYPE_NAME = 'ModelRun' class ModelBlessing(_TfxArtifact):
64
64
18
9
55
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
ModelBlessing
ModelBlessing
128
129
128
128
1db25f902a184444dacd9b2e12d4d30d5dabc4df
bigcode/the-stack
train
62161114f46a2c94d8a6fde9
train
class
class ExampleAnomalies(_TfxArtifact): TYPE_NAME = 'ExampleAnomalies' PROPERTIES = { 'span': SPAN_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, }
class ExampleAnomalies(_TfxArtifact):
TYPE_NAME = 'ExampleAnomalies' PROPERTIES = { 'span': SPAN_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, }
).__init__(*args, **kwargs) class Examples(_TfxArtifact): TYPE_NAME = 'Examples' PROPERTIES = { 'span': SPAN_PROPERTY, 'version': VERSION_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, } class ExampleAnomalies(_TfxArtifact):
64
64
45
10
54
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
ExampleAnomalies
ExampleAnomalies
91
96
91
91
3d9a05340bc07ca1f081a474033ffb522b497f85
bigcode/the-stack
train
680cbdc98f26dde1c63468de
train
class
class ModelEvaluation(_TfxArtifact): TYPE_NAME = 'ModelEvaluation'
class ModelEvaluation(_TfxArtifact):
TYPE_NAME = 'ModelEvaluation'
TYPE_NAME = 'InfraBlessing' class Model(_TfxArtifact): TYPE_NAME = 'Model' class ModelRun(_TfxArtifact): TYPE_NAME = 'ModelRun' class ModelBlessing(_TfxArtifact): TYPE_NAME = 'ModelBlessing' class ModelEvaluation(_TfxArtifact):
64
64
16
8
56
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
ModelEvaluation
ModelEvaluation
132
133
132
132
efee8b7758674d604887deab6cedf4787cc95982
bigcode/the-stack
train
510ff78ef21e32abac2cd4fb
train
class
class DataView(_TfxArtifact): TYPE_NAME = 'DataView'
class DataView(_TfxArtifact):
TYPE_NAME = 'DataView'
s"' % (serialized_value, reserialized_string)) return result class TransformGraph(_TfxArtifact): TYPE_NAME = 'TransformGraph' class HyperParameters(_TfxArtifact): TYPE_NAME = 'HyperParameters' # WIP and subject to change. class DataView(_TfxArtifact):
64
64
16
8
56
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
DataView
DataView
250
251
250
250
3a88aa812b54dc3b659f37a9db1769f5781625b6
bigcode/the-stack
train
15ee9a7d80dce47bf22bb9fd
train
class
class Bytes(ValueArtifact): """Artifacts representing raw bytes.""" TYPE_NAME = 'Bytes' def encode(self, value: bytes): if not isinstance(value, bytes): raise TypeError('Expecting bytes but got value %s of type %s' % (str(value), type(value))) return value def decode(self, ...
class Bytes(ValueArtifact):
"""Artifacts representing raw bytes.""" TYPE_NAME = 'Bytes' def encode(self, value: bytes): if not isinstance(value, bytes): raise TypeError('Expecting bytes but got value %s of type %s' % (str(value), type(value))) return value def decode(self, serialized_value: bytes): ...
fxArtifact): TYPE_NAME = 'ModelEvaluation' class PushedModel(_TfxArtifact): TYPE_NAME = 'PushedModel' class Schema(_TfxArtifact): TYPE_NAME = 'Schema' class TransformCache(_TfxArtifact): TYPE_NAME = 'TransformCache' class Bytes(ValueArtifact):
64
64
82
5
59
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
Bytes
Bytes
148
159
148
148
83a64e3448b283880b1c94beb2fa996bd89c0571
bigcode/the-stack
train
9e1d40344c59abb595dfc9c0
train
class
class Integer(ValueArtifact): """Integer-typed artifact.""" TYPE_NAME = 'Integer' def encode(self, value: int) -> bytes: if not isinstance(value, int): raise TypeError('Expecting int but got value %s of type %s' % (str(value), type(value))) return str(value).encode('utf-8') ...
class Integer(ValueArtifact):
"""Integer-typed artifact.""" TYPE_NAME = 'Integer' def encode(self, value: int) -> bytes: if not isinstance(value, int): raise TypeError('Expecting int but got value %s of type %s' % (str(value), type(value))) return str(value).encode('utf-8') def decode(self, serialized_v...
raise TypeError('Expecting Text but got value %s of type %s' % (str(value), type(value))) return value.encode('utf-8') def decode(self, serialized_value: bytes) -> Text: return serialized_value.decode('utf-8') class Integer(ValueArtifact):
64
64
97
5
59
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
Integer
Integer
177
188
177
177
6392eae70f4425ad7c97ccc6cd8e00d749480379
bigcode/the-stack
train
d1552dfb40e2c723645f5a8f
train
class
class Model(_TfxArtifact): TYPE_NAME = 'Model'
class Model(_TfxArtifact):
TYPE_NAME = 'Model'
deprecate ExternalArtifact. class ExternalArtifact(_TfxArtifact): TYPE_NAME = 'ExternalArtifact' class InferenceResult(_TfxArtifact): TYPE_NAME = 'InferenceResult' class InfraBlessing(_TfxArtifact): TYPE_NAME = 'InfraBlessing' class Model(_TfxArtifact):
64
64
14
7
57
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
Model
Model
120
121
120
120
ad95fcb045335ccba221e75492d30b216c1ab4ce
bigcode/the-stack
train
7d22c2d9563313b6b78712ea
train
class
class ExternalArtifact(_TfxArtifact): TYPE_NAME = 'ExternalArtifact'
class ExternalArtifact(_TfxArtifact):
TYPE_NAME = 'ExternalArtifact'
} class ExampleStatistics(_TfxArtifact): TYPE_NAME = 'ExampleStatistics' PROPERTIES = { 'span': SPAN_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, } # TODO(b/158334890): deprecate ExternalArtifact. class ExternalArtifact(_TfxArtifact):
64
64
16
8
56
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
ExternalArtifact
ExternalArtifact
108
109
108
108
534b6896e77a8f51ec48755e6c0b066ba0b88acf
bigcode/the-stack
train
308a76cc5d1a3ec55a2955a7
train
class
class ModelRun(_TfxArtifact): TYPE_NAME = 'ModelRun'
class ModelRun(_TfxArtifact):
TYPE_NAME = 'ModelRun'
TYPE_NAME = 'ExternalArtifact' class InferenceResult(_TfxArtifact): TYPE_NAME = 'InferenceResult' class InfraBlessing(_TfxArtifact): TYPE_NAME = 'InfraBlessing' class Model(_TfxArtifact): TYPE_NAME = 'Model' class ModelRun(_TfxArtifact):
64
64
16
8
56
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
ModelRun
ModelRun
124
125
124
124
c97c11c836c6298ae3ed4b5ad79c03f1ca27244b
bigcode/the-stack
train
c9fcdf361bfe5ba2517a2d24
train
class
class ExampleStatistics(_TfxArtifact): TYPE_NAME = 'ExampleStatistics' PROPERTIES = { 'span': SPAN_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, }
class ExampleStatistics(_TfxArtifact):
TYPE_NAME = 'ExampleStatistics' PROPERTIES = { 'span': SPAN_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, }
'split_names': SPLIT_NAMES_PROPERTY, } class ExampleAnomalies(_TfxArtifact): TYPE_NAME = 'ExampleAnomalies' PROPERTIES = { 'span': SPAN_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, } class ExampleStatistics(_TfxArtifact):
64
64
41
8
56
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
ExampleStatistics
ExampleStatistics
99
104
99
99
389829ac744485d1358823cb8d861f72837e5e39
bigcode/the-stack
train
e2b4f66755fb7a43dd8c596a
train
class
class _TfxArtifact(Artifact): """TFX first-party component artifact definition. Do not construct directly, used for creating Channel, e.g., ``` Channel(type=standard_artifacts.Model) ``` """ def __init__(self, *args, **kwargs): """Construct TFX first-party component artifact.""" # TODO(b/17679...
class _TfxArtifact(Artifact):
"""TFX first-party component artifact definition. Do not construct directly, used for creating Channel, e.g., ``` Channel(type=standard_artifacts.Model) ``` """ def __init__(self, *args, **kwargs): """Construct TFX first-party component artifact.""" # TODO(b/176795331): Refactor directory stru...
ValueArtifact # Span for an artifact. SPAN_PROPERTY = Property(type=PropertyType.INT) # Version for an artifact. VERSION_PROPERTY = Property(type=PropertyType.INT) # Comma separated of splits for an artifact. Empty string means artifact # has no split. SPLIT_NAMES_PROPERTY = Property(type=PropertyType.STRING) # Value...
96
96
321
8
88
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
_TfxArtifact
_TfxArtifact
46
79
46
46
ccb92eda3b23f4f7c8ab1a541a1fc4a62f08941d
bigcode/the-stack
train
e61fdb57e565cfb874e9f459
train
class
class HyperParameters(_TfxArtifact): TYPE_NAME = 'HyperParameters'
class HyperParameters(_TfxArtifact):
TYPE_NAME = 'HyperParameters'
is_exact: absl.logging.warning( 'The number "%s" has lost precision when converted to float "%s"' % (serialized_value, reserialized_string)) return result class TransformGraph(_TfxArtifact): TYPE_NAME = 'TransformGraph' class HyperParameters(_TfxArtifact):
64
64
16
8
56
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
HyperParameters
HyperParameters
245
246
245
245
174aa7779e33316de24ad829dc42feeb55d1fbb4
bigcode/the-stack
train
f52da5fc4555c3f957152dc0
train
class
class InferenceResult(_TfxArtifact): TYPE_NAME = 'InferenceResult'
class InferenceResult(_TfxArtifact):
TYPE_NAME = 'InferenceResult'
PROPERTIES = { 'span': SPAN_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, } # TODO(b/158334890): deprecate ExternalArtifact. class ExternalArtifact(_TfxArtifact): TYPE_NAME = 'ExternalArtifact' class InferenceResult(_TfxArtifact):
64
64
17
9
55
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
InferenceResult
InferenceResult
112
113
112
112
410e637d4e8bc35695aff4f621a60c5fb3faafe6
bigcode/the-stack
train
eccb1b254ee21268275a34d3
train
class
class Examples(_TfxArtifact): TYPE_NAME = 'Examples' PROPERTIES = { 'span': SPAN_PROPERTY, 'version': VERSION_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, }
class Examples(_TfxArtifact):
TYPE_NAME = 'Examples' PROPERTIES = { 'span': SPAN_PROPERTY, 'version': VERSION_PROPERTY, 'split_names': SPLIT_NAMES_PROPERTY, }
tests run in Bazel. if can_import_setuptools and not can_import_components: raise Exception('The full "tfx" package must be installed to use this ' 'functionality.') super(_TfxArtifact, self).__init__(*args, **kwargs) class Examples(_TfxArtifact):
64
64
46
7
57
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
Examples
Examples
82
88
82
82
890be6c9199547832981201e01efa784528b0563
bigcode/the-stack
train
39ef00996e53e2639549c3b2
train
class
class Float(ValueArtifact): """Float-typed artifact.""" TYPE_NAME = 'Float' _POSITIVE_INFINITY = float('Inf') _NEGATIVE_INFINITY = float('-Inf') _ENCODED_POSITIVE_INFINITY = 'Infinity' _ENCODED_NEGATIVE_INFINITY = '-Infinity' _ENCODED_NAN = 'NaN' def encode(self, value: float) -> bytes: if not is...
class Float(ValueArtifact):
"""Float-typed artifact.""" TYPE_NAME = 'Float' _POSITIVE_INFINITY = float('Inf') _NEGATIVE_INFINITY = float('-Inf') _ENCODED_POSITIVE_INFINITY = 'Infinity' _ENCODED_NEGATIVE_INFINITY = '-Infinity' _ENCODED_NAN = 'NaN' def encode(self, value: float) -> bytes: if not isinstance(value, float): ...
_value: bytes) -> Text: return serialized_value.decode('utf-8') class Integer(ValueArtifact): """Integer-typed artifact.""" TYPE_NAME = 'Integer' def encode(self, value: int) -> bytes: if not isinstance(value, int): raise TypeError('Expecting int but got value %s of type %s' % ...
119
119
397
5
114
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
Float
Float
191
238
191
191
3caee99f5f6340b51922432fec56da9655686c4c
bigcode/the-stack
train
1ba566653c5dd1696e111c08
train
class
class TransformGraph(_TfxArtifact): TYPE_NAME = 'TransformGraph'
class TransformGraph(_TfxArtifact):
TYPE_NAME = 'TransformGraph'
.Decimal(serialized_string) == decimal.Decimal(reserialized_string)) if not is_exact: absl.logging.warning( 'The number "%s" has lost precision when converted to float "%s"' % (serialized_value, reserialized_string)) return result class TransformGraph(_TfxArtifact):
64
64
16
8
55
Saiprasad16/tfx
tfx/types/standard_artifacts.py
Python
TransformGraph
TransformGraph
241
242
241
241
f1e9ca38007e10bc0bb9dbb818699a7315164db7
bigcode/the-stack
train
14e92ff882221abeaddef87f
train
function
@api_bp.route("/alias/custom/new", methods=["POST"]) @cross_origin() @verify_api_key def new_custom_alias(): """ Create a new custom alias Input: alias_prefix, for ex "www_groupon_com" alias_suffix, either .random_letters@simplelogin.co or @my-domain.com optional "hostname" in args ...
@api_bp.route("/alias/custom/new", methods=["POST"]) @cross_origin() @verify_api_key def new_custom_alias():
""" Create a new custom alias Input: alias_prefix, for ex "www_groupon_com" alias_suffix, either .random_letters@simplelogin.co or @my-domain.com optional "hostname" in args Output: 201 if success 409 if alias already exists """ user = g.user if not u...
from flask import g from flask import jsonify, request from flask_cors import cross_origin from app.api.base import api_bp, verify_api_key from app.config import EMAIL_DOMAIN from app.extensions import db from app.log import LOG from app.models import GenEmail, AliasUsedOn from app.utils import convert_to_id @api_bp.r...
97
183
610
27
69
NinhDinh/app
app/api/views/new_custom_alias.py
Python
new_custom_alias
new_custom_alias
13
84
13
16
d9b9088882d379c0e2d2ff8cc53879b35a8f4608
bigcode/the-stack
train
60ddb863470b38c5f3dbb88e
train
class
class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'array_formula02.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_t...
class TestCompareXLSXFiles(ExcelComparisonTest):
""" Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'array_formula02.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test...
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest):
68
87
291
12
55
shareablee/XlsxWriter
xlsxwriter/test/comparison/test_array_formula02.py
Python
TestCompareXLSXFiles
TestCompareXLSXFiles
12
51
12
12
768082ad95df27e8062e056802e99dabb06bbdac
bigcode/the-stack
train
6108c2f6500228044f2bfad3
train
function
def _get_checked_path(path, config, must_exist=True, allow_none=True): """Convert path to absolute if not None.""" if path in (None, ""): if allow_none: return None raise ValueError("Invalid path {!r}".format(path)) # Evaluate path relative to the folder of the config file (if an...
def _get_checked_path(path, config, must_exist=True, allow_none=True):
"""Convert path to absolute if not None.""" if path in (None, ""): if allow_none: return None raise ValueError("Invalid path {!r}".format(path)) # Evaluate path relative to the folder of the config file (if any) config_file = config.get("_config_file") if config_file and ...
files if no --config=... option is specified DEFAULT_CONFIG_FILES = ("wsgidav.yaml", "wsgidav.json", "wsgidav.conf") _logger = logging.getLogger("wsgidav") def _get_checked_path(path, config, must_exist=True, allow_none=True):
64
64
153
17
47
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_get_checked_path
_get_checked_path
65
79
65
65
6b53fb81b86788e934127a5bd417471bf0e562fb
bigcode/the-stack
train
cac6a9eabe2d456be46edeaf
train
function
def _run_ext_wsgiutils(app, config, mode): """Run WsgiDAV using ext_wsgiutils_server from the wsgidav package.""" from wsgidav.server import ext_wsgiutils_server _logger.info( "Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...".format(__version__) ) _logger.warning( "WARNING: Th...
def _run_ext_wsgiutils(app, config, mode):
"""Run WsgiDAV using ext_wsgiutils_server from the wsgidav package.""" from wsgidav.server import ext_wsgiutils_server _logger.info( "Running WsgiDAV {} on wsgidav.ext_wsgiutils_server...".format(__version__) ) _logger.warning( "WARNING: This single threaded server (ext-wsgiutils) i...
for production." ) httpd = make_server(config["host"], config["port"], app) try: httpd.serve_forever() except KeyboardInterrupt: _logger.warning("Caught Ctrl-C, shutting down...") return def _run_ext_wsgiutils(app, config, mode):
64
64
134
12
51
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_run_ext_wsgiutils
_run_ext_wsgiutils
733
747
733
733
d46da5f9c9ba97062a985aaba076366ce398e6ed
bigcode/the-stack
train
6a3890b3d731be9def20d2e3
train
function
def _run_gevent(app, config, mode): """Run WsgiDAV using gevent if gevent is installed. See https://github.com/gevent/gevent/blob/master/src/gevent/pywsgi.py#L1356 https://github.com/gevent/gevent/blob/master/src/gevent/server.py#L38 for more options """ import gevent import gevent...
def _run_gevent(app, config, mode):
"""Run WsgiDAV using gevent if gevent is installed. See https://github.com/gevent/gevent/blob/master/src/gevent/pywsgi.py#L1356 https://github.com/gevent/gevent/blob/master/src/gevent/server.py#L38 for more options """ import gevent import gevent.monkey gevent.monkey.patch_all...
://127.0.0.1:{}".format(port, "http", port) ) else: _logger.info("Serving on {}://{}:{}".format("http", host, port)) try: server.serve_forever() except KeyboardInterrupt: _logger.warning("Caught Ctrl-C, shutting down...") return def _run_gevent(app, config, mode):
84
84
280
11
72
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_run_gevent
_run_gevent
483
517
483
483
e05144adb6b26f62b5a39b6821a94ea6d977eb5c
bigcode/the-stack
train
e146e1e68c40edf21f8a91a6
train
class
class FullExpandedPath(argparse.Action): """Expand user- and relative-paths""" def __call__(self, parser, namespace, values, option_string=None): new_val = os.path.abspath(os.path.expanduser(values)) setattr(namespace, self.dest, new_val)
class FullExpandedPath(argparse.Action):
"""Expand user- and relative-paths""" def __call__(self, parser, namespace, values, option_string=None): new_val = os.path.abspath(os.path.expanduser(values)) setattr(namespace, self.dest, new_val)
path = os.path.normpath(os.path.join(os.path.dirname(config_file), path)) else: path = os.path.abspath(path) if must_exist and not os.path.exists(path): raise ValueError("Invalid path {!r}".format(path)) return path class FullExpandedPath(argparse.Action):
64
64
58
8
55
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
FullExpandedPath
FullExpandedPath
82
87
82
82
45af5ca9cfa764c718b8c925e9f80d618be0597d
bigcode/the-stack
train
ba44e401fae2c6505063e512
train
function
def _run_wsgiref(app, config, mode): """Run WsgiDAV using wsgiref.simple_server, on Python 2.5+.""" # http://www.python.org/doc/2.5.2/lib/module-wsgiref.html from wsgiref.simple_server import make_server, software_version version = "WsgiDAV/{} {}".format(__version__, software_version) _logger.info(...
def _run_wsgiref(app, config, mode):
"""Run WsgiDAV using wsgiref.simple_server, on Python 2.5+.""" # http://www.python.org/doc/2.5.2/lib/module-wsgiref.html from wsgiref.simple_server import make_server, software_version version = "WsgiDAV/{} {}".format(__version__, software_version) _logger.info("Running {}...".format(version)) ...
erver( app, bindAddress=(config["host"], config["port"]), # debug=True, ) try: server.run() except KeyboardInterrupt: _logger.warning("Caught Ctrl-C, shutting down...") return def _run_wsgiref(app, config, mode):
64
64
175
13
50
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_run_wsgiref
_run_wsgiref
715
730
715
715
9e0f9f86340a98cc2ae1326f676e30f95cf2258b
bigcode/the-stack
train
3e9a01996e6796f3da00d935
train
function
def run(): config = _init_config() util.init_logging(config) app = WsgiDAVApp(config) server = config["server"] handler = SUPPORTED_SERVERS.get(server) if not handler: raise RuntimeError( "Unsupported server type {!r} (expected {!r})".format( server, "', '"...
def run():
config = _init_config() util.init_logging(config) app = WsgiDAVApp(config) server = config["server"] handler = SUPPORTED_SERVERS.get(server) if not handler: raise RuntimeError( "Unsupported server type {!r} (expected {!r})".format( server, "', '".join(SUPPO...
_run__cherrypy, "ext-wsgiutils": _run_ext_wsgiutils, "flup-fcgi": _run_flup, "flup-fcgi_fork": _run_flup, "wsgiref": _run_wsgiref, } def run():
64
64
160
3
61
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
run
run
762
784
762
762
e60f1a98830c8bee5fc64af15f5cc2ffe686df05
bigcode/the-stack
train
abb12525a30c5fe21648de1e
train
function
def _run__cherrypy(app, config, mode): """Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed.""" assert mode == "cherrypy-wsgiserver" try: from cherrypy import wsgiserver from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter _logger.warning("WARNING: cherrypy.ws...
def _run__cherrypy(app, config, mode):
"""Run WsgiDAV using cherrypy.wsgiserver if CherryPy is installed.""" assert mode == "cherrypy-wsgiserver" try: from cherrypy import wsgiserver from cherrypy.wsgiserver.ssl_builtin import BuiltinSSLAdapter _logger.warning("WARNING: cherrypy.wsgiserver is deprecated.") _logg...
""" import gevent import gevent.monkey gevent.monkey.patch_all() from gevent.pywsgi import WSGIServer server_args = { "bind_addr": (config["host"], config["port"]), "wsgi_app": app, # TODO: SSL support "keyfile": None, "certfile": None, } protoco...
215
215
718
13
201
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_run__cherrypy
_run__cherrypy
520
603
520
520
e69936431d2ff309205a740c4d257ee4f6abdeca
bigcode/the-stack
train
643ede05c05a8852028e2ff3
train
function
def _run_cheroot(app, config, mode): """Run WsgiDAV using cheroot.server if Cheroot is installed.""" assert mode == "cheroot" try: from cheroot import server, wsgi # from cheroot.ssl.builtin import BuiltinSSLAdapter # import cheroot.ssl.pyopenssl except ImportError: ...
def _run_cheroot(app, config, mode):
"""Run WsgiDAV using cheroot.server if Cheroot is installed.""" assert mode == "cheroot" try: from cheroot import server, wsgi # from cheroot.ssl.builtin import BuiltinSSLAdapter # import cheroot.ssl.pyopenssl except ImportError: _logger.error("*" * 78) _l...
_name": server_name, } # Override or add custom args server_args.update(config.get("server_args", {})) server = wsgiserver.CherryPyWSGIServer(**server_args) # If the caller passed a startup event, monkey patch the server to set it # when the request handler loop is entered startup_event = ...
189
189
632
12
176
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_run_cheroot
_run_cheroot
606
685
606
606
9a2bd3a027bc86a6dd64da289f55b121a739341d
bigcode/the-stack
train
5f862c308451b869c99fda34
train
function
def _init_config(): """Setup configuration dictionary from default, command line and configuration file.""" cli_opts, parser = _init_command_line_options() cli_verbose = cli_opts["verbose"] # Set config defaults config = copy.deepcopy(DEFAULT_CONFIG) # Configuration file overrides defaults ...
def _init_config():
"""Setup configuration dictionary from default, command line and configuration file.""" cli_opts, parser = _init_command_line_options() cli_verbose = cli_opts["verbose"] # Set config defaults config = copy.deepcopy(DEFAULT_CONFIG) # Configuration file overrides defaults config_file = cli_o...
io.open(config_file, mode="r", encoding="utf-8") as json_file: # Minify the JSON file to strip embedded comments minified = jsmin(json_file.read()) conf = json.loads(minified) elif config_file.endswith(".yaml"): with io.open(config_file, mode="r", encoding="utf-8") as yaml_...
256
256
902
5
250
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_init_config
_init_config
306
422
306
306
542aae351c1a303482bfbb0024bc0511355005ef
bigcode/the-stack
train
a71cc71288024f85a54301bf
train
function
def _run_flup(app, config, mode): """Run WsgiDAV using flup.server.fcgi if Flup is installed.""" # http://trac.saddi.com/flup/wiki/FlupServers if mode == "flup-fcgi": from flup.server.fcgi import WSGIServer, __version__ as flupver elif mode == "flup-fcgi-fork": from flup.server.fcgi_fork...
def _run_flup(app, config, mode):
"""Run WsgiDAV using flup.server.fcgi if Flup is installed.""" # http://trac.saddi.com/flup/wiki/FlupServers if mode == "flup-fcgi": from flup.server.fcgi import WSGIServer, __version__ as flupver elif mode == "flup-fcgi-fork": from flup.server.fcgi_fork import WSGIServer, __version__ as...
org_tick() org_tick = server.tick server.tick = _patched_tick try: server.start() except KeyboardInterrupt: _logger.warning("Caught Ctrl-C, shutting down...") finally: server.stop() return def _run_flup(app, config, mode):
64
64
216
11
52
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_run_flup
_run_flup
688
712
688
688
ee313071622c7af059d54cd494551babc653aeda
bigcode/the-stack
train
6e2adedfad659a9571eb43d8
train
function
def _init_command_line_options(): """Parse command line options into a dictionary.""" description = """\ Run a WEBDAV server to share file system folders. Examples: Share filesystem folder '/temp' for anonymous access (no config file used): wsgidav --port=80 --host=0.0.0.0 --root=/temp --auth=anonymou...
def _init_command_line_options():
"""Parse command line options into a dictionary.""" description = """\ Run a WEBDAV server to share file system folders. Examples: Share filesystem folder '/temp' for anonymous access (no config file used): wsgidav --port=80 --host=0.0.0.0 --root=/temp --auth=anonymous Run using a specific configur...
specified DEFAULT_CONFIG_FILES = ("wsgidav.yaml", "wsgidav.json", "wsgidav.conf") _logger = logging.getLogger("wsgidav") def _get_checked_path(path, config, must_exist=True, allow_none=True): """Convert path to absolute if not None.""" if path in (None, ""): if allow_none: return None ...
256
256
1,168
7
249
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_init_command_line_options
_init_command_line_options
90
255
90
90
ba41890f1be1c45b28e389b575da9e06d569e15b
bigcode/the-stack
train
916f207b079d3467d239d6be
train
function
def _read_config_file(config_file, verbose): """Read configuration file options into a dictionary.""" config_file = os.path.abspath(config_file) if not os.path.exists(config_file): raise RuntimeError("Couldn't open configuration file '{}'.".format(config_file)) if config_file.endswith(".json"...
def _read_config_file(config_file, verbose):
"""Read configuration file options into a dictionary.""" config_file = os.path.abspath(config_file) if not os.path.exists(config_file): raise RuntimeError("Couldn't open configuration file '{}'.".format(config_file)) if config_file.endswith(".json"): with io.open(config_file, mode="r"...
find specified configuration file: {}".format( args.config_file ) ) # Convert args object to dictionary cmdLineOpts = args.__dict__.copy() if args.verbose >= 5: print("Command line args:") for k, v in cmdLineOpts.items(): print(" ...
94
94
315
10
83
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_read_config_file
_read_config_file
258
303
258
258
79a1c6df121991874d8539e07cf06830d39ae7c2
bigcode/the-stack
train
7724c0aa13102ca9abe7b61b
train
function
def _run_paste(app, config, mode): """Run WsgiDAV using paste.httpserver, if Paste is installed. See http://pythonpaste.org/modules/httpserver.html for more options """ from paste import httpserver version = "WsgiDAV/{} {} Python {}".format( __version__, httpserver.WSGIHandler.server_versi...
def _run_paste(app, config, mode):
"""Run WsgiDAV using paste.httpserver, if Paste is installed. See http://pythonpaste.org/modules/httpserver.html for more options """ from paste import httpserver version = "WsgiDAV/{} {} Python {}".format( __version__, httpserver.WSGIHandler.server_version, util.PYTHON_VERSION ) _...
True, "accept_digest": False, "default_to_digest": False, } ) config["pam_dc"] = {"service": "login"} # print(config) if cli_opts.get("reload"): print("Installing paste.reloader.", file=sys.stderr) from paste import reloader # @Unres...
127
127
425
11
115
WorldException/wsgidav
wsgidav/server/server_cli.py
Python
_run_paste
_run_paste
425
480
425
425
84843b9a34b30ff6c84f38f5efab03a5104b3abc
bigcode/the-stack
train
03efe951153b3fb5e39802f7
train
function
@mock.patch("os.getcwd", return_value="/cwd") @mock.patch("os.makedirs") def test_target_directory_with_no_path(_, makedirs): assert target_directory() == "/cwd" makedirs.assert_called()
@mock.patch("os.getcwd", return_value="/cwd") @mock.patch("os.makedirs") def test_target_directory_with_no_path(_, makedirs):
assert target_directory() == "/cwd" makedirs.assert_called()
os.makedirs") def test_target_directory_with_absolute_path(_, makedirs): assert target_directory("/test") == "/test" makedirs.assert_called() @mock.patch("os.getcwd", return_value="/cwd") @mock.patch("os.makedirs") def test_target_directory_with_no_path(_, makedirs):
64
64
47
31
33
Twixes/pytube3
tests/test_helpers.py
Python
test_target_directory_with_no_path
test_target_directory_with_no_path
72
76
72
74
8024e145c9e4e9861a89f9ca2eead46ea0f43885
bigcode/the-stack
train
cf31272b39baf4f1bce60094
train
function
@mock.patch("os.path.isabs", return_value=False) @mock.patch("os.getcwd", return_value="/cwd") @mock.patch("os.makedirs") def test_target_directory_with_relative_path(_, __, makedirs): assert target_directory("test") == "/cwd/test" makedirs.assert_called()
@mock.patch("os.path.isabs", return_value=False) @mock.patch("os.getcwd", return_value="/cwd") @mock.patch("os.makedirs") def test_target_directory_with_relative_path(_, __, makedirs):
assert target_directory("test") == "/cwd/test" makedirs.assert_called()
_func("bye") cached_func("bye") assert call_count == 2 @mock.patch("os.path.isabs", return_value=False) @mock.patch("os.getcwd", return_value="/cwd") @mock.patch("os.makedirs") def test_target_directory_with_relative_path(_, __, makedirs):
64
64
65
46
17
Twixes/pytube3
tests/test_helpers.py
Python
test_target_directory_with_relative_path
test_target_directory_with_relative_path
57
62
57
60
8a998179cfb2a7164f6f93336c05ba1af8b71058
bigcode/the-stack
train
cef8a90b5166d925f6485177
train
function
def test_regex_search_no_match(): with pytest.raises(RegexMatchError): helpers.regex_search("^a$", "", group=0)
def test_regex_search_no_match():
with pytest.raises(RegexMatchError): helpers.regex_search("^a$", "", group=0)
# -*- coding: utf-8 -*- from unittest import mock import pytest from pytube import helpers from pytube.exceptions import RegexMatchError from pytube.helpers import deprecated, cache, target_directory def test_regex_search_no_match():
50
64
28
7
42
Twixes/pytube3
tests/test_helpers.py
Python
test_regex_search_no_match
test_regex_search_no_match
11
13
11
11
b6732ae9ede68a8febf9e3c5134c138b03be907f
bigcode/the-stack
train
530b1aa7f091bf8b95643a2a
train
function
def test_regex_search(): assert helpers.regex_search("^a$", "a", group=0) == "a"
def test_regex_search():
assert helpers.regex_search("^a$", "a", group=0) == "a"
import pytest from pytube import helpers from pytube.exceptions import RegexMatchError from pytube.helpers import deprecated, cache, target_directory def test_regex_search_no_match(): with pytest.raises(RegexMatchError): helpers.regex_search("^a$", "", group=0) def test_regex_search():
64
64
24
5
59
Twixes/pytube3
tests/test_helpers.py
Python
test_regex_search
test_regex_search
16
17
16
16
5f8c903c583a84057b4591a591f466a2ac4b32ef
bigcode/the-stack
train
2a2dc7ca9ec25038dea2a172
train
function
@mock.patch("os.path.isabs", return_value=True) @mock.patch("os.makedirs") def test_target_directory_with_absolute_path(_, makedirs): assert target_directory("/test") == "/test" makedirs.assert_called()
@mock.patch("os.path.isabs", return_value=True) @mock.patch("os.makedirs") def test_target_directory_with_absolute_path(_, makedirs):
assert target_directory("/test") == "/test" makedirs.assert_called()
test_target_directory_with_relative_path(_, __, makedirs): assert target_directory("test") == "/cwd/test" makedirs.assert_called() @mock.patch("os.path.isabs", return_value=True) @mock.patch("os.makedirs") def test_target_directory_with_absolute_path(_, makedirs):
64
64
50
32
32
Twixes/pytube3
tests/test_helpers.py
Python
test_target_directory_with_absolute_path
test_target_directory_with_absolute_path
65
69
65
67
2d3efd6decb5bd7ee0394b5ceee44987090c3dd4
bigcode/the-stack
train
2d8aedffe6b16af6f2ccd40f
train
function
@mock.patch("warnings.warn") def test_deprecated(warn): @deprecated("oh no") def deprecated_function(): return None deprecated_function() warn.assert_called_with( "Call to deprecated function deprecated_function (oh no).", category=DeprecationWarning, stacklevel=2, )...
@mock.patch("warnings.warn") def test_deprecated(warn): @deprecated("oh no")
def deprecated_function(): return None deprecated_function() warn.assert_called_with( "Call to deprecated function deprecated_function (oh no).", category=DeprecationWarning, stacklevel=2, )
_safe_filename(): """Unsafe characters get stripped from generated filename""" assert helpers.safe_filename("abc1245$$") == "abc1245" assert helpers.safe_filename("abc##") == "abc" @mock.patch("warnings.warn") def test_deprecated(warn): @deprecated("oh no")
64
64
69
21
43
Twixes/pytube3
tests/test_helpers.py
Python
test_deprecated
test_deprecated
26
37
26
28
5f7530add64a1a108c278cde60fa2a80a1cd4a47
bigcode/the-stack
train
611f074ea231bc079ee91274
train
function
def test_safe_filename(): """Unsafe characters get stripped from generated filename""" assert helpers.safe_filename("abc1245$$") == "abc1245" assert helpers.safe_filename("abc##") == "abc"
def test_safe_filename():
"""Unsafe characters get stripped from generated filename""" assert helpers.safe_filename("abc1245$$") == "abc1245" assert helpers.safe_filename("abc##") == "abc"
deprecated, cache, target_directory def test_regex_search_no_match(): with pytest.raises(RegexMatchError): helpers.regex_search("^a$", "", group=0) def test_regex_search(): assert helpers.regex_search("^a$", "a", group=0) == "a" def test_safe_filename():
64
64
45
5
59
Twixes/pytube3
tests/test_helpers.py
Python
test_safe_filename
test_safe_filename
20
23
20
20
451f850a07784d56dd02830e8949bc189c6b430b
bigcode/the-stack
train
6153a5048a22d69116ffc567
train
function
def test_cache(): call_count = 0 @cache def cached_func(stuff): nonlocal call_count call_count += 1 return stuff cached_func("hi") cached_func("hi") cached_func("bye") cached_func("bye") assert call_count == 2
def test_cache():
call_count = 0 @cache def cached_func(stuff): nonlocal call_count call_count += 1 return stuff cached_func("hi") cached_func("hi") cached_func("bye") cached_func("bye") assert call_count == 2
_deprecated(warn): @deprecated("oh no") def deprecated_function(): return None deprecated_function() warn.assert_called_with( "Call to deprecated function deprecated_function (oh no).", category=DeprecationWarning, stacklevel=2, ) def test_cache():
64
64
71
4
60
Twixes/pytube3
tests/test_helpers.py
Python
test_cache
test_cache
40
54
40
40
4271c60550da10551762be49acbf79f9e82f3b79
bigcode/the-stack
train
56e3fe294e3103637bcce16f
train
class
class InputFeatures(object): """A single set of features of data.""" def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self.input_ids = input_ids self.input_mask = input_mask self.input_type_ids = input_type_ids
class InputFeatures(object):
"""A single set of features of data.""" def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self.input_ids = input_ids self.input_mask = input_mask self.input_type_ids = input_type_ids
this should be True " "since it is much faster.") class InputExample(object): def __init__(self, unique_id, text_a, text_b): self.unique_id = unique_id self.text_a = text_a self.text_b = text_b class InputFeatures(object):
64
64
77
5
58
seldas/bert
TF2/extract_features.py
Python
InputFeatures
InputFeatures
89
97
89
89
49274c386419f9664053f2671dfac74440e594b0
bigcode/the-stack
train
412734dd67b1ae20a255b381
train
function
def model_fn_builder(bert_config, init_checkpoint, layer_indexes, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" unique_ids = f...
def model_fn_builder(bert_config, init_checkpoint, layer_indexes, use_tpu, use_one_hot_embeddings):
"""Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument """The `model_fn` for TPUEstimator.""" unique_ids = features["unique_ids"] input_ids = features["input_ids"] input_mask = features["input_mask"] input_type_ids = ...
.int32), "input_ids": tf.constant( all_input_ids, shape=[num_examples, seq_length], dtype=tf.int32), "input_mask": tf.constant( all_input_mask, shape=[num_examples, seq_length], dtype=tf.int32), ...
141
141
473
24
116
seldas/bert
TF2/extract_features.py
Python
model_fn_builder
model_fn_builder
148
207
148
149
b32999a3a3ee47a7d56b9a722ad5547275e719cd
bigcode/the-stack
train
244b78a6e1543ddce1c7abc9
train
function
def _truncate_seq_pair(tokens_a, tokens_b, max_length): """Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one s...
def _truncate_seq_pair(tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length.""" # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very short then each token # that's truncat...
in input_type_ids])) features.append( InputFeatures( unique_id=example.unique_id, tokens=tokens, input_ids=input_ids, input_mask=input_mask, input_type_ids=input_type_ids)) return features def _truncate_seq_pair(tokens_a, tokens_b, max_length):...
64
64
146
14
49
seldas/bert
TF2/extract_features.py
Python
_truncate_seq_pair
_truncate_seq_pair
302
316
302
302
e0549efd31813094d65cd90ad15dfcd4e0c0a190
bigcode/the-stack
train
7ea6a61e052d640f407fafb7
train
function
def read_examples(input_file): """Read a list of `InputExample`s from an input file.""" examples = [] unique_id = 0 with tf.compat.v1.gfile.GFile(input_file, "r") as reader: while True: line = tokenization.convert_to_unicode(reader.readline()) if not line: break line = line.strip()...
def read_examples(input_file):
"""Read a list of `InputExample`s from an input file.""" examples = [] unique_id = 0 with tf.compat.v1.gfile.GFile(input_file, "r") as reader: while True: line = tokenization.convert_to_unicode(reader.readline()) if not line: break line = line.strip() text_a = None text...
information than a longer sequence. while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_length: break if len(tokens_a) > len(tokens_b): tokens_a.pop() else: tokens_b.pop() def read_examples(input_file):
64
64
179
6
58
seldas/bert
TF2/extract_features.py
Python
read_examples
read_examples
319
340
319
319
01335869c957d76fc4d81036ccd95fb7a8ecaec8
bigcode/the-stack
train
25196164c028a60395fded01
train
function
def input_fn_builder(features, seq_length): """Creates an `input_fn` closure to be passed to TPUEstimator.""" all_unique_ids = [] all_input_ids = [] all_input_mask = [] all_input_type_ids = [] for feature in features: all_unique_ids.append(feature.unique_id) all_input_ids.append(feature.input_ids)...
def input_fn_builder(features, seq_length):
"""Creates an `input_fn` closure to be passed to TPUEstimator.""" all_unique_ids = [] all_input_ids = [] all_input_mask = [] all_input_type_ids = [] for feature in features: all_unique_ids.append(feature.unique_id) all_input_ids.append(feature.input_ids) all_input_mask.append(feature.input_mas...
text_a self.text_b = text_b class InputFeatures(object): """A single set of features of data.""" def __init__(self, unique_id, tokens, input_ids, input_mask, input_type_ids): self.unique_id = unique_id self.tokens = tokens self.input_ids = input_ids self.input_mask = input_mask self.inpu...
97
97
326
9
87
seldas/bert
TF2/extract_features.py
Python
input_fn_builder
input_fn_builder
100
145
100
100
afb8d621b1497d9d8b6b0a110a9b08ef304d44f6
bigcode/the-stack
train
e9a8d160879e04593a71d202
train
function
def convert_examples_to_features(examples, seq_length, tokenizer): """Loads a data file into a list of `InputBatch`s.""" features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(...
def convert_examples_to_features(examples, seq_length, tokenizer):
"""Loads a data file into a list of `InputBatch`s.""" features = [] for (ex_index, example) in enumerate(examples): tokens_a = tokenizer.tokenize(example.text_a) tokens_b = None if example.text_b: tokens_b = tokenizer.tokenize(example.text_b) if tokens_b: # Modifies `tokens_a` and `...
tvars, init_checkpoint) if use_tpu: def tpu_scaffold(): tf.train.init_from_checkpoint(init_checkpoint, assignment_map) return tf.train.Scaffold() scaffold_fn = tpu_scaffold else: tf.compat.v1.train.init_from_checkpoint(init_checkpoint, assignment_map) tf.compat....
256
256
922
13
242
seldas/bert
TF2/extract_features.py
Python
convert_examples_to_features
convert_examples_to_features
210
299
210
210
fc4b9b4381f215e99a84335f5276f0ea29265ad1
bigcode/the-stack
train
9042aa3e537fd2ebed5e33f1
train
function
def main(_): tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) layer_indexes = [int(x) for x in FLAGS.layers.split(",")] bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower...
def main(_):
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.INFO) layer_indexes = [int(x) for x in FLAGS.layers.split(",")] bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) is_...
def read_examples(input_file): """Read a list of `InputExample`s from an input file.""" examples = [] unique_id = 0 with tf.compat.v1.gfile.GFile(input_file, "r") as reader: while True: line = tokenization.convert_to_unicode(reader.readline()) if not line: break line = line.strip()...
183
183
611
4
178
seldas/bert
TF2/extract_features.py
Python
main
main
343
410
343
343
962daebbdec5ff283dff5e3ffb5da684a49e6ef6
bigcode/the-stack
train
ca7e4637e445476f485b98b9
train
class
class InputExample(object): def __init__(self, unique_id, text_a, text_b): self.unique_id = unique_id self.text_a = text_a self.text_b = text_b
class InputExample(object):
def __init__(self, unique_id, text_a, text_b): self.unique_id = unique_id self.text_a = text_a self.text_b = text_b
.DEFINE_bool( "use_one_hot_embeddings", False, "If True, tf.one_hot will be used for embedding lookups, otherwise " "tf.nn.embedding_lookup will be used. On TPUs, this should be True " "since it is much faster.") class InputExample(object):
63
64
45
5
58
seldas/bert
TF2/extract_features.py
Python
InputExample
InputExample
81
86
81
82
70847b8e9c847b57fc6c01116a5b1c55d26780fb
bigcode/the-stack
train
e4d6281de49b6582f7bff7ab
train
function
def shrink(filename): """ :param filename: str, the filename of the image to be processed :return img: SimpleImage, the shrunk image """ img = SimpleImage(filename) # Create a blank frame with shrunk size. shrink_img = SimpleImage.blank(img.width//2, img.height//2) # Loop the pix...
def shrink(filename):
""" :param filename: str, the filename of the image to be processed :return img: SimpleImage, the shrunk image """ img = SimpleImage(filename) # Create a blank frame with shrunk size. shrink_img = SimpleImage.blank(img.width//2, img.height//2) # Loop the pixels of the original ima...
""" File: shrink.py Author: David ------------------------------- Create a new "out" image half the width and height of the original. Set pixels at x=0 1 2 3 in out , from x=0 2 4 6 in original, and likewise in the y direction. """ from simpleimage import SimpleImage def shrink(filename):
76
108
363
4
71
YuHaoHan/MystanCodeProjects
stanCode_Projects/my_photoshop/shrink.py
Python
shrink
shrink
13
46
13
13
d2fb257e7ccc355d66b21980580dd80e4165d86a
bigcode/the-stack
train
31904c152f37f53f1fb9ca97
train
function
def main(): """ This program shrinks the image in the x and y direction by a factor of 2. """ original = SimpleImage("images/poppy.png") original.show() after_shrink = shrink("images/poppy.png") after_shrink.show()
def main():
""" This program shrinks the image in the x and y direction by a factor of 2. """ original = SimpleImage("images/poppy.png") original.show() after_shrink = shrink("images/poppy.png") after_shrink.show()
the blank frame. shrink_img_p = shrink_img.get_pixel(x/2, y/2) shrink_img_p.red = red_total // count shrink_img_p.green = green_total // count shrink_img_p.blue = blue_total // count return shrink_img def main():
62
64
60
3
58
YuHaoHan/MystanCodeProjects
stanCode_Projects/my_photoshop/shrink.py
Python
main
main
49
56
49
49
a3dc6d02088d3a80c9a81d4567fb2e54a2938f00
bigcode/the-stack
train
ebe52e6bdac5757f8e1f5ad1
train
class
class Power(IntEnum): """ Power settings. """ BULB_ON = 65535 BULB_OFF = 0
class Power(IntEnum):
""" Power settings. """ BULB_ON = 65535 BULB_OFF = 0
CHOREQUEST = 58 ECHORESPONSE = 59 GET = 101 SETCOLOR = 102 STATE = 107 GETPOWER2 = 116 SETPOWER2 = 117 STATEPOWER2 = 118 class Power(IntEnum):
64
64
28
5
58
TangoAlpha/liffylights
liffylights.py
Python
Power
Power
76
79
76
76
bb07ae3069eeda2425fb8ebe12b41052b4b61a73
bigcode/the-stack
train
bdef0949257d7076cd6ae90c
train
class
class LiffyLights(): """ Provides liffylights API class. """ def __init__(self, device_callback, power_callback, color_callback, server_addr=None, broadcast_addr=None): self._device_callback = device_callback self._power_callback = power_callback self._color_callback = c...
class LiffyLights():
""" Provides liffylights API class. """ def __init__(self, device_callback, power_callback, color_callback, server_addr=None, broadcast_addr=None): self._device_callback = device_callback self._power_callback = power_callback self._color_callback = color_callback ...
STATEHOSTFIRMWARE = 15 GETWIFIINFO = 16 STATEWIFIINFO = 17 GETWIFIFIRMWARE = 18 STATEWIFIFIRMWARE = 19 GETPOWER1 = 20 SETPOWER1 = 21 STATEPOWER1 = 22 GETLABEL = 23 SETLABEL = 24 STATELABEL = 25 GETVERSION = 32 STATEVERSION = 33 GETINFO = 34 STATEINFO = 35 ACK...
256
256
2,704
5
250
TangoAlpha/liffylights
liffylights.py
Python
LiffyLights
LiffyLights
82
451
82
82
a262a92b56874faae6dd0b3dda6785acf2503029
bigcode/the-stack
train
b16254d0d6e332566bbf2df4
train
class
class PayloadType(IntEnum): """ Message payload types. """ GETSERVICE = 2 STATESERVICE = 3 GETHOSTINFO = 12 STATEHOSTINFO = 13 GETHOSTFIRMWARE = 14 STATEHOSTFIRMWARE = 15 GETWIFIINFO = 16 STATEWIFIINFO = 17 GETWIFIFIRMWARE = 18 STATEWIFIFIRMWARE = 19 GETPOWER1 = 20 SE...
class PayloadType(IntEnum):
""" Message payload types. """ GETSERVICE = 2 STATESERVICE = 3 GETHOSTINFO = 12 STATEHOSTINFO = 13 GETHOSTFIRMWARE = 14 STATEHOSTFIRMWARE = 15 GETWIFIINFO = 16 STATEWIFIINFO = 17 GETWIFIFIRMWARE = 18 STATEWIFIFIRMWARE = 19 GETPOWER1 = 20 SETPOWER1 = 21 STATEPOWER1...
_MAX = 65535 # LIFX saturation maximum value BRIGHTNESS_MIN = 0 # LIFX brightness minimum value BRIGHTNESS_MAX = 65535 # LIFX brightness maximum value TEMP_MIN = 2500 # LIFX temperature minimum value TEMP_MAX = 9000 # LIFX temperature maximum value class PayloadType(...
83
83
279
6
76
TangoAlpha/liffylights
liffylights.py
Python
PayloadType
PayloadType
39
73
39
39
81e190317b378a6163efc0d80141ce26708acecc
bigcode/the-stack
train
13bcb7da5238f1d135caf9a7
train
function
def collect_combo(universe, contract_months, tick_db, until=None): """ Creates a combo and initiates real-time data collection for it. Parameters ---------- universe : str, required the universe of futures from which to select the contract contract_months contract_months : tuple, requi...
def collect_combo(universe, contract_months, tick_db, until=None):
""" Creates a combo and initiates real-time data collection for it. Parameters ---------- universe : str, required the universe of futures from which to select the contract contract_months contract_months : tuple, required a tuple of contract months which should make up the leg...
law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pandas as pd import io from...
104
104
349
16
87
quantrocket-codeload/calspread
calspread/collect_combo.py
Python
collect_combo
collect_combo
21
60
21
21
31320b7b19ed0d9fd85182a063a34f12c7198fc5
bigcode/the-stack
train
12b8b1505d46e3553b477fe3
train
class
class ApplicationGatewaysOperations(object): """ApplicationGatewaysOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operati...
class ApplicationGatewaysOperations(object):
"""ApplicationGatewaysOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.netwo...
-------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect ...
256
256
8,161
7
249
LianwMS/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2017_03_01/operations/_application_gateways_operations.py
Python
ApplicationGatewaysOperations
ApplicationGatewaysOperations
28
830
28
28
59be90560f90aa6f6186cc6886ffc36ebce64234
bigcode/the-stack
train
f05bd1aa5afd23f9173e04e0
train
function
def display() : global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB, inW, inH, outW, outH # 기존에 캐버스 있으면 뜯어내기. if canvas != None : canvas.destroy() # 화면 준비 (고정됨) window.geometry(str(outH) + 'x' + str(outW)) canvas = Canvas(window, wi...
def display() :
global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB, inW, inH, outW, outH # 기존에 캐버스 있으면 뜯어내기. if canvas != None : canvas.destroy() # 화면 준비 (고정됨) window.geometry(str(outH) + 'x' + str(outW)) canvas = Canvas(window, width=outW, height=...
H filename = askopenfilename(parent=window, filetypes=(("그림파일", "*.gif;*.jpg;*.png;*.tif;*.bmp"), ("모든파일", "*.*"))) loadImage(filename) # 파일 --> 입력메모리 equal() # 입력메모리--> 출력메모리 def display() :
77
77
258
4
72
yunjung-lee/class_python_data
tk_all_image_analy_ver0.03.py
Python
display
display
106
142
106
107
7cd3516cf996a8b2512a7af342867eaf63cdfd67
bigcode/the-stack
train
06374774f01131348b9afa59
train
function
def equal() : # 동일 영상 알고리즘 global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImageR, outImageG, outImageB = [], [], []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초...
def equal() : # 동일 영상 알고리즘
global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImageR, outImageG, outImageB = [], [], []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초기화) tmpList = [] ...
) : for k in range(outW) : dataR = outImageR[i][k] dataG = outImageG[i][k] dataB = outImageB[i][k] #print(dataR, dataG, dataB, end='/') paper.put('#%02x%02x%02x' % (dataR, dataG, dataB), (k,i)) canvas.pack() def equal() : # 동일 영상 알고리즘
104
105
352
12
92
yunjung-lee/class_python_data
tk_all_image_analy_ver0.03.py
Python
equal
equal
150
212
150
151
d75ece62c3ad5e1f9b34a6d31042e922e43af532
bigcode/the-stack
train
71201e578bb7092c971e9fb4
train
function
def exitFile() : global window, canvas, paper, filename,inImage, outImage,inW, inH, outW, outH pass
def exitFile() :
global window, canvas, paper, filename,inImage, outImage,inW, inH, outW, outH pass
+ value display() def saveFile() : global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR, outImageG, outImageB, inW, inH, outW, outH def exitFile() :
63
64
34
5
57
yunjung-lee/class_python_data
tk_all_image_analy_ver0.03.py
Python
exitFile
exitFile
320
324
320
321
73d4aec845d5daa132ab1bf152f782997634ab82
bigcode/the-stack
train
05b0ae8e3ea1f6b125b1766b
train
function
def addImage() : # 밝게하기 알고리즘 global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImageR, outImageG, outImageB = [], [], []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로...
def addImage() : # 밝게하기 알고리즘
global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB, inW, inH, outW, outH # 중요! 출력메모리의 크기를 결정 outW = inW; outH = inH; outImageR, outImageG, outImageB = [], [], []; tmpList = [] for i in range(outH): # 출력메모리 확보(0으로 초기화) tmpList = [] ...
화) tmpList = [] for k in range(outW): tmpList.append(0) outImageB.append(tmpList[:]) ############################# # 진짜 영상처리 알고리즘을 구현 ############################ for i in range(inH) : for k in range(inW) : outImageR[i][k] = inIm...
143
144
481
14
129
yunjung-lee/class_python_data
tk_all_image_analy_ver0.03.py
Python
addImage
addImage
220
302
220
221
312ddea4536bc7970ef0e8ec3d1723c1f78eb001
bigcode/the-stack
train
dced618357c6948db3c13400
train
function
def saveFile() : global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR, outImageG, outImageB, inW, inH, outW, outH
def saveFile() :
global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR, outImageG, outImageB, inW, inH, outW, outH
][k] + value if inImageB[i][k] + value > 255 : outImageB[i][k] = 255 else : outImageB[i][k] = inImageB[i][k] + value display() def saveFile() :
63
64
51
5
58
yunjung-lee/class_python_data
tk_all_image_analy_ver0.03.py
Python
saveFile
saveFile
307
309
307
308
d44b2aa5a854755e651ce5ac3dbbe19b76f866f4
bigcode/the-stack
train
e4a22d1451ae4226249ba5a2
train
function
def loadImage(fname) : global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB , inW, inH, outW, outH photo = Image(filename=filename) inW = photo.width; inH = photo.height inImageR, inImageG, inImageB = [], [],[]; tmpList = [] for i in range...
def loadImage(fname) :
global window, canvas, paper, filename, inImageR, inImageG, inImageB, outImageR,outImageG,outImageB , inW, inH, outW, outH photo = Image(filename=filename) inW = photo.width; inH = photo.height inImageR, inImageG, inImageB = [], [],[]; tmpList = [] for i in range(inH) : # 입력메모리 확보(0으로 ...
## 영상 처리 및 데이터 분석 툴 from tkinter import *; import os.path ;import math from tkinter.filedialog import * from tkinter.simpledialog import * from wand.image import * ## 함수 선언부 def loadImage(fname) :
53
131
437
6
46
yunjung-lee/class_python_data
tk_all_image_analy_ver0.03.py
Python
loadImage
loadImage
13
86
13
14
793fce724f846fbddb504e90fd3cafd38c933e95
bigcode/the-stack
train
6bb1fa1fbe7807427ebd566d
train
function
def openFile() : global window, canvas, paper, filename,inImageR, inImageG, inImageB, outImageR,outImageG,outImageB ,inW, inH, outW, outH filename = askopenfilename(parent=window, filetypes=(("그림파일", "*.gif;*.jpg;*.png;*.tif;*.bmp"), ("모든파일", "*.*"))) loadImage(filename) # 파일 --> 입력메모리 e...
def openFile() :
global window, canvas, paper, filename,inImageR, inImageG, inImageB, outImageR,outImageG,outImageB ,inW, inH, outW, outH filename = askopenfilename(parent=window, filetypes=(("그림파일", "*.gif;*.jpg;*.png;*.tif;*.bmp"), ("모든파일", "*.*"))) loadImage(filename) # 파일 --> 입력메모리 equal() # 입력메모리--> ...
][k] = r inImageG[i][k] = g inImageB[i][k] = b #print(inImageR[i][k], inImageG[i][k], inImageB[i][k], end='/') photo=None def openFile() :
64
64
119
5
58
yunjung-lee/class_python_data
tk_all_image_analy_ver0.03.py
Python
openFile
openFile
91
101
91
92
0f39a9376457ece69a3110ffb5aaa228a455b7fe
bigcode/the-stack
train
f713678a516a45e9b6c1c850
train
class
class RedisCacheProviderWithHashTestCase(unittest.TestCase): def setUp(self): logging.basicConfig(level=logging.INFO) logging.getLogger('RedisCacheProvider').setLevel(logging.DEBUG) self.options = { 'REDIS_SERVER_ADDRESS': '192.168.1.90', 'REDIS_SERVER_PORT': 6379 ...
class RedisCacheProviderWithHashTestCase(unittest.TestCase):
def setUp(self): logging.basicConfig(level=logging.INFO) logging.getLogger('RedisCacheProvider').setLevel(logging.DEBUG) self.options = { 'REDIS_SERVER_ADDRESS': '192.168.1.90', 'REDIS_SERVER_PORT': 6379 } def tearDown(self): cache_provider = Red...
import logging import unittest from cache.provider.RedisCacheProviderWithHash import RedisCacheProviderWithHash class RedisCacheProviderWithHashTestCase(unittest.TestCase):
33
256
2,172
12
20
eugene-the-red/automata-redis-timeseries
tests/cache/provider/RedisCacheProviderWithHash_test.py
Python
RedisCacheProviderWithHashTestCase
RedisCacheProviderWithHashTestCase
7
207
7
8
8746342381366b0b72f90250b33330504890a42a
bigcode/the-stack
train
4c4358d15407f7f8b962e48a
train
class
class TestPrivateMessageAPI(TestCase): """Tests for the private API for the Message model""" def setUp(self) -> None: """Sets up the APIClient for the tests and creates users""" self.user_one = create_user( email='one@testdomain.com', password='test_password_one', ...
class TestPrivateMessageAPI(TestCase):
"""Tests for the private API for the Message model""" def setUp(self) -> None: """Sets up the APIClient for the tests and creates users""" self.user_one = create_user( email='one@testdomain.com', password='test_password_one', username='test_username_one', ...
email='two@testdomain.com', password='test_password_two', username='test_username_two', ) self.client = APIClient() def test_create_message_unauthorized(self) -> None: """ Tests what happens if a Message is created by an anonymous User """...
256
256
1,754
8
248
MaciejChoromanski/crypton
app/api/tests/test_message_api.py
Python
TestPrivateMessageAPI
TestPrivateMessageAPI
75
303
75
75
eaa26892a41e2fc7e5749a72e3989ea600ab95fc
bigcode/the-stack
train
68a17ff8a73a8abca54b81d1
train
class
class TestPublicMessageAPI(TestCase): """Tests for the public API for the Message model""" def setUp(self) -> None: """Sets up the APIClient for the tests and creates users""" self.user_one = create_user( email='one@testdomain.com', password='test_password_one', ...
class TestPublicMessageAPI(TestCase):
"""Tests for the public API for the Message model""" def setUp(self) -> None: """Sets up the APIClient for the tests and creates users""" self.user_one = create_user( email='one@testdomain.com', password='test_password_one', username='test_username_one', ...
import reverse from freezegun import freeze_time from rest_framework.test import APIClient from rest_framework import status from .utils import ( create_user, create_friend_request, create_friend, create_message, ) from core.models import Message, Friend, User CREATE_MESSAGE_URL = reverse('api:mess...
99
99
331
8
91
MaciejChoromanski/crypton
app/api/tests/test_message_api.py
Python
TestPublicMessageAPI
TestPublicMessageAPI
22
72
22
22
ab4abd0d5e79cae7d6a070ea19be1f7a1efe4563
bigcode/the-stack
train
d7c34052a8ecb43dc84027ff
train
class
class RapidcheckConan(ConanFile): name = "rapidcheck" description = "QuickCheck clone for C++ with the goal of being simple to use with as little boilerplate as possible" url = "https://github.com/conan-io/conan-center-index" homepage = "https://github.com/emil-e/rapidcheck" license = "BSD-2-Clause"...
class RapidcheckConan(ConanFile):
name = "rapidcheck" description = "QuickCheck clone for C++ with the goal of being simple to use with as little boilerplate as possible" url = "https://github.com/conan-io/conan-center-index" homepage = "https://github.com/emil-e/rapidcheck" license = "BSD-2-Clause" topics = "quickcheck", "testi...
from conans import CMake, ConanFile, tools from conans.errors import ConanInvalidConfiguration import os import textwrap required_conan_version = ">=1.43.0" class RapidcheckConan(ConanFile):
51
256
1,547
10
41
rockandsalt/conan-center-index
recipes/rapidcheck/all/conanfile.py
Python
RapidcheckConan
RapidcheckConan
9
156
9
9
67d428e2f1c39a0412e4aa7ae2ff96c49f5fa4a1
bigcode/the-stack
train
17d91b446811204999abb5dc
train
class
class TheoryGuidedModel(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, has_download_instructions=None, keywords=None, has_documentation=None, has_grid=None, software_requirements=None, has_down...
class TheoryGuidedModel(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, has_download_instructions=None, keywords=None, has_documentation=None, has_grid=None, software_requirements=None, has_download_url=None, type=None, has_in...
# coding: utf-8 from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server import util class TheoryGuidedModel(Model):
66
256
13,293
7
58
mintproject/MINT-ModelCatalogIngestionAPI
server/openapi_server/models/theory_guided_model.py
Python
TheoryGuidedModel
TheoryGuidedModel
12
1,719
12
12
df5d38e0ea755556c9a7a66005447060dc6e3927
bigcode/the-stack
train
0d9b0eeda794753f0faf9b57
train
class
@DGL.register() class ALaGCN(NodeClasTrainer): """ Implementation of ALaGCN in `When Do GNNs Work: Understanding and Improving Neighborhood Aggregation <https://www.ijcai.org/Proceedings/2020/0181.pdf>` DGL implementation: <https://github.com/raspberryice/ala-gcn> """ ...
@DGL.register() class ALaGCN(NodeClasTrainer):
""" Implementation of ALaGCN in `When Do GNNs Work: Understanding and Improving Neighborhood Aggregation <https://www.ijcai.org/Proceedings/2020/0181.pdf>` DGL implementation: <https://github.com/raspberryice/ala-gcn> """ def data_step(self, adj_...
import torch import graphgallery.nn.models.dgl as models from graphgallery.data.sequence import FullBatchSequence from graphgallery import functional as gf from graphgallery.gallery.nodeclas import NodeClasTrainer from graphgallery.gallery.nodeclas import DGL @DGL.register() class ALaGCN(NodeClasTrainer):
66
256
908
14
51
houchengbin/GraphGallery
graphgallery/gallery/nodeclas/dgl/ala_gnn/ala_gcn.py
Python
ALaGCN
ALaGCN
9
128
9
10
d67604e792e13f96dd99b361766d9dbf3e027d8a
bigcode/the-stack
train
b89e94a91f2d7cce5e80dab3
train
function
def test_transformer(num_enc_layers=2, num_dec_layers=2, embed_dims=8, num_heads=2, num_query=5, batch_size=1): module = Transformer(embed_dims, num_heads, num_enc_layers, num_dec_layers) height, width = 8, ...
def test_transformer(num_enc_layers=2, num_dec_layers=2, embed_dims=8, num_heads=2, num_query=5, batch_size=1):
module = Transformer(embed_dims, num_heads, num_enc_layers, num_dec_layers) height, width = 8, 6 x = torch.rand(batch_size, embed_dims, height, width) mask = torch.rand(batch_size, height, width) > 0.5 query_embed = torch.rand(num_query, embed_dims) pos_embed = torch.rand(batch_size, embed_dims,...
# return_intermediate module = TransformerDecoder( num_layers, embed_dims, num_heads, feedforward_channels, order=order, return_intermediate=True) out = module(query, memory, memory_pos, query_pos, memory_attn_mask, target_attn_mask, memory_ke...
135
135
451
41
94
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
test_transformer
test_transformer
490
537
490
495
ca61c791ec3422dfe37242a953747798c598c18e
bigcode/the-stack
train
28831fe7fbdecedacacdf845
train
function
def _encoder_layer_forward(self, x, pos=None, attn_mask=None, key_padding_mask=None): norm_cnt = 0 inp_residual = x for layer in self.order: if layer == 'selfattn': x = self.self_a...
def _encoder_layer_forward(self, x, pos=None, attn_mask=None, key_padding_mask=None):
norm_cnt = 0 inp_residual = x for layer in self.order: if layer == 'selfattn': x = self.self_attn( x, x, x, inp_residual if self.pre_norm else None, query_pos=pos, attn_mask=attn_mask, ...
_str = 'selfattn' if selfattn else 'multiheadattn' return x + '_{}(residual={})'.format(attn_str, residual_str) def _encoder_layer_forward(self, x, pos=None, attn_mask=None, key_padding_mask=None):
64
64
187
26
38
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
_encoder_layer_forward
_encoder_layer_forward
53
78
53
57
639e74d7768bd144178a265748564e7b263ae682
bigcode/the-stack
train
aef3ceadcc1b8ad746d8ce15
train
function
def test_transformer_decoder_layer(embed_dims=8, num_heads=2, feedforward_channels=8, num_key=10, num_query=5, batch_size=1): query = torch.r...
def test_transformer_decoder_layer(embed_dims=8, num_heads=2, feedforward_channels=8, num_key=10, num_query=5, batch_size=1):
query = torch.rand(num_query, batch_size, embed_dims) # test invalid number of order with pytest.raises(AssertionError): order = ('norm', 'selfattn', 'norm', 'multiheadattn', 'norm', 'ffn', 'norm') module = TransformerDecoderLayer( embed_dims, num_heads, feedforw...
num_key, batch_size, embed_dims) @patch('mmdet.models.utils.TransformerEncoderLayer.forward', _encoder_layer_forward) @patch('mmdet.models.utils.FFN.forward', _ffn_forward) @patch('mmdet.models.utils.MultiheadAttention.forward', _multihead_attention_forward) def test_order(): ...
256
256
1,039
42
214
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
test_transformer_decoder_layer
test_transformer_decoder_layer
254
367
254
259
97ed9b5c94ab2fb49dabc257060574f80c0122ae
bigcode/the-stack
train
a953d3ef0accf5efec424f3d
train
function
def test_multihead_attention(embed_dims=8, num_heads=2, dropout=0.1, num_query=5, num_key=10, batch_size=1): module = MultiheadAttention(embed_dims, num_heads, dropout) ...
def test_multihead_attention(embed_dims=8, num_heads=2, dropout=0.1, num_query=5, num_key=10, batch_size=1):
module = MultiheadAttention(embed_dims, num_heads, dropout) # self attention query = torch.rand(num_query, batch_size, embed_dims) out = module(query) assert out.shape == (num_query, batch_size, embed_dims) # set key key = torch.rand(num_key, batch_size, embed_dims) out = module(query, ...
=memory_attn_mask, key_padding_mask=memory_key_padding_mask, selfattn=False) inp_residual = x elif layer == 'ffn': x = self.ffn(x, inp_residual if self.pre_norm else None) else: raise ValueError(f'Unsupported layer type {layer}.') r...
116
116
389
41
74
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
test_multihead_attention
test_multihead_attention
125
163
125
130
1ccea763fd4ed39a3604c292b63d8e88453d7421
bigcode/the-stack
train
1dd4904e48b03aa42cdb623c
train
function
def test_transformer_decoder(num_layers=2, embed_dims=8, num_heads=2, feedforward_channels=8, num_key=10, num_query=5, batch_size=1): module =...
def test_transformer_decoder(num_layers=2, embed_dims=8, num_heads=2, feedforward_channels=8, num_key=10, num_query=5, batch_size=1):
module = TransformerDecoder(num_layers, embed_dims, num_heads, feedforward_channels) query = torch.rand(num_query, batch_size, embed_dims) memory = torch.rand(num_key, batch_size, embed_dims) out = module(query, memory) assert out.shape == (1, num_query, batch_size, e...
= module(x, pos, None, key_padding_mask) assert out.shape == (num_key, batch_size, embed_dims) # set attn_mask attn_mask = torch.rand(num_key, num_key) > 0.5 out = module(x, pos, attn_mask, key_padding_mask) assert out.shape == (num_key, batch_size, embed_dims) # pre_norm order = ('norm',...
223
223
744
47
176
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
test_transformer_decoder
test_transformer_decoder
409
487
409
415
a6d0d3a52bd7c3ec715f8d068f74d08765013e20
bigcode/the-stack
train
227347e247a00b85889b2369
train
function
def _ffn_forward(self, x, residual=None): if residual is None: residual = x residual_str = residual.split('_')[-1] if '(residual' in residual_str: residual_str = residual_str.split('(residual')[0] return x + '_ffn(residual={})'.format(residual_str)
def _ffn_forward(self, x, residual=None):
if residual is None: residual = x residual_str = residual.split('_')[-1] if '(residual' in residual_str: residual_str = residual_str.split('(residual')[0] return x + '_ffn(residual={})'.format(residual_str)
# limitations under the License. from unittest.mock import patch import pytest import torch from mmdet.models.utils import (FFN, MultiheadAttention, Transformer, TransformerDecoder, TransformerDecoderLayer, TransformerEncoder, TransformerEncoderLayer) ...
64
64
74
12
52
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
_ffn_forward
_ffn_forward
25
31
25
25
c4ebb4bfe7a5908532b9897df07e581529f2c8db
bigcode/the-stack
train
e450e63ae643d8a2ba109220
train
function
def _multihead_attention_forward(self, x, key=None, value=None, residual=None, query_pos=None, key_pos=None, ...
def _multihead_attention_forward(self, x, key=None, value=None, residual=None, query_pos=None, key_pos=None, ...
if residual is None: residual = x residual_str = residual.split('_')[-1] if '(residual' in residual_str: residual_str = residual_str.split('(residual')[0] attn_str = 'selfattn' if selfattn else 'multiheadattn' return x + '_{}(residual={})'.format(attn_str, residual_str)
'_ffn(residual={})'.format(residual_str) def _multihead_attention_forward(self, x, key=None, value=None, residual=None, query_pos=None, ...
64
64
137
51
13
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
_multihead_attention_forward
_multihead_attention_forward
34
50
34
43
c3247dfcc57a0135004ae8a648a3f62d9a2e4506
bigcode/the-stack
train
f673ac1ccf1a77e2bf44627a
train
function
def test_transformer_encoder_layer(embed_dims=8, num_heads=2, feedforward_channels=8, num_key=10, batch_size=1): x = torch.rand(num_key, batch_size, embed_dims) # test inva...
def test_transformer_encoder_layer(embed_dims=8, num_heads=2, feedforward_channels=8, num_key=10, batch_size=1):
x = torch.rand(num_key, batch_size, embed_dims) # test invalid number of order with pytest.raises(AssertionError): order = ('norm', 'selfattn', 'norm', 'ffn', 'norm') module = TransformerEncoderLayer( embed_dims, num_heads, feedforward_channels, order=order) # test invalid v...
module = FFN(embed_dims, feedforward_channels, 1) module = FFN(embed_dims, feedforward_channels, num_fcs) x = torch.rand(batch_size, embed_dims) out = module(x) assert out.shape == (batch_size, embed_dims) # set residual residual = torch.rand(batch_size, embed_dims) out = module(x, residua...
189
189
631
36
153
Ascend/modelzoo
built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py
Python
test_transformer_encoder_layer
test_transformer_encoder_layer
187
251
187
191
343d20a63eabb75a5498a9b63367ce6665e8acfd
bigcode/the-stack
train