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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
30f5686742be6d5589d41fd2 | train | function | def string_starts_with_number(string):
try:
n = float(string.lstrip()[0])
return True
except:
return False
| def string_starts_with_number(string):
| try:
n = float(string.lstrip()[0])
return True
except:
return False
| import sys
import numpy as np
import math
# absolutely horrible
def string_starts_with_number(string):
| 23 | 64 | 32 | 8 | 14 | Jvanrhijn/tsp-local-search | graph/tsplib_coordinates_to_matrix.py | Python | string_starts_with_number | string_starts_with_number | 7 | 12 | 7 | 7 | 6802472815b945f137dd278867f1dd301bd1a448 | bigcode/the-stack | train |
1ac2dc55e69403f26651a33d | train | function | def get_distance_matrix(points):
d = np.zeros((len(points), len(points)))
for i in range(d.shape[0]):
for j in range(d.shape[1]):
d[i, j] = np.linalg.norm(points[i] - points[j])
return d
| def get_distance_matrix(points):
| d = np.zeros((len(points), len(points)))
for i in range(d.shape[0]):
for j in range(d.shape[1]):
d[i, j] = np.linalg.norm(points[i] - points[j])
return d
| ):
dt = d.T
with open(outpath, "w") as file:
for i, line in enumerate(dt):
for num in line:
file.write(str(num) + " ")
if i != len(dt)-1:
file.write("\n")
def get_distance_matrix(points):
| 64 | 64 | 59 | 6 | 58 | Jvanrhijn/tsp-local-search | graph/tsplib_coordinates_to_matrix.py | Python | get_distance_matrix | get_distance_matrix | 46 | 53 | 46 | 46 | 77c96b25ee9e5ac38a09c77958f361c1fe846f07 | bigcode/the-stack | train |
ee0397e955effff0411ee365 | train | function | def write_distance_matrix(d, outpath):
dt = d.T
with open(outpath, "w") as file:
for i, line in enumerate(dt):
for num in line:
file.write(str(num) + " ")
if i != len(dt)-1:
file.write("\n")
| def write_distance_matrix(d, outpath):
| dt = d.T
with open(outpath, "w") as file:
for i, line in enumerate(dt):
for num in line:
file.write(str(num) + " ")
if i != len(dt)-1:
file.write("\n")
| l = line.split()
xs.append(float(l[1]))
ys.append(float(l[2]))
points = np.zeros((len(xs), 2))
points[:, 0] = xs
points[:, 1] = ys
return points
def write_distance_matrix(d, outpath):
| 64 | 64 | 66 | 9 | 54 | Jvanrhijn/tsp-local-search | graph/tsplib_coordinates_to_matrix.py | Python | write_distance_matrix | write_distance_matrix | 36 | 43 | 36 | 36 | 431142004f41fd1fb1f4ab2a74a0b56111cb17df | bigcode/the-stack | train |
bd7bebe9b8c5a7dfca8dc16f | train | function | def read_distance_matrix(path):
points = read_coordinate_file(path)
return get_distance_matrix(points)
| def read_distance_matrix(path):
| points = read_coordinate_file(path)
return get_distance_matrix(points)
| get_distance_matrix(points):
d = np.zeros((len(points), len(points)))
for i in range(d.shape[0]):
for j in range(d.shape[1]):
d[i, j] = np.linalg.norm(points[i] - points[j])
return d
def read_distance_matrix(path):
| 64 | 64 | 21 | 6 | 57 | Jvanrhijn/tsp-local-search | graph/tsplib_coordinates_to_matrix.py | Python | read_distance_matrix | read_distance_matrix | 56 | 58 | 56 | 56 | 545b662de60053bef451de08da2757c78d90e25c | bigcode/the-stack | train |
878bb3581bc71b5d1f82319e | train | function | def read_coordinate_file(path):
xs = []
ys = []
with open(path, "r") as file:
lines = file.readlines()
coordinates = list(filter(string_starts_with_number, lines))
for line in coordinates:
l = line.split()
xs.append(float(l[1]))
ys.append... | def read_coordinate_file(path):
| xs = []
ys = []
with open(path, "r") as file:
lines = file.readlines()
coordinates = list(filter(string_starts_with_number, lines))
for line in coordinates:
l = line.split()
xs.append(float(l[1]))
ys.append(float(l[2]))
points = np.z... | import sys
import numpy as np
import math
# absolutely horrible
def string_starts_with_number(string):
try:
n = float(string.lstrip()[0])
return True
except:
return False
def read_coordinate_file(path):
| 53 | 64 | 107 | 6 | 46 | Jvanrhijn/tsp-local-search | graph/tsplib_coordinates_to_matrix.py | Python | read_coordinate_file | read_coordinate_file | 15 | 33 | 15 | 15 | 3514e4910e855d1ec37e748ce4477c72f48a54d4 | bigcode/the-stack | train |
e18fec5a565e151a293a5860 | train | function | def load_checkpoint(
checkpoint_path: str, fine_tune_encoder: bool, encoder_lr: float
) -> Tuple[nn.Module, nn.Module, optim.Optimizer, optim.Optimizer, int, int, float, str]:
"""
Load a checkpoint, so that we can continue to train on it.
Parameters
----------
checkpoint_path : str
Path... | def load_checkpoint(
checkpoint_path: str, fine_tune_encoder: bool, encoder_lr: float
) -> Tuple[nn.Module, nn.Module, optim.Optimizer, optim.Optimizer, int, int, float, str]:
| """
Load a checkpoint, so that we can continue to train on it.
Parameters
----------
checkpoint_path : str
Path to the checkpoint to be loaded
fine_tune_encoder : bool
Fine-tune encoder or not
encoder_lr : float
Learning rate of encoder (if fine-tune)
Returns
... | decoder_optimizer,
'caption_model': caption_model
}
filename = 'checkpoint_' + config.model_basename + '.pth.tar'
torch.save(state, config.model_path + filename)
# If this checkpoint is the best so far, store a copy so it doesn't get overwritten by a worse checkpoint
if is_best:
to... | 132 | 132 | 442 | 48 | 84 | Renovamen/Image-Captioning | utils/common.py | Python | load_checkpoint | load_checkpoint | 67 | 132 | 67 | 69 | 505031c66daacdc257111547c428fea2454b2b68 | bigcode/the-stack | train |
0261d81e9136f18eea5c5a2b | train | function | def accuracy(scores: torch.Tensor, targets: torch.Tensor, k: int) -> float:
"""
Compute the top-k accuracy.
Parameters
----------
scores : torch.Tensor
Scores from the model
targets : torch.Tensor
True labels
k : int
k in top-k accuracy
Returns
-------
... | def accuracy(scores: torch.Tensor, targets: torch.Tensor, k: int) -> float:
| """
Compute the top-k accuracy.
Parameters
----------
scores : torch.Tensor
Scores from the model
targets : torch.Tensor
True labels
k : int
k in top-k accuracy
Returns
-------
accuracy : float
Top-k accuracy
"""
batch_size = targets.si... | learning rate with
"""
print("\nDECAYING learning rate.")
for param_group in optimizer.param_groups:
param_group['lr'] = param_group['lr'] * shrink_factor
print("The new learning rate is %f\n" % (optimizer.param_groups[0]['lr'],))
def accuracy(scores: torch.Tensor, targets: torch.Tensor, k: int... | 83 | 83 | 278 | 19 | 64 | Renovamen/Image-Captioning | utils/common.py | Python | accuracy | accuracy | 195 | 229 | 195 | 195 | d19cdb38d6449e5ca9790cd3df1f6cfc710abaa5 | bigcode/the-stack | train |
02d180eb7987915f52098a72 | train | function | def save_checkpoint(
epoch: int,
epochs_since_improvement: int,
encoder: nn.Module,
decoder: nn.Module,
encoder_optimizer: optim.Optimizer,
decoder_optimizer: optim.Optimizer,
caption_model: str,
bleu4: float,
is_best: bool
) -> None:
"""
Save a model checkpoint
Paramete... | def save_checkpoint(
epoch: int,
epochs_since_improvement: int,
encoder: nn.Module,
decoder: nn.Module,
encoder_optimizer: optim.Optimizer,
decoder_optimizer: optim.Optimizer,
caption_model: str,
bleu4: float,
is_best: bool
) -> None:
| """
Save a model checkpoint
Parameters
----------
epoch : int
Epoch number the current checkpoint have been trained for
epochs_since_improvement : int
Number of epochs since last improvement in BLEU-4 score
encoder : nn.Module
Encoder model
decoder : nn.Module... | import torch
from torch import nn, optim
from typing import Tuple
from config import config
def save_checkpoint(
epoch: int,
epochs_since_improvement: int,
encoder: nn.Module,
decoder: nn.Module,
encoder_optimizer: optim.Optimizer,
decoder_optimizer: optim.Optimizer,
caption_model: str,
... | 87 | 109 | 365 | 67 | 19 | Renovamen/Image-Captioning | utils/common.py | Python | save_checkpoint | save_checkpoint | 7 | 65 | 7 | 17 | 767f5f22354270ce1bc8e948a9a8aea5b14ae27c | bigcode/the-stack | train |
b26cb1f495d5dd6be86107ad | train | class | class AverageMeter:
"""
Keep track of most recent, average, sum, and count of a metric
"""
def __init__(self, tag = None, writer = None):
self.writer = writer
self.tag = tag
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
... | class AverageMeter:
| """
Keep track of most recent, average, sum, and count of a metric
"""
def __init__(self, tag = None, writer = None):
self.writer = writer
self.tag = tag
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
... | filter(lambda p: p.requires_grad, encoder.CNN.parameters()),
lr = encoder_lr
)
caption_model = checkpoint['caption_model']
return encoder, encoder_optimizer, decoder, decoder_optimizer, \
start_epoch, epochs_since_improvement, best_bleu4, caption_model
class AverageMeter:
| 64 | 64 | 154 | 4 | 59 | Renovamen/Image-Captioning | utils/common.py | Python | AverageMeter | AverageMeter | 134 | 157 | 134 | 134 | f38952233a10ba3c4cdefdd428bba04a6dd048ea | bigcode/the-stack | train |
2c636973f514ddc95a1a91da | train | function | def adjust_learning_rate(
optimizer: optim.Optimizer, shrink_factor: float
) -> None:
"""
Shrink learning rate by a specified factor.
Parameters
----------
optimizer : optim.Optimizer
Optimizer whose learning rate must be shrunk
shrink_factor : float
Factor in interval (0, ... | def adjust_learning_rate(
optimizer: optim.Optimizer, shrink_factor: float
) -> None:
| """
Shrink learning rate by a specified factor.
Parameters
----------
optimizer : optim.Optimizer
Optimizer whose learning rate must be shrunk
shrink_factor : float
Factor in interval (0, 1) to multiply learning rate with
"""
print("\nDECAYING learning rate.")
for p... | Clip value
"""
for group in optimizer.param_groups:
for param in group['params']:
if param.grad is not None:
param.grad.data.clamp_(-grad_clip, grad_clip)
def adjust_learning_rate(
optimizer: optim.Optimizer, shrink_factor: float
) -> None:
| 64 | 64 | 138 | 21 | 43 | Renovamen/Image-Captioning | utils/common.py | Python | adjust_learning_rate | adjust_learning_rate | 176 | 193 | 176 | 178 | 9abb4651bf07ee6ffdbb39c48a1b5fabd615c8b9 | bigcode/the-stack | train |
b0c998f41f9b499314e62406 | train | function | def clip_gradient(optimizer: optim.Optimizer, grad_clip: float) -> None:
"""
Clip gradients computed during backpropagation to avoid explosion of gradients.
Parameters
----------
optimizer : optim.Optimizer
Optimizer with the gradients to be clipped
grad_clip : float
Clip value... | def clip_gradient(optimizer: optim.Optimizer, grad_clip: float) -> None:
| """
Clip gradients computed during backpropagation to avoid explosion of gradients.
Parameters
----------
optimizer : optim.Optimizer
Optimizer with the gradients to be clipped
grad_clip : float
Clip value
"""
for group in optimizer.param_groups:
for param in gr... | self.sum += val * n
self.count += n
self.avg = self.sum / self.count
# tensorboard
if self.writer is not None:
self.writer.add_scalar(self.tag, val)
def clip_gradient(optimizer: optim.Optimizer, grad_clip: float) -> None:
| 64 | 64 | 106 | 18 | 46 | Renovamen/Image-Captioning | utils/common.py | Python | clip_gradient | clip_gradient | 159 | 174 | 159 | 159 | fe47dd48d7948216747d53b12d77760102273566 | bigcode/the-stack | train |
4fabb82563f4db3f0ecc2e98 | train | class | class NOArticle:
def __init__(self, args):
self.id = str(uuid.uuid4())
if 'author' or 'by' in args.keys():
if 'by' in args.keys():
self.author = args['by']
else:
self.author = args['author']
else:
self.author = None
... | class NOArticle:
| def __init__(self, args):
self.id = str(uuid.uuid4())
if 'author' or 'by' in args.keys():
if 'by' in args.keys():
self.author = args['by']
else:
self.author = args['author']
else:
self.author = None
if 'title' in a... |
import uuid
class NOArticle:
| 8 | 131 | 439 | 4 | 3 | YannickSF/Vision | sources/objects.py | Python | NOArticle | NOArticle | 5 | 77 | 5 | 5 | 12fd84635f45f7bf6582b36b996a6a74b2a558ac | bigcode/the-stack | train |
bfae43f22e5bdc4b8a222808 | train | class | class NOResult:
def __init__(self, args):
if args is not None:
if args != {}:
self.status = args['status']
if self.status == 'ok':
self.totalResults = args['totalResults']
self.articles = []
else:
... | class NOResult:
| def __init__(self, args):
if args is not None:
if args != {}:
self.status = args['status']
if self.status == 'ok':
self.totalResults = args['totalResults']
self.articles = []
else:
self.to... | Image': self.urlToImage,
'publishAt': self.publishedAt,
'content': self.content,
'favoris': self.favoris,
'category': self.category
}
def __str__(self):
return self.__repr__().__str__()
class NOResult:
| 63 | 64 | 148 | 4 | 60 | YannickSF/Vision | sources/objects.py | Python | NOResult | NOResult | 80 | 100 | 80 | 80 | d42df0bd8ac712c2deed192bfb87953f0a750944 | bigcode/the-stack | train |
0420f6db4083db2ab4e0a0ee | train | function | def h_make_polygon(mask):
#mask = np.array(mask)
mask = mask[::-1, :] # for cytomine bottom left
mask = np.ascontiguousarray(mask, dtype=np.uint8)
_, thresh = cv.threshold(mask, 0.001, 255, 0)
thresh = cv.medianBlur(thresh,11)
#thresh = thresh.astype(np.uint8)
components = h_find_components... | def h_make_polygon(mask):
#mask = np.array(mask)
| mask = mask[::-1, :] # for cytomine bottom left
mask = np.ascontiguousarray(mask, dtype=np.uint8)
_, thresh = cv.threshold(mask, 0.001, 255, 0)
thresh = cv.medianBlur(thresh,11)
#thresh = thresh.astype(np.uint8)
components = h_find_components(thresh)
# contour = np.squeeze(contour[0])
... | 02 * w * h)
for i, component in enumerate(components):
components[i] = Polygon(components[i][0])
n_comp = [component for component in components if component.area > min_area]
return n_comp
def h_make_polygon(mask):
#mask = np.array(mask)
| 64 | 64 | 122 | 14 | 49 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | h_make_polygon | h_make_polygon | 222 | 233 | 222 | 223 | d1b379479228c558cc18a3024c680453d98cde30 | bigcode/the-stack | train |
b7eea64f7834f65066ef508d | train | function | def bb_pts(mask):
"""
return coordinate points from predicted mask
"""
# mask = mask.numpy()
mask_arr = np.squeeze(mask, axis=2)
coord = np.where(mask_arr == [255])
y_min = min(coord[0])
y_max = max(coord[0])
x_max = max(coord[1])
x_min = min(coord[1])
dim_x = x_max - x_min
... | def bb_pts(mask):
| """
return coordinate points from predicted mask
"""
# mask = mask.numpy()
mask_arr = np.squeeze(mask, axis=2)
coord = np.where(mask_arr == [255])
y_min = min(coord[0])
y_max = max(coord[0])
x_max = max(coord[1])
x_min = min(coord[1])
dim_x = x_max - x_min
dim_y = y_max - ... | """
image = tf.image.resize_with_pad(image, size, size, method='nearest')
image = tf.cast(image, tf.float32) / 255.0 # normalize the image
image = tf.expand_dims(image, 0)
pred_mask = model.predict(image)
pred_mask = tf.squeeze(pred_mask)
pred_mask = tf.argmax(pred_mask, axis=-1)
pred_mask... | 103 | 103 | 346 | 5 | 97 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | bb_pts | bb_pts | 30 | 73 | 30 | 30 | 9ff171267aae3f19d64308d18fd113d1693b306f | bigcode/the-stack | train |
76bd0c975cba0f6ef4ab931c | train | function | def upscale_pts(pts, size, up_size):
"""
upscale points to original image size to be used for cropping
"""
h, w = size
h_up, w_up = up_size
w_fact = w_up / w
h_fact = h_up / h
up_x1 = pts[0] * w_fact
up_x2 = pts[2] * w_fact
up_y1 = pts[1] * h_fact
up_y2 = pts[3] * h_fact
... | def upscale_pts(pts, size, up_size):
| """
upscale points to original image size to be used for cropping
"""
h, w = size
h_up, w_up = up_size
w_fact = w_up / w
h_fact = h_up / h
up_x1 = pts[0] * w_fact
up_x2 = pts[2] * w_fact
up_y1 = pts[1] * h_fact
up_y2 = pts[3] * h_fact
return [up_x1, up_y1, up_x2, up_y2]
| 2
y_min = y_min - rem_y
y_max = y_max + rem_y
pts = [x_min, y_min, x_max, y_max]
pts = np.asarray(pts).astype(int)
return pts
def upscale_pts(pts, size, up_size):
| 64 | 64 | 136 | 11 | 52 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | upscale_pts | upscale_pts | 76 | 92 | 76 | 76 | 35547b6abd26d55d288e08ab2d773fc280780ea2 | bigcode/the-stack | train |
bf21de7d8768b242c256e9c2 | train | function | def draw_contours(image, h_mask, op_mask):
h_mask = np.array(h_mask)
op_mask = np.array(op_mask)
# main = cv.imread(image_path,cv.IMREAD_GRAYSCALE)
main = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
main = cv.cvtColor(main, cv.COLOR_GRAY2RGB)
br_main = cv.convertScaleAbs(main, alpha=5, beta=40)
... | def draw_contours(image, h_mask, op_mask):
| h_mask = np.array(h_mask)
op_mask = np.array(op_mask)
# main = cv.imread(image_path,cv.IMREAD_GRAYSCALE)
main = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
main = cv.cvtColor(main, cv.COLOR_GRAY2RGB)
br_main = cv.convertScaleAbs(main, alpha=5, beta=40)
######## get contour of head and operculu... | bbox_pts[1]
tr_h = bbox_pts[3] - bbox_pts[1] # target height
tr_w = bbox_pts[2] - bbox_pts[0] # target width
image = tf.image.crop_to_bounding_box(image, h, w, tr_h, tr_w)
return image
def draw_contours(image, h_mask, op_mask):
| 83 | 83 | 277 | 12 | 70 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | draw_contours | draw_contours | 117 | 137 | 117 | 117 | 52dffcb3253a14c2d0cefd4b044e688ec8eaae3d | bigcode/the-stack | train |
73739e953b69689ecc4e3b76 | train | function | def crop_to_aspect(mask, asp_ratio):
cr_h = mask.shape[0] * asp_ratio
cr_h = int(cr_h)
cr_w = mask.shape[1]
crop_mask = tf.image.resize_with_crop_or_pad(mask, cr_h, cr_w)
return crop_mask
| def crop_to_aspect(mask, asp_ratio):
| cr_h = mask.shape[0] * asp_ratio
cr_h = int(cr_h)
cr_w = mask.shape[1]
crop_mask = tf.image.resize_with_crop_or_pad(mask, cr_h, cr_w)
return crop_mask
| = pts[2] * w_fact
up_y1 = pts[1] * h_fact
up_y2 = pts[3] * h_fact
return [up_x1, up_y1, up_x2, up_y2]
def crop_to_aspect(mask, asp_ratio):
| 64 | 64 | 66 | 10 | 54 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | crop_to_aspect | crop_to_aspect | 94 | 101 | 94 | 94 | 05cf4dfe394e943d8131bffaeca1ec5953d13720 | bigcode/the-stack | train |
c6c0ac01095d17b36128e2e2 | train | function | def o_make_polygon(mask):
#mask = np.array(mask)
mask = mask[::-1, :] # for cytomine bottom left
mask = np.ascontiguousarray(mask, dtype=np.uint8)
_, thresh = cv.threshold(mask, 0.001, 255, 0)
#kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
#thresh = cv.morphologyEx(thresh, cv... | def o_make_polygon(mask):
#mask = np.array(mask)
| mask = mask[::-1, :] # for cytomine bottom left
mask = np.ascontiguousarray(mask, dtype=np.uint8)
_, thresh = cv.threshold(mask, 0.001, 255, 0)
#kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (5, 5))
#thresh = cv.morphologyEx(thresh, cv.MORPH_OPEN, kernel, iterations=5)
thresh = cv.me... | (thresh,11)
#thresh = thresh.astype(np.uint8)
components = h_find_components(thresh)
# contour = np.squeeze(contour[0])
# polygon = Polygon(contour)
return components
def o_make_polygon(mask):
#mask = np.array(mask)
| 64 | 64 | 172 | 14 | 49 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | o_make_polygon | o_make_polygon | 235 | 249 | 235 | 236 | 92db53498350d10a25c49dbef09fc54c787fc5df | bigcode/the-stack | train |
a5c80a6238f6fe54dff3bfc5 | train | function | def cropped(mask, image):
"""
Creating cropped image from original size image
"""
bbox_pts = bb_pts(mask)
w = bbox_pts[0]
h = bbox_pts[1]
tr_h = bbox_pts[3] - bbox_pts[1] # target height
tr_w = bbox_pts[2] - bbox_pts[0] # target width
image = tf.image.crop_to_bounding_box(image, h, w, tr... | def cropped(mask, image):
| """
Creating cropped image from original size image
"""
bbox_pts = bb_pts(mask)
w = bbox_pts[0]
h = bbox_pts[1]
tr_h = bbox_pts[3] - bbox_pts[1] # target height
tr_w = bbox_pts[2] - bbox_pts[0] # target width
image = tf.image.crop_to_bounding_box(image, h, w, tr_h, tr_w)
return imag... | _ratio):
cr_h = mask.shape[0] * asp_ratio
cr_h = int(cr_h)
cr_w = mask.shape[1]
crop_mask = tf.image.resize_with_crop_or_pad(mask, cr_h, cr_w)
return crop_mask
def cropped(mask, image):
| 64 | 64 | 110 | 6 | 57 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | cropped | cropped | 103 | 114 | 103 | 103 | 404d0a62c9bee7bf1103b7e53abbe85c92d838c9 | bigcode/the-stack | train |
5ecc1b86d1bb79744d10a85b | train | function | def op_pad_up(h_mask, op_mask, size, upsize):
"""
Upsize the cropped version of the predicted op_mask to original
image size to be used to find the contours of the operculum
"""
h_bb = bb_pts(h_mask)
h_bb_up = upscale_pts(h_bb, size, upsize)
h_bb_up = np.asarray(h_bb_up)
h_bb_up = tf.dtypes.cast(... | def op_pad_up(h_mask, op_mask, size, upsize):
| """
Upsize the cropped version of the predicted op_mask to original
image size to be used to find the contours of the operculum
"""
h_bb = bb_pts(h_mask)
h_bb_up = upscale_pts(h_bb, size, upsize)
h_bb_up = np.asarray(h_bb_up)
h_bb_up = tf.dtypes.cast(h_bb_up, tf.int32)
pad_arr = np.zeros(upsi... | resh,9)
#thresh = thresh.astype(np.uint8)
components = o_find_components(thresh)
# contour = np.squeeze(contour[0])
# polygon = Polygon(contour)
return components
def op_pad_up(h_mask, op_mask, size, upsize):
| 64 | 64 | 177 | 15 | 48 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | op_pad_up | op_pad_up | 252 | 268 | 252 | 252 | ce21f9f2569756550894400ed3b837024bfed225 | bigcode/the-stack | train |
e259716738086eb810da8a9c | train | function | def predict_mask(image, model, size):
"""
Predict the mask from image
"""
image = tf.image.resize_with_pad(image, size, size, method='nearest')
image = tf.cast(image, tf.float32) / 255.0 # normalize the image
image = tf.expand_dims(image, 0)
pred_mask = model.predict(image)
pred_mask = tf.sq... | def predict_mask(image, model, size):
| """
Predict the mask from image
"""
image = tf.image.resize_with_pad(image, size, size, method='nearest')
image = tf.cast(image, tf.float32) / 255.0 # normalize the image
image = tf.expand_dims(image, 0)
pred_mask = model.predict(image)
pred_mask = tf.squeeze(pred_mask)
pred_mask = tf.ar... | -*-
"""
Created on Wed Aug 5 11:22:47 2020
@author: Navdeep Kumar
"""
import tensorflow as tf
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from shapely.geometry import Polygon
def predict_mask(image, model, size):
| 64 | 64 | 117 | 9 | 54 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | predict_mask | predict_mask | 15 | 27 | 15 | 15 | b712436db63265514a434881dd064c05e46166cb | bigcode/the-stack | train |
e5bbab49938cbc3e5d4baad5 | train | function | def pad_to_patch(image, patch_size):
"""
Padd the image to match with the integer patch count
"""
h = im.shape[0]
w = im.shape[1]
h_offset = (patch_size - h % patch_size)//2
w_offset = (patch_size - w % patch_size)//2
re_image = cv.copyMakeBorder(im, h_offset, h_offset, w_offset, w_offs... | def pad_to_patch(image, patch_size):
| """
Padd the image to match with the integer patch count
"""
h = im.shape[0]
w = im.shape[1]
h_offset = (patch_size - h % patch_size)//2
w_offset = (patch_size - w % patch_size)//2
re_image = cv.copyMakeBorder(im, h_offset, h_offset, w_offset, w_offset, cv.BORDER_REFLECT)
return re_... | y_min, x_max, y_max = h_bb_up # pts from head
pad_arr[y_min:y_max, x_min:x_max] = op_mask
pad_arr = np.expand_dims(pad_arr, axis=2)
return pad_arr
def pad_to_patch(image, patch_size):
| 64 | 64 | 105 | 9 | 54 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | pad_to_patch | pad_to_patch | 270 | 280 | 270 | 270 | e1365b9cf484085aca7e3750f45829ab628e60ef | bigcode/the-stack | train |
a82cf4d46d668c9c016eb015 | train | function | def h_find_components(image):
contours, hierarchy = cv.findContours(image, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)
components = []
if len(contours) > 0:
top_index = 0
tops_remaining = True
while tops_remaining:
exterior = contours[top_index][:, 0, :].tolist()
in... | def h_find_components(image):
| contours, hierarchy = cv.findContours(image, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)
components = []
if len(contours) > 0:
top_index = 0
tops_remaining = True
while tops_remaining:
exterior = contours[top_index][:, 0, :].tolist()
interiors = []
# che... | , cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
o_contours, _ = cv.findContours(op_thresh, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
cv.drawContours(br_main, h_contours, -1, (0, 255, 255), 1)
cv.drawContours(br_main, o_contours, -1, (255, 0, 255), 1)
plt.imshow(br_main)
def h_find_components(image):
| 102 | 102 | 341 | 6 | 96 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | h_find_components | h_find_components | 140 | 179 | 140 | 140 | eeb1f091ca3a27910e3b5175603405d2e88f6f4e | bigcode/the-stack | train |
69b759d498c3860de535c103 | train | function | def o_find_components(image):
contours, hierarchy = cv.findContours(image, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)
components = []
if len(contours) > 0:
top_index = 0
tops_remaining = True
while tops_remaining:
exterior = contours[top_index][:, 0, :].tolist()
in... | def o_find_components(image):
| contours, hierarchy = cv.findContours(image, cv.RETR_LIST, cv.CHAIN_APPROX_NONE)
components = []
if len(contours) > 0:
top_index = 0
tops_remaining = True
while tops_remaining:
exterior = contours[top_index][:, 0, :].tolist()
interiors = []
# che... | 0] != -1:
top_index = hierarchy[0][top_index][0]
else:
tops_remaining = False
h, w = image.shape[:2]
min_area = int(0.02 * w * h)
for i, component in enumerate(components):
components[i] = Polygon(components[i][0])
n_comp = [component for component in ... | 102 | 102 | 342 | 6 | 95 | navdeepkaushish/S_Zebrafish_Head_Operculum_UNet_Segmentation | utils.py | Python | o_find_components | o_find_components | 180 | 219 | 180 | 180 | 43b18ceb02b95ceaf75b2d0a1bc05058853e7015 | bigcode/the-stack | train |
0048427605c00bc8bbf2cd6e | train | function | def get_split(split_name, dataset_dir, file_pattern=None, reader=None):
"""Gets a dataset tuple with instructions for reading ImageNet.
Args:
split_name: A train/test split name.
dataset_dir: The base directory of the dataset sources.
file_pattern: The file pattern to use when matching the dataset sour... | def get_split(split_name, dataset_dir, file_pattern=None, reader=None):
| """Gets a dataset tuple with instructions for reading ImageNet.
Args:
split_name: A train/test split name.
dataset_dir: The base directory of the dataset sources.
file_pattern: The file pattern to use when matching the dataset sources.
It is assumed that the pattern contains a '%s' string so that... | to just one class.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import tensorflow as tf
slim = tf.contrib.slim
_FILE_PATTERN = '%s-*'
_SPLITS_TO_SIZES = {
'train': 1281167,
'validation': 50000,
}
_ITEMS_TO_DESCRIPTIONS = {
... | 183 | 183 | 610 | 16 | 166 | SimiaCryptus/models | research/adv_imagenet_models/imagenet.py | Python | get_split | get_split | 52 | 119 | 52 | 52 | cd45eaf916183489a4fd4a85302e22474ee27a98 | bigcode/the-stack | train |
a5b5f8341be8f6baf46d946d | train | function | def run_sleep(period):
proc = subprocess.Popen(['sleep', str(period)])
return proc
| def run_sleep(period):
| proc = subprocess.Popen(['sleep', str(period)])
return proc
| import subprocess
from time import time
def run_sleep(period):
| 13 | 64 | 20 | 5 | 7 | zeroam/TIL | python/subprocess/subprocess_wait.py | Python | run_sleep | run_sleep | 5 | 7 | 5 | 5 | 5e1c7f791e70fb5120b14fdbcc38eeacd724fa79 | bigcode/the-stack | train |
fc50c0436edaa392f1fc453b | train | class | class GAMESS(logfileparser.Logfile):
"""A GAMESS/Firefly log file."""
# Used to index self.scftargets[].
SCFRMS, SCFMAX, SCFENERGY = list(range(3))
# Used to extact Dunning basis set names.
dunningbas = {'CCD': 'cc-pVDZ', \
'CCT': 'cc-pVTZ', \
'CCQ': 'cc-pVQZ', \
... | class GAMESS(logfileparser.Logfile):
| """A GAMESS/Firefly log file."""
# Used to index self.scftargets[].
SCFRMS, SCFMAX, SCFENERGY = list(range(3))
# Used to extact Dunning basis set names.
dunningbas = {'CCD': 'cc-pVDZ', \
'CCT': 'cc-pVTZ', \
'CCQ': 'cc-pVQZ', \
'CC5': 'cc-pV5Z', \
'CC... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2018, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Parser for GAMESS(US) output files"""
from __future__ import print_function
import re
import numpy
from cclib.pars... | 111 | 256 | 16,335 | 9 | 101 | peter-reinholdt/cclib | cclib/parser/gamessparser.py | Python | GAMESS | GAMESS | 21 | 1,457 | 21 | 21 | cd3b950aa99a6b0ad19815b6625e3d5c92436cf3 | bigcode/the-stack | train |
5bf8e4edee064dc3995763c1 | train | class | class AlipayCommerceAntestAlipayversionQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayCommerceAntestAlipayversionQueryResponse, self).__init__()
self._data = None
@property
def data(self):
return self._data
@data.setter
def data(self, value):
if isi... | class AlipayCommerceAntestAlipayversionQueryResponse(AlipayResponse):
| def __init__(self):
super(AlipayCommerceAntestAlipayversionQueryResponse, self).__init__()
self._data = None
@property
def data(self):
return self._data
@data.setter
def data(self, value):
if isinstance(value, list):
self._data = list()
for i... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayCommerceAntestAlipayversionQueryResponse(AlipayResponse):
| 48 | 64 | 152 | 16 | 31 | antopen/alipay-sdk-python-all | alipay/aop/api/response/AlipayCommerceAntestAlipayversionQueryResponse.py | Python | AlipayCommerceAntestAlipayversionQueryResponse | AlipayCommerceAntestAlipayversionQueryResponse | 8 | 28 | 8 | 9 | 4ff505bfd44e396ffb794c56c5ed0324f4131096 | bigcode/the-stack | train |
c63aba46c169354d5c0154f8 | train | class | class Migration(migrations.Migration):
dependencies = [
('users', '0002_auto_20170619_1234'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='midea_ssotoken',
field=models.CharField(default=False, max_length=100),
),
]
| class Migration(migrations.Migration):
| dependencies = [
('users', '0002_auto_20170619_1234'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='midea_ssotoken',
field=models.CharField(default=False, max_length=100),
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-06-19 14:34
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
| 54 | 64 | 71 | 7 | 46 | haisome/django-Julyblog | apps/users/migrations/0003_userprofile_midea_ssotoken.py | Python | Migration | Migration | 8 | 20 | 8 | 9 | 4a0e9107e4ad29a62fc344f254599aca43d11e14 | bigcode/the-stack | train |
639fb0563fdcc1dc6310fdc1 | train | class | class SSDMobileNetV1FeatureExtractor(ssd_meta_arch.SSDFeatureExtractor):
"""SSD Feature Extractor using MobilenetV1 features."""
def __init__(self,
depth_multiplier,
min_depth,
conv_hyperparams,
reuse_weights=None):
"""MobileNetV1 Feature Extractor fo... | class SSDMobileNetV1FeatureExtractor(ssd_meta_arch.SSDFeatureExtractor):
| """SSD Feature Extractor using MobilenetV1 features."""
def __init__(self,
depth_multiplier,
min_depth,
conv_hyperparams,
reuse_weights=None):
"""MobileNetV1 Feature Extractor for SSD Models.
Args:
depth_multiplier: float depth multiplier f... | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Travis Yates
"""SSDFeatureExtractor for MobilenetV1 features."""
import tensorflow as tf
from object_detection.meta_architectures import ssd_meta_arch
from object_detection.models import feature_map_generators
from nets import mobilenet_v1
slim = tf.... | 91 | 189 | 631 | 17 | 73 | travisyates81/object-detection | object_detection/models/ssd_mobilenet_v1_feature_extractor.py | Python | SSDMobileNetV1FeatureExtractor | SSDMobileNetV1FeatureExtractor | 16 | 90 | 16 | 16 | 921e8cbf0954a4fe3559e5b9bdeead37d78c2b4b | bigcode/the-stack | train |
f913d582b20260e1e417b6e2 | train | function | def _is_iterable_container(x):
return hasattr(x, '__iter__')
| def _is_iterable_container(x):
| return hasattr(x, '__iter__')
| # are used primarily for routing range-sharded keyspace queries.
self.sharding_key = None
self.entity_column_name = None
self.entity_id_sharding_key_map = None
self.keyrange = None
self.shard_name = None
def _is_iterable_container(x):
| 64 | 64 | 17 | 8 | 55 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | _is_iterable_container | _is_iterable_container | 50 | 51 | 50 | 50 | 2cbd7fd3f1586a043cef032e8d33218e87610c5c | bigcode/the-stack | train |
701199f079bc0d89ecdb4824 | train | function | def write_db_class_method(*pargs, **kwargs):
"""Used for DML methods. Calls db_class_method."""
kwargs["write_method"] = True
return db_class_method(*pargs, **kwargs)
| def write_db_class_method(*pargs, **kwargs):
| """Used for DML methods. Calls db_class_method."""
kwargs["write_method"] = True
return db_class_method(*pargs, **kwargs)
| disabled on view", table_class)
if pargs[2:]:
return method(table_class, cursor, *pargs[2:], **kwargs)
else:
return method(table_class, cursor, **kwargs)
return _db_wrapper
def write_db_class_method(*pargs, **kwargs):
| 64 | 64 | 46 | 12 | 51 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | write_db_class_method | write_db_class_method | 186 | 189 | 186 | 186 | ca73837863a6e0b26827f37af181ab5ae14317f4 | bigcode/the-stack | train |
20c31d6220c20825c2b035a6 | train | function | def create_stream_cursor_from_cursor(original_cursor):
"""
This method creates streaming cursor from a regular cursor.
Args:
original_cursor: Cursor of VTGateCursor type
Returns:
Returns StreamVTGateCursor that is not writable.
"""
if not isinstance(original_cursor, vtgate_cursor.VTGateCursor):
... | def create_stream_cursor_from_cursor(original_cursor):
| """
This method creates streaming cursor from a regular cursor.
Args:
original_cursor: Cursor of VTGateCursor type
Returns:
Returns StreamVTGateCursor that is not writable.
"""
if not isinstance(original_cursor, vtgate_cursor.VTGateCursor):
raise dbexceptions.ProgrammingError(
"Origina... | .
table_class: table for which the cursor is being created.
Returns:
cursor
"""
cursor = table_class.create_vtgate_cursor(old_cursor._conn,
old_cursor.tablet_type,
old_cursor.is_writable())
return cursor
def create_... | 64 | 64 | 146 | 9 | 54 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | create_stream_cursor_from_cursor | create_stream_cursor_from_cursor | 105 | 124 | 105 | 105 | ce8af8b0247e93f618daed63af20f33b9291ee7c | bigcode/the-stack | train |
bf13dda614b302a284f6cd7d | train | function | def db_class_method(*pargs, **kwargs):
"""This function calls db_wrapper to create the appropriate cursor."""
return classmethod(db_wrapper(*pargs, **kwargs))
| def db_class_method(*pargs, **kwargs):
| """This function calls db_wrapper to create the appropriate cursor."""
return classmethod(db_wrapper(*pargs, **kwargs))
| )
return _db_wrapper
def write_db_class_method(*pargs, **kwargs):
"""Used for DML methods. Calls db_class_method."""
kwargs["write_method"] = True
return db_class_method(*pargs, **kwargs)
def db_class_method(*pargs, **kwargs):
| 64 | 64 | 37 | 11 | 53 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | db_class_method | db_class_method | 192 | 194 | 192 | 192 | 1dcc503904191a9ec7a6eba31ce24edfd1948c5d | bigcode/the-stack | train |
991c24bf16fada938cfa7593 | train | class | class InvalidUtf8DbWrite(dbexceptions.Error):
"""Raised when an attempt to write invalid utf-8 to the DB is made.
"""
template = ("Attempt to write invalid utf-8 strings to the DB table '%s' in "
"columns %s")
def __init__(self, table_name, columns):
self.table_name = table_name
self.colu... | class InvalidUtf8DbWrite(dbexceptions.Error):
| """Raised when an attempt to write invalid utf-8 to the DB is made.
"""
template = ("Attempt to write invalid utf-8 strings to the DB table '%s' in "
"columns %s")
def __init__(self, table_name, columns):
self.table_name = table_name
self.columns = columns
self.template_args = (table_... | _method"] = True
return db_class_method(*pargs, **kwargs)
def db_class_method(*pargs, **kwargs):
"""This function calls db_wrapper to create the appropriate cursor."""
return classmethod(db_wrapper(*pargs, **kwargs))
class InvalidUtf8DbWrite(dbexceptions.Error):
| 64 | 64 | 114 | 10 | 54 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | InvalidUtf8DbWrite | InvalidUtf8DbWrite | 197 | 207 | 197 | 197 | efeedbb4f48dda4f154995801df6ce78003b124a | bigcode/the-stack | train |
cb859a6a84a0d2846de68a6a | train | class | class ShardRouting(object):
"""VTGate Shard Routing Class.
Attributes:
keyspace: keyspace where the table resides.
sharding_key: sharding key of the table.
keyrange: keyrange for the query.
entity_column_name: the name of the lookup based entity used for routing.
entity_id_sharding_key_map: this map is u... | class ShardRouting(object):
| """VTGate Shard Routing Class.
Attributes:
keyspace: keyspace where the table resides.
sharding_key: sharding key of the table.
keyrange: keyrange for the query.
entity_column_name: the name of the lookup based entity used for routing.
entity_id_sharding_key_map: this map is used for in clause queries.
... | range
from vtdb import keyrange_constants
from vtdb import shard_constants
from vtdb import sql_builder
from vtdb import vtgate_cursor
class __EmptyBindVariables(frozenset):
pass
EmptyBindVariables = __EmptyBindVariables()
class ShardRouting(object):
| 64 | 64 | 201 | 6 | 58 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | ShardRouting | ShardRouting | 27 | 47 | 27 | 27 | 3f789eba5405a313556982c8b872c54573c32fcd | bigcode/the-stack | train |
847d6b04fe2caebfb86729b5 | train | function | def create_batch_cursor_from_cursor(original_cursor, writable=False):
"""
This method creates a batch cursor from a regular cursor.
Args:
original_cursor: Cursor of VTGateCursor type
Returns:
Returns BatchVTGateCursor that has same attributes as original_cursor.
"""
if not isinstance(original_curs... | def create_batch_cursor_from_cursor(original_cursor, writable=False):
| """
This method creates a batch cursor from a regular cursor.
Args:
original_cursor: Cursor of VTGateCursor type
Returns:
Returns BatchVTGateCursor that has same attributes as original_cursor.
"""
if not isinstance(original_cursor, vtgate_cursor.VTGateCursor):
raise dbexceptions.ProgrammingErr... | .StreamVTGateCursor(
original_cursor._conn, original_cursor.keyspace,
original_cursor.tablet_type,
keyspace_ids=original_cursor.keyspace_ids,
keyranges=original_cursor.keyranges,
writable=False)
return stream_cursor
def create_batch_cursor_from_cursor(original_cursor, writable=False):
| 64 | 64 | 129 | 12 | 51 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | create_batch_cursor_from_cursor | create_batch_cursor_from_cursor | 127 | 144 | 127 | 127 | 6b6a7221c1b5a5bff14ea98bb5c833c518e79b99 | bigcode/the-stack | train |
c39b9918968a7ed8dcd6c3b3 | train | function | def db_wrapper(method, **decorator_kwargs):
"""Decorator that is used to create the appropriate cursor
for the table and call the database method with it.
Args:
method: Method to decorate.
decorator_kwargs: Keyword args for db_wrapper.
Returns:
Decorated method.
"""
@functools.wraps(method)
... | def db_wrapper(method, **decorator_kwargs):
| """Decorator that is used to create the appropriate cursor
for the table and call the database method with it.
Args:
method: Method to decorate.
decorator_kwargs: Keyword args for db_wrapper.
Returns:
Decorated method.
"""
@functools.wraps(method)
def _db_wrapper(*pargs, **kwargs):
table... | original_cursor.
"""
if not isinstance(original_cursor, vtgate_cursor.VTGateCursor):
raise dbexceptions.ProgrammingError(
"Original cursor should be of VTGateCursor type.")
batch_cursor = vtgate_cursor.BatchVTGateCursor(
original_cursor._conn,
original_cursor.tablet_type,
writable=w... | 85 | 85 | 286 | 10 | 74 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | db_wrapper | db_wrapper | 147 | 183 | 147 | 147 | f42161170bb8d103e12b1093de3e20b540f692ec | bigcode/the-stack | train |
7d03d1aacf6338bc2d2dd027 | train | class | class DBObjectBase(object):
"""Base class for db classes.
This abstracts sharding information and provides helper methods
for common database access operations.
"""
keyspace = None
sharding = None
table_name = None
id_column_name = None
is_mysql_view = False
utf8_columns = None
@classmethod
d... | class DBObjectBase(object):
| """Base class for db classes.
This abstracts sharding information and provides helper methods
for common database access operations.
"""
keyspace = None
sharding = None
table_name = None
id_column_name = None
is_mysql_view = False
utf8_columns = None
@classmethod
def create_shard_routing(clas... | writes disabled on view", table_class)
if pargs[2:]:
return method(table_class, cursor, *pargs[2:], **kwargs)
else:
return method(table_class, cursor, **kwargs)
return _db_wrapper
def write_db_class_method(*pargs, **kwargs):
"""Used for DML methods. Calls db_class_method."""
kwargs["write_m... | 256 | 256 | 1,472 | 6 | 250 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | DBObjectBase | DBObjectBase | 210 | 400 | 210 | 210 | 1df5e18f8cb6e0f11040debf3426fd182db2b83f | bigcode/the-stack | train |
5868d21137c254c4b3e1cea8 | train | function | def create_cursor_from_params(vtgate_conn, tablet_type, is_dml, table_class):
"""This method creates the cursor from the required params.
This is mainly used for creating lookup cursor during create_shard_routing,
as there is no real cursor available.
Args:
vtgate_conn: connection to vtgate server.
ta... | def create_cursor_from_params(vtgate_conn, tablet_type, is_dml, table_class):
| """This method creates the cursor from the required params.
This is mainly used for creating lookup cursor during create_shard_routing,
as there is no real cursor available.
Args:
vtgate_conn: connection to vtgate server.
tablet_type: tablet type for the cursor.
is_dml: indicates writable cursor o... | .split(' ')[0]
first_kw = first_kw.lower()
if first_kw == INSERT_KW or first_kw == UPDATE_KW or first_kw == DELETE_KW:
return True
return False
def create_cursor_from_params(vtgate_conn, tablet_type, is_dml, table_class):
| 64 | 64 | 139 | 20 | 43 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | create_cursor_from_params | create_cursor_from_params | 67 | 83 | 67 | 67 | d70fa39aab8090d6dffd3cdd93a1732b860e13e7 | bigcode/the-stack | train |
bd40733ef4bf2765bf0cfa79 | train | class | class __EmptyBindVariables(frozenset):
pass
| class __EmptyBindVariables(frozenset):
| pass
| import dbexceptions
from vtdb import db_validator
from vtdb import keyrange
from vtdb import keyrange_constants
from vtdb import shard_constants
from vtdb import sql_builder
from vtdb import vtgate_cursor
class __EmptyBindVariables(frozenset):
| 64 | 64 | 13 | 10 | 53 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | __EmptyBindVariables | __EmptyBindVariables | 22 | 23 | 22 | 22 | 4a2f45f9ef6ce4f587fb388f143578b1ef2524b8 | bigcode/the-stack | train |
30bfa62494c2f2991537c114 | train | function | def create_cursor_from_old_cursor(old_cursor, table_class):
"""This method creates the cursor from an existing cursor.
This is mainly used for creating lookup cursor during db operations on
other database tables.
Args:
old_cursor: existing cursor from which important params are evaluated.
table_class:... | def create_cursor_from_old_cursor(old_cursor, table_class):
| """This method creates the cursor from an existing cursor.
This is mainly used for creating lookup cursor during db operations on
other database tables.
Args:
old_cursor: existing cursor from which important params are evaluated.
table_class: table for which the cursor is being created.
Returns:
... | writable cursor or not.
table_class: table for which the cursor is being created.
Returns:
cursor
"""
cursor = table_class.create_vtgate_cursor(vtgate_conn, tablet_type, is_dml)
return cursor
def create_cursor_from_old_cursor(old_cursor, table_class):
| 64 | 64 | 113 | 12 | 51 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | create_cursor_from_old_cursor | create_cursor_from_old_cursor | 86 | 102 | 86 | 86 | f52e457c8ac66c4182a2e4a267631103c4dd6c66 | bigcode/the-stack | train |
4700746cbbde410fb74cc0d7 | train | function | def is_dml(sql):
first_kw = sql.split(' ')[0]
first_kw = first_kw.lower()
if first_kw == INSERT_KW or first_kw == UPDATE_KW or first_kw == DELETE_KW:
return True
return False
| def is_dml(sql):
| first_kw = sql.split(' ')[0]
first_kw = first_kw.lower()
if first_kw == INSERT_KW or first_kw == UPDATE_KW or first_kw == DELETE_KW:
return True
return False
| _key_map = None
self.keyrange = None
self.shard_name = None
def _is_iterable_container(x):
return hasattr(x, '__iter__')
INSERT_KW = "insert"
UPDATE_KW = "update"
DELETE_KW = "delete"
def is_dml(sql):
| 64 | 64 | 55 | 6 | 58 | kmiku7/vitess-annotated | py/vtdb/db_object.py | Python | is_dml | is_dml | 59 | 64 | 59 | 59 | c870f1d48d1f0280a98c879db54068818e9df240 | bigcode/the-stack | train |
9c29e10828c6834950abc546 | train | function | def text_to_int(text):
return np.array([char2idx[c] for c in text])
| def text_to_int(text):
| return np.array([char2idx[c] for c in text])
| ourselves. We are going to encode each unique character as a different integer.
"""
vocab = sorted(set(text))
# Creating a mapping from unique characters to indices
char2idx = {u:i for i, u in enumerate(vocab)}
idx2char = np.array(vocab)
def text_to_int(text):
| 64 | 64 | 21 | 6 | 58 | Reeju2019/Projects | Mechine_learning/rnn_play_generator.py | Python | text_to_int | text_to_int | 99 | 100 | 99 | 99 | 0950c533bdf33bf644fc32da1311be1eb2b4444f | bigcode/the-stack | train |
45c8ad2337e05079b83db3b1 | train | function | def split_input_target(chunk): # for the example: hello
input_text = chunk[:-1] # hell
target_text = chunk[1:] # ello
return input_text, target_text # hell, ello
| def split_input_target(chunk): # for the example: hello
| input_text = chunk[:-1] # hell
target_text = chunk[1:] # ello
return input_text, target_text # hell, ello
| len(text)//(seq_length+1)
# Create training examples / targets
char_dataset = tf.data.Dataset.from_tensor_slices(text_as_int)
"""Next we can use the batch method to turn this stream of characters into batches of desired length."""
def split_input_target(chunk): # for the example: hello
| 64 | 64 | 51 | 14 | 50 | Reeju2019/Projects | Mechine_learning/rnn_play_generator.py | Python | split_input_target | split_input_target | 137 | 140 | 137 | 137 | 6bfdd611729a5c6f56819757448fd598790a240d | bigcode/the-stack | train |
f6edd5b26965a96d82fb8f66 | train | function | def generate_text(model, start_string):
# Evaluation step (generating text using the learned model)
# Number of characters to generate
num_generate = 800
# Converting our start string to numbers (vectorizing)
input_eval = [char2idx[s] for s in start_string]
input_eval = tf.expand_dims(input_eval, 0)
# ... | def generate_text(model, start_string):
# Evaluation step (generating text using the learned model)
# Number of characters to generate
| num_generate = 800
# Converting our start string to numbers (vectorizing)
input_eval = [char2idx[s] for s in start_string]
input_eval = tf.expand_dims(input_eval, 0)
# Empty string to store our results
text_generated = []
# Low temperatures results in more predictable text.
# Higher temperatures resu... | (tf.train.load_checkpoint("./training_checkpoints/ckpt_" + str(checkpoint_num)))
model.build(tf.TensorShape([1, None]))
"""##Generating Text
Now we can use the lovely function provided by tensorflow to generate some text using any starting string we'd like.
"""
def generate_text(model, start_string):
# Evaluation st... | 84 | 84 | 283 | 29 | 55 | Reeju2019/Projects | Mechine_learning/rnn_play_generator.py | Python | generate_text | generate_text | 273 | 309 | 273 | 276 | cb0b160da5efd7312bd1bf26beff7b8d07d6996f | bigcode/the-stack | train |
51290cae28188c12c7afa7c4 | train | function | def loss(labels, logits):
return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)
| def loss(labels, logits):
| return tf.keras.losses.sparse_categorical_crossentropy(labels, logits, from_logits=True)
| = int_to_text(sampled_indices)
predicted_chars # and this is what the model predicted for training sequence 1
"""So now we need to create a loss function that can compare that output to the expected output and give us some numeric value representing how close the two were."""
def loss(labels, logits):
| 64 | 64 | 26 | 6 | 58 | Reeju2019/Projects | Mechine_learning/rnn_play_generator.py | Python | loss | loss | 222 | 223 | 222 | 222 | d643d4bcd596cd798b338cda02b4ae8e960e14ee | bigcode/the-stack | train |
570946d4f63a80ac93f77e84 | train | function | def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim,
batch_input_shape=[batch_size, None]),
tf.keras.layers.LSTM(rnn_units,
return_sequences=True,
... | def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
| model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim,
batch_input_shape=[batch_size, None]),
tf.keras.layers.LSTM(rnn_units,
return_sequences=True,
stateful=True,
recurrent_initia... | is time to build the model. We will use an embedding layer a LSTM and one dense layer that contains a node for each unique character in our training data. The dense layer will give us a probability distribution over all nodes.
"""
def build_model(vocab_size, embedding_dim, rnn_units, batch_size):
| 64 | 64 | 91 | 17 | 47 | Reeju2019/Projects | Mechine_learning/rnn_play_generator.py | Python | build_model | build_model | 170 | 180 | 170 | 170 | d550ded0993a89a2a1189060cb88ee4e7fe19b7c | bigcode/the-stack | train |
e409a902c994dbb85c68aeb7 | train | function | def int_to_text(ints):
try:
ints = ints.numpy()
except:
pass
return ''.join(idx2char[ints])
| def int_to_text(ints):
| try:
ints = ints.numpy()
except:
pass
return ''.join(idx2char[ints])
| text_as_int = text_to_int(text)
# lets look at how part of our text is encoded
print("Text:", text[:13])
print("Encoded:", text_to_int(text[:13]))
"""And here we will make a function that can convert our numeric values to text."""
def int_to_text(ints):
| 64 | 64 | 32 | 7 | 57 | Reeju2019/Projects | Mechine_learning/rnn_play_generator.py | Python | int_to_text | int_to_text | 110 | 115 | 110 | 110 | 9c9114f08dde2d88af2dc7a737fd2c33fed9adcf | bigcode/the-stack | train |
fc97637cc3edd9160f47b51d | train | class | class BaseRecommenderMetric(FullDatasetEvaluationMetric):
annotation_types = (HitRatioAnnotation, )
prediction_types = (HitRatioPrediction, )
@classmethod
def parameters(cls):
parameters = super().parameters()
parameters.update({
'top_k': NumberField(
value_t... | class BaseRecommenderMetric(FullDatasetEvaluationMetric):
| annotation_types = (HitRatioAnnotation, )
prediction_types = (HitRatioPrediction, )
@classmethod
def parameters(cls):
parameters = super().parameters()
parameters.update({
'top_k': NumberField(
value_type=int, min_value=1, optional=True, default=10,
... | a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable 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 lan... | 129 | 129 | 432 | 12 | 116 | apankratovantonp/open_model_zoo | tools/accuracy_checker/accuracy_checker/metrics/hit_ratio.py | Python | BaseRecommenderMetric | BaseRecommenderMetric | 26 | 77 | 26 | 26 | 758db5b3fdd7156b66c53f6126345b6b0a3e31d6 | bigcode/the-stack | train |
168b7225eb03a9f028e3db35 | train | function | def hit_ratio_discounter(item, rank):
return int(item in rank)
| def hit_ratio_discounter(item, rank):
| return int(item in rank)
| .gt_items.keys():
measure.append(self.discounter(self.gt_items[user], ranklist))
return np.mean(measure)
def reset(self):
self.pred_per_user = {i: [] for i in range(self.users_num)}
self.gt_items = {}
def hit_ratio_discounter(item, rank):
| 63 | 64 | 16 | 9 | 54 | apankratovantonp/open_model_zoo | tools/accuracy_checker/accuracy_checker/metrics/hit_ratio.py | Python | hit_ratio_discounter | hit_ratio_discounter | 80 | 81 | 80 | 80 | 949b31902ca3e3b02e8684dd7b0db78702499328 | bigcode/the-stack | train |
5cd28f7b213366ef28ffc48d | train | function | def ndcg_discounter(item, rank):
if item in rank:
return math.log(2) / math.log(rank.index(item) + 2)
return 0
| def ndcg_discounter(item, rank):
| if item in rank:
return math.log(2) / math.log(rank.index(item) + 2)
return 0
| list))
return np.mean(measure)
def reset(self):
self.pred_per_user = {i: [] for i in range(self.users_num)}
self.gt_items = {}
def hit_ratio_discounter(item, rank):
return int(item in rank)
def ndcg_discounter(item, rank):
| 64 | 64 | 38 | 9 | 55 | apankratovantonp/open_model_zoo | tools/accuracy_checker/accuracy_checker/metrics/hit_ratio.py | Python | ndcg_discounter | ndcg_discounter | 84 | 88 | 84 | 84 | 5765f3d5b5e841221e96b3ceb91851434fab9b32 | bigcode/the-stack | train |
e601e2b1fb5f9085e5c413b6 | train | class | class HitRatioMetric(BaseRecommenderMetric):
"""
Class for evaluating Hit Ratio metric
"""
__provider__ = 'hit_ratio'
def __init__(self, *args, **kwargs):
super().__init__(hit_ratio_discounter, *args, **kwargs)
| class HitRatioMetric(BaseRecommenderMetric):
| """
Class for evaluating Hit Ratio metric
"""
__provider__ = 'hit_ratio'
def __init__(self, *args, **kwargs):
super().__init__(hit_ratio_discounter, *args, **kwargs)
| def hit_ratio_discounter(item, rank):
return int(item in rank)
def ndcg_discounter(item, rank):
if item in rank:
return math.log(2) / math.log(rank.index(item) + 2)
return 0
class HitRatioMetric(BaseRecommenderMetric):
| 64 | 64 | 60 | 10 | 53 | apankratovantonp/open_model_zoo | tools/accuracy_checker/accuracy_checker/metrics/hit_ratio.py | Python | HitRatioMetric | HitRatioMetric | 91 | 99 | 91 | 91 | 151a8f48b42acb7eff2562612e78d221f6fd79e7 | bigcode/the-stack | train |
737e4b2ce7a6c71e8a82f80c | train | class | class NDSGMetric(BaseRecommenderMetric):
"""
Class for evaluating Normalized Discounted Cumulative Gain metric
"""
__provider__ = 'ndcg'
def __init__(self, *args, **kwargs):
super().__init__(ndcg_discounter, *args, **kwargs)
| class NDSGMetric(BaseRecommenderMetric):
| """
Class for evaluating Normalized Discounted Cumulative Gain metric
"""
__provider__ = 'ndcg'
def __init__(self, *args, **kwargs):
super().__init__(ndcg_discounter, *args, **kwargs)
| enderMetric):
"""
Class for evaluating Hit Ratio metric
"""
__provider__ = 'hit_ratio'
def __init__(self, *args, **kwargs):
super().__init__(hit_ratio_discounter, *args, **kwargs)
class NDSGMetric(BaseRecommenderMetric):
| 64 | 64 | 66 | 11 | 53 | apankratovantonp/open_model_zoo | tools/accuracy_checker/accuracy_checker/metrics/hit_ratio.py | Python | NDSGMetric | NDSGMetric | 102 | 110 | 102 | 102 | 1714eb5d42b828a9739502fb8355b3a2c6679ece | bigcode/the-stack | train |
41d5ebc45de7bd54bde04d4d | train | function | def solve(data, flag=False):
data = list(map(int, data.split()))
root_node = parse_node(data)
if not flag:
return metadata_value
if flag:
return root_node["value"]
| def solve(data, flag=False):
| data = list(map(int, data.split()))
root_node = parse_node(data)
if not flag:
return metadata_value
if flag:
return root_node["value"]
| + metadata_count
node_info = {"len": length, "child_count": child_count, "metadata_count": metadata_count, "metadata": metadata, "children": children, "value": value}
# print('node info', node_info)
return node_info
def solve(data, flag=False):
| 64 | 64 | 46 | 7 | 56 | Hwesta/advent-of-code | aoc2018/day8.py | Python | solve | solve | 101 | 108 | 101 | 101 | 58274ace05841a4f805d49336fc749c03638f8c0 | bigcode/the-stack | train |
fecb6b86c340f0c85936f7e0 | train | function | def parse_node(node):
"""Recursively parse a node's header, metadata & children"""
global metadata_value
# print('new node', node)
child_count = node[0]
metadata_count = node[1]
parsed = 2
# print(f"child count: {child_count}, metadata count: {metadata_count}")
# print("children", node[2... | def parse_node(node):
| """Recursively parse a node's header, metadata & children"""
global metadata_value
# print('new node', node)
child_count = node[0]
metadata_count = node[1]
parsed = 2
# print(f"child count: {child_count}, metadata count: {metadata_count}")
# print("children", node[2:])
children = []... | B has a value of 33 and node C has a value of 0, the value of node A is 33+33+0=66.
So, in this example, the value of the root node is 66.
What is the value of the root node?
"""
from __future__ import print_function
import os
metadata_value = 0
def parse_node(node):
| 80 | 80 | 268 | 5 | 74 | Hwesta/advent-of-code | aoc2018/day8.py | Python | parse_node | parse_node | 65 | 98 | 65 | 65 | 46ae00dc357113f66f40f75f2078c0a44e05c3a4 | bigcode/the-stack | train |
4cb1e00e82ab7d5880e4c61b | train | function | def trainModel(train_data_generator, val_data_generator, model, initial_epoch):
"""
Model training.
# Arguments
train_data_generator: Training data generated batch by batch.
val_data_generator: Validation data generated batch by batch.
model: Target image channels.
initial_epoch... | def trainModel(train_data_generator, val_data_generator, model, initial_epoch):
| """
Model training.
# Arguments
train_data_generator: Training data generated batch by batch.
val_data_generator: Validation data generated batch by batch.
model: Target image channels.
initial_epoch: Dimension of model output.
"""
# Initialize loss weights
model.al... | utils
import log_utils
from common_flags import FLAGS
def getModel(img_width, img_height, img_channels, output_dim, weights_path):
"""
Initialize model.
# Arguments
img_width: Target image widht.
img_height: Target image height.
img_channels: Target image channels.
output_di... | 180 | 180 | 603 | 16 | 163 | alejodosr/rpg_public_dronet | cnn.py | Python | trainModel | trainModel | 44 | 98 | 44 | 44 | dd3a412700d41551a3063c9eba8d54d91503fa49 | bigcode/the-stack | train |
eba9a07dd79468813a8d11f9 | train | function | def getModel(img_width, img_height, img_channels, output_dim, weights_path):
"""
Initialize model.
# Arguments
img_width: Target image widht.
img_height: Target image height.
img_channels: Target image channels.
output_dim: Dimension of model output.
weights_path: Path to... | def getModel(img_width, img_height, img_channels, output_dim, weights_path):
| """
Initialize model.
# Arguments
img_width: Target image widht.
img_height: Target image height.
img_channels: Target image channels.
output_dim: Dimension of model output.
weights_path: Path to pre-trained model.
# Returns
model: A Model instance.
"""
... | np
import os
import sys
import gflags
from keras.callbacks import ModelCheckpoint
from keras import optimizers
import logz
import cnn_models
import utils
import log_utils
from common_flags import FLAGS
def getModel(img_width, img_height, img_channels, output_dim, weights_path):
| 64 | 64 | 152 | 18 | 45 | alejodosr/rpg_public_dronet | cnn.py | Python | getModel | getModel | 18 | 41 | 18 | 18 | a1124ce3e16780d805e0b77df3277c4483d5e521 | bigcode/the-stack | train |
823d558b125e4e45a6b1cc08 | train | function | def main(argv):
# Utility main to load flags
try:
argv = FLAGS(argv) # parse flags
except gflags.FlagsError:
print ('Usage: %s ARGS\\n%s' % (sys.argv[0], FLAGS))
sys.exit(1)
_main()
| def main(argv):
# Utility main to load flags
| try:
argv = FLAGS(argv) # parse flags
except gflags.FlagsError:
print ('Usage: %s ARGS\\n%s' % (sys.argv[0], FLAGS))
sys.exit(1)
_main()
| json
json_model_path = os.path.join(FLAGS.experiment_rootdir, FLAGS.json_model_fname)
utils.modelToJson(model, json_model_path)
# Train model
trainModel(train_generator, val_generator, model, initial_epoch)
def main(argv):
# Utility main to load flags
| 64 | 64 | 65 | 12 | 52 | alejodosr/rpg_public_dronet | cnn.py | Python | main | main | 169 | 177 | 169 | 170 | 207fef7bbfbb6e5e72b1fe03dd00d8709d2920bb | bigcode/the-stack | train |
66ce3c54e216636ea5fed50c | train | function | def _main():
# Create the experiment rootdir if not already there
if not os.path.exists(FLAGS.experiment_rootdir):
os.makedirs(FLAGS.experiment_rootdir)
# Input image dimensions
img_width, img_height = FLAGS.img_width, FLAGS.img_height
# Cropped image dimensions
crop_img_width, crop_i... | def _main():
# Create the experiment rootdir if not already there
| if not os.path.exists(FLAGS.experiment_rootdir):
os.makedirs(FLAGS.experiment_rootdir)
# Input image dimensions
img_width, img_height = FLAGS.img_width, FLAGS.img_height
# Cropped image dimensions
crop_img_width, crop_img_height = FLAGS.crop_img_width, FLAGS.crop_img_height
# Image mo... | losses.
logz.configure_output_dir(FLAGS.experiment_rootdir)
saveModelAndLoss = log_utils.MyCallback(filepath=FLAGS.experiment_rootdir,
period=FLAGS.log_rate,
batch_size=FLAGS.batch_size)
# Train model
steps_per_epo... | 159 | 159 | 532 | 16 | 143 | alejodosr/rpg_public_dronet | cnn.py | Python | _main | _main | 101 | 166 | 101 | 103 | 1f4ade0ca7cdc4ef20494c4f800870be0520dd9b | bigcode/the-stack | train |
2e173dda9c9fd2818914f418 | train | function | def main():
args = parse_args()
logging.config.fileConfig(args.log_config.name)
model_config = read_model_config(args.model_config.name, args.model_name)
mq_config = MQConfig()
translator = Translator(model_config)
consumer = MQConsumer(
translator=translator,
mq_config=mq_confi... | def main():
| args = parse_args()
logging.config.fileConfig(args.log_config.name)
model_config = read_model_config(args.model_config.name, args.model_name)
mq_config = MQConfig()
translator = Translator(model_config)
consumer = MQConsumer(
translator=translator,
mq_config=mq_config
)
... | ', type=str,
help="The model to load. Refers to the model name in the config file.")
parser.add_argument('--log-config', type=FileType('r'), default='config/logging.prod.ini',
help="Path to log config file.")
return parser.parse_args()
def main():
| 64 | 64 | 73 | 3 | 61 | TartuNLP/translation-worker | main.py | Python | main | main | 21 | 33 | 21 | 21 | c1bcc6e406b3667452c500b3e3dc6b8fc9271175 | bigcode/the-stack | train |
99e2b7c46546f9bd3848a175 | train | function | def parse_args():
parser = ArgumentParser(
description="A neural machine translation worker that processes incoming translation requests via RabbitMQ."
)
parser.add_argument('--model-config', type=FileType('r'), default='config/config.yaml',
help="The model config YAML file t... | def parse_args():
| parser = ArgumentParser(
description="A neural machine translation worker that processes incoming translation requests via RabbitMQ."
)
parser.add_argument('--model-config', type=FileType('r'), default='config/config.yaml',
help="The model config YAML file to load.")
pars... | import logging.config
from argparse import ArgumentParser, FileType
from nmt_worker import MQConsumer, Translator, MQConfig, read_model_config
def parse_args():
| 34 | 64 | 129 | 4 | 29 | TartuNLP/translation-worker | main.py | Python | parse_args | parse_args | 7 | 18 | 7 | 7 | 97ca4aaf351c3d5d3d7dd6e1f1076269e558acf6 | bigcode/the-stack | train |
7610fc07be83ce9908a7bd5f | train | function | def add_elem(lst,ele):
lst.append(ele)
| def add_elem(lst,ele):
| lst.append(ele)
| def add_elem(lst,ele):
| 7 | 64 | 12 | 7 | 0 | royqh1979/programming_with_python | Chap04Functions/1-2-3.通过形参修改实参指向.py | Python | add_elem | add_elem | 1 | 2 | 1 | 1 | 5bb176715f1348771028cf6ad4bbf83a58a01a42 | bigcode/the-stack | train |
9900d1418235dfca86c946a7 | train | class | class Runner:
""" Base class for runner """
def get_log(self):
""" Forcing implementation of path and filename for current log. """
raise 'Missing get_log(self) implementation!'
def get_timestamp(self):
""" Get current date as unix timestamp. """
now = datetime.dat... | class Runner:
| """ Base class for runner """
def get_log(self):
""" Forcing implementation of path and filename for current log. """
raise 'Missing get_log(self) implementation!'
def get_timestamp(self):
""" Get current date as unix timestamp. """
now = datetime.datetime.now()
... | import os
import time
import datetime
class Runner:
| 12 | 64 | 151 | 3 | 8 | thomas-lehmann-private/queen | scripts/runner.py | Python | Runner | Runner | 5 | 28 | 5 | 5 | b10375f520e4637748ee17f2aee43179f9812115 | bigcode/the-stack | train |
90b6698e62ec4f199d730da1 | train | class | class ChangeFlagStateViewTest(BaseCommentFlagTest):
@patch.object(settings, 'COMMENT_FLAGS_ALLOWED', 1)
def setUp(self):
super().setUp()
self.data = {
'state': self.comment_for_change_state.flag.REJECTED
}
self.create_flag_instance(self.user_1, self.comment_for_change... | class ChangeFlagStateViewTest(BaseCommentFlagTest):
@patch.object(settings, 'COMMENT_FLAGS_ALLOWED', 1)
| def setUp(self):
super().setUp()
self.data = {
'state': self.comment_for_change_state.flag.REJECTED
}
self.create_flag_instance(self.user_1, self.comment_for_change_state, **self.flag_data)
self.create_flag_instance(self.user_2, self.comment_for_change_state, **se... | self.get_url('comment:flag', self.comment.id)
response = self.client_non_ajax.post(url, data=self.flag_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_incorrect_comment_id(self):
"""Test response when an incorrect comment id is passed"""
url = sel... | 208 | 208 | 694 | 25 | 183 | ZendaInnocent/Comment | comment/tests/test_views/test_flags.py | Python | ChangeFlagStateViewTest | ChangeFlagStateViewTest | 122 | 179 | 122 | 123 | 6797677010e250d59c7f4fb1d8d3f74bb23f1c3a | bigcode/the-stack | train |
1012b46b663c9a910557ba1b | train | class | class SetFlagViewTest(BaseCommentFlagTest):
def setUp(self):
super().setUp()
self.flag_data.update({
'info': ''
})
self.response_data = {
'status': 1
}
def test_set_flag(self):
_url = self.get_url('comment:flag', self.comment.id)
... | class SetFlagViewTest(BaseCommentFlagTest):
| def setUp(self):
super().setUp()
self.flag_data.update({
'info': ''
})
self.response_data = {
'status': 1
}
def test_set_flag(self):
_url = self.get_url('comment:flag', self.comment.id)
self.flag_data['reason'] = 1
resp... | from unittest.mock import patch
from rest_framework import status
from comment.conf import settings
from comment.messages import FlagInfo, FlagError
from comment.tests.base import BaseCommentFlagTest
class SetFlagViewTest(BaseCommentFlagTest):
| 48 | 256 | 957 | 10 | 37 | ZendaInnocent/Comment | comment/tests/test_views/test_flags.py | Python | SetFlagViewTest | SetFlagViewTest | 10 | 119 | 10 | 10 | 31bc9294e8cb9586bccacc97122db3abddaac97f | bigcode/the-stack | train |
6dfd0183977760885b3093f3 | train | function | def add_back_delimiter(sentence_list, delimiter):
for i in range(0, len(sentence_list)-1):
sentence_list[i] += " " + delimiter
return sentence_list
| def add_back_delimiter(sentence_list, delimiter):
| for i in range(0, len(sentence_list)-1):
sentence_list[i] += " " + delimiter
return sentence_list
| cleaned_line = re.sub('^(.*?)INFO - ', '', line)
cleaned_line = re.sub('^(.*?)ERROR - ', '', cleaned_line)
if len(cleaned_line) > 0:
output += cleaned_line + '\n'
return output
def add_back_delimiter(sentence_list, delimiter):
| 64 | 64 | 40 | 10 | 53 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | add_back_delimiter | add_back_delimiter | 75 | 78 | 75 | 75 | c36a6264b8f4e6f595aa3520b85d79985a26c8ae | bigcode/the-stack | train |
c8eb7471f7455da8d47a037e | train | function | def save_to_path(save_path, object_list, save_name):
for i in range(0, len(object_list)):
with open(save_path + "%d_" % i + save_name + ".txt", 'w', encoding='utf-8') as file:
file.write(object_list[i])
| def save_to_path(save_path, object_list, save_name):
| for i in range(0, len(object_list)):
with open(save_path + "%d_" % i + save_name + ".txt", 'w', encoding='utf-8') as file:
file.write(object_list[i])
| temp3 = add_back_delimiter(j.split(" ! "), "!")
for t in temp3:
if t.startswith("<"):
t = t[1:]
sentences.append(t)
return "\n".join(sentences).strip()
def save_to_path(save_path, object_list, save_name):
| 64 | 64 | 62 | 13 | 51 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | save_to_path | save_to_path | 95 | 98 | 95 | 95 | b2132898bd31f25586698dd139e7a25ede386887 | bigcode/the-stack | train |
9f26049457d46a0490f3364f | train | function | def clean_logger_output(text):
output = ""
for line in text.split('\n'):
cleaned_line = re.sub('^(.*?)INFO - ', '', line)
cleaned_line = re.sub('^(.*?)ERROR - ', '', cleaned_line)
if len(cleaned_line) > 0:
output += cleaned_line + '\n'
return output
| def clean_logger_output(text):
| output = ""
for line in text.split('\n'):
cleaned_line = re.sub('^(.*?)INFO - ', '', line)
cleaned_line = re.sub('^(.*?)ERROR - ', '', cleaned_line)
if len(cleaned_line) > 0:
output += cleaned_line + '\n'
return output
| clean_reference(input_txt):
output_txt = []
for line in input_txt:
line = re.sub(r'<EOS>', '', line)
line = re.sub(r'<PAD>', '', line)
line = line.strip()
output_txt.append(line)
return output_txt
def clean_logger_output(text):
| 64 | 64 | 74 | 6 | 57 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | clean_logger_output | clean_logger_output | 65 | 72 | 65 | 65 | 413212460b42cdda90f40f9837759b0ce27db352 | bigcode/the-stack | train |
0d598820a23a4111102e0af4 | train | function | def read_file(path, num_total):
text = open(path, encoding='utf-8').read()
if path.endswith(".log"):
text = clean_logger_output(text) # when using logger
titles = []
output = []
not_truth = False
for line in text.split('\n'):
if line.startswith('>'):
if not_truth:
... | def read_file(path, num_total):
| text = open(path, encoding='utf-8').read()
if path.endswith(".log"):
text = clean_logger_output(text) # when using logger
titles = []
output = []
not_truth = False
for line in text.split('\n'):
if line.startswith('>'):
if not_truth:
titles.pop() # te... | import re
def read_file(path, num_total):
| 11 | 64 | 201 | 8 | 2 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | read_file | read_file | 4 | 26 | 4 | 4 | a7230fe1c71898794a7e2ec602705dfb583660bb | bigcode/the-stack | train |
d36cc31d1baf79ee720df8b7 | train | function | def clean_modelsummary(input_txt):
output_txt = []
for line in input_txt:
line = line.split(" ")
line = " ".join(line[2:])
line = re.sub(r'<EOS>', '', line)
line = re.sub(r'<PAD>', '', line)
line = line.strip()
output_txt.append(line)
return output_txt
| def clean_modelsummary(input_txt):
| output_txt = []
for line in input_txt:
line = line.split(" ")
line = " ".join(line[2:])
line = re.sub(r'<EOS>', '', line)
line = re.sub(r'<PAD>', '', line)
line = line.strip()
output_txt.append(line)
return output_txt
| line in text.split('\n'):
if line.startswith('>'):
article.append(line[1:])
article = clean_reference(article)[:num_total]
for i in range(0, len(article)):
article[i] = split_sentence(article[i])
return article
def clean_modelsummary(input_txt):
| 64 | 64 | 77 | 7 | 56 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | clean_modelsummary | clean_modelsummary | 43 | 52 | 43 | 43 | 82b518cd2c621d6ddf3a30ca6b3785bc7a3f06a2 | bigcode/the-stack | train |
0a9f2813810747135b173977 | train | function | def split_beamsearch_to_multiple_files(save_path, num_summaries):
print("Started extracting titles...")
# save paths
path_to_article = save_path + '/article/'
path_to_combined = save_path + '/combined_objective/'
path_to_combined_mle = save_path + '/combined_objective_with_mle/'
path_to_discrim... | def split_beamsearch_to_multiple_files(save_path, num_summaries):
| print("Started extracting titles...")
# save paths
path_to_article = save_path + '/article/'
path_to_combined = save_path + '/combined_objective/'
path_to_combined_mle = save_path + '/combined_objective_with_mle/'
path_to_discriminator = save_path + '/discriminator_objective/'
path_to_discr... | re.sub('^(.*?)ERROR - ', '', cleaned_line)
if len(cleaned_line) > 0:
output += cleaned_line + '\n'
return output
def add_back_delimiter(sentence_list, delimiter):
for i in range(0, len(sentence_list)-1):
sentence_list[i] += " " + delimiter
return sentence_list
def split_sent... | 256 | 256 | 967 | 16 | 240 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | split_beamsearch_to_multiple_files | split_beamsearch_to_multiple_files | 101 | 151 | 101 | 101 | fa7e31d312962844be7c92c53f8e8511cc7e9015 | bigcode/the-stack | train |
5eec556f42b40e21f22be79d | train | function | def clean_reference(input_txt):
output_txt = []
for line in input_txt:
line = re.sub(r'<EOS>', '', line)
line = re.sub(r'<PAD>', '', line)
line = line.strip()
output_txt.append(line)
return output_txt
| def clean_reference(input_txt):
| output_txt = []
for line in input_txt:
line = re.sub(r'<EOS>', '', line)
line = re.sub(r'<PAD>', '', line)
line = line.strip()
output_txt.append(line)
return output_txt
| line = line.split(" ")
line = " ".join(line[2:])
line = re.sub(r'<EOS>', '', line)
line = re.sub(r'<PAD>', '', line)
line = line.strip()
output_txt.append(line)
return output_txt
def clean_reference(input_txt):
| 64 | 64 | 59 | 6 | 57 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | clean_reference | clean_reference | 55 | 62 | 55 | 55 | 1a1ccb0333da269fa7e0829b24903221d311e1cc | bigcode/the-stack | train |
67d404cd66aa6e5d5ed47b96 | train | function | def read_article(path, num_total):
text = open(path, encoding='utf-8').read()
if path.endswith(".log"):
text = clean_logger_output(text) # when using logger
article = []
for line in text.split('\n'):
if line.startswith('>'):
article.append(line[1:])
article = clean_refer... | def read_article(path, num_total):
| text = open(path, encoding='utf-8').read()
if path.endswith(".log"):
text = clean_logger_output(text) # when using logger
article = []
for line in text.split('\n'):
if line.startswith('>'):
article.append(line[1:])
article = clean_reference(article)[:num_total]
for i... | (output)[:num_total]
titles = clean_reference(titles)[:num_total]
for i in range(0, len(output)):
output[i] = split_sentence(output[i])
titles[i] = split_sentence(titles[i])
return titles, output
def read_article(path, num_total):
| 64 | 64 | 106 | 8 | 55 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | read_article | read_article | 29 | 40 | 29 | 29 | 1a1eacb13083c5d52a7c60a7fd60ed6a5523ba5a | bigcode/the-stack | train |
396cd8d7c685f3b55250be98 | train | function | def split_sentence(sentence):
sentences = []
temp = add_back_delimiter(sentence.split(" . "), ".")
for k in temp:
temp2 = add_back_delimiter(k.split(" ? "), "?")
for j in temp2:
temp3 = add_back_delimiter(j.split(" ! "), "!")
for t in temp3:
if t.start... | def split_sentence(sentence):
| sentences = []
temp = add_back_delimiter(sentence.split(" . "), ".")
for k in temp:
temp2 = add_back_delimiter(k.split(" ? "), "?")
for j in temp2:
temp3 = add_back_delimiter(j.split(" ! "), "!")
for t in temp3:
if t.startswith("<"):
... | _line) > 0:
output += cleaned_line + '\n'
return output
def add_back_delimiter(sentence_list, delimiter):
for i in range(0, len(sentence_list)-1):
sentence_list[i] += " " + delimiter
return sentence_list
def split_sentence(sentence):
| 64 | 64 | 102 | 5 | 58 | hbjornoy/TDT4900-Robo-Journalism | evaluation/seq2seq/create_result_files.py | Python | split_sentence | split_sentence | 81 | 92 | 81 | 81 | 2710c916666e16bf5f77ff2fc94940effeac1d96 | bigcode/the-stack | train |
d6b5961b355bf6c2e88b6aca | train | class | class DictGraphTest(unittest.TestCase):
def setUp(self):
self.graph = DictGraph()
self.graph.addEdge(0, 1, 1)
self.graph.addEdge(1, 3, 1)
self.graph.addEdge(0, 2, 2)
self.graph.addEdge(2, 3, 5)
self.graph.addEdge(0, 4, 1)
self.graph.addEdge(3, 4, 1)
se... | class DictGraphTest(unittest.TestCase):
| def setUp(self):
self.graph = DictGraph()
self.graph.addEdge(0, 1, 1)
self.graph.addEdge(1, 3, 1)
self.graph.addEdge(0, 2, 2)
self.graph.addEdge(2, 3, 5)
self.graph.addEdge(0, 4, 1)
self.graph.addEdge(3, 4, 1)
self.graph.setVertex(5, None)
... | from apgl.graph.DictGraph import DictGraph
from apgl.util.Util import Util
import unittest
import numpy
import logging
import numbers
import numpy.testing as nptst
class DictGraphTest(unittest.TestCase):
| 46 | 256 | 8,184 | 8 | 37 | mathemaphysics/APGL | apgl/graph/test/DictGraphTest.py | Python | DictGraphTest | DictGraphTest | 9 | 826 | 9 | 9 | d5da40e3fcd5b9453455b45df613203059edcc47 | bigcode/the-stack | train |
c301554d581631f02e0b6178 | train | class | class BAROR(BaseCard):
"""
+-------+---+-----+---+---+-------+-----+-------+------+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+=======+===+=====+===+===+=======+=====+=======+======+
| BAROR | | PID | | | G0/X1 | X2 | X3 | OFFT |
+-------+---+-----+---+---+-------+-----+... | class BAROR(BaseCard):
| """
+-------+---+-----+---+---+-------+-----+-------+------+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+=======+===+=====+===+===+=======+=====+=======+======+
| BAROR | | PID | | | G0/X1 | X2 | X3 | OFFT |
+-------+---+-----+---+---+-------+-----+-------+------+
| B... | \nL = %s' % (self.Rho(),
# self.Area(),
# self.Nsm(), L)
#raise TypeError(msg)
return mass
def uncross_reference(self) -> None:
"""Removes cross-reference links"""
... | 232 | 233 | 779 | 6 | 226 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | BAROR | BAROR | 163 | 233 | 163 | 163 | 9de1186bdf3411fb69ee959712a592bf12a4ec76 | bigcode/the-stack | train |
0b2aea0a3a94faf49aca59b7 | train | function | def get_bar_vector(model, elem, node1, node2, xyz1):
"""helper method for ``rotate_v_wa_wb``"""
cd1 = node1.Cd()
cd2 = node2.Cd()
if model is None:
cd1_ref = node1.cd_ref
cd2_ref = node2.cd_ref
# get the vector v, which defines the projection on to the elemental
# coordi... | def get_bar_vector(model, elem, node1, node2, xyz1):
| """helper method for ``rotate_v_wa_wb``"""
cd1 = node1.Cd()
cd2 = node2.Cd()
if model is None:
cd1_ref = node1.cd_ref
cd2_ref = node2.cd_ref
# get the vector v, which defines the projection on to the elemental
# coordinate frame
if elem.g0:
#msg = 'wh... | s\n' % g0
msg += 'X = %s\n' % x
raise RuntimeError(msg)
else:
msg = ('field5 on %s (G0/X1) is the wrong type...id=%s field5=%s '
'type=%s' % (card.field(0), eid, field5, type(field5)))
raise RuntimeError(msg)
return x, g0
def get_bar_vector(model, elem, no... | 110 | 110 | 369 | 17 | 92 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | get_bar_vector | get_bar_vector | 1,797 | 1,832 | 1,797 | 1,797 | 9f53211c5af4378ac4206dc52b99ebe90e5a6209 | bigcode/the-stack | train |
fb6119f297be1fc8bff140b9 | train | function | def init_x_g0_cbeam3(card, eid, x1_default, x2_default, x3_default):
"""reads the x/g0 field for the CBEAM3"""
field6 = integer_double_or_blank(card, 6, 'g0_x1', x1_default)
if isinstance(field6, integer_types):
g0 = field6
x = None
elif isinstance(field6, float):
g0 = None
... | def init_x_g0_cbeam3(card, eid, x1_default, x2_default, x3_default):
| """reads the x/g0 field for the CBEAM3"""
field6 = integer_double_or_blank(card, 6, 'g0_x1', x1_default)
if isinstance(field6, integer_types):
g0 = field6
x = None
elif isinstance(field6, float):
g0 = None
x = np.array([field6,
double_or_blank(card,... | -> str:
card = self.repr_fields()
if size == 8:
return self.comment + print_card_8(card)
return self.comment + print_card_16(card)
def _verify(self, xref):
unused_edges = self.get_edge_ids()
def init_x_g0_cbeam3(card, eid, x1_default, x2_default, x3_default):
| 82 | 82 | 274 | 24 | 58 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | init_x_g0_cbeam3 | init_x_g0_cbeam3 | 1,439 | 1,460 | 1,439 | 1,439 | e73a4a27615ecb1c2d63e8ea17b92ff81b1cbeda | bigcode/the-stack | train |
a91aa9dafad35ac0b0fee519 | train | class | class LineElement(Element): # CBAR, CBEAM, CBEAM3, CBEND
def __init__(self):
Element.__init__(self)
self.pid_ref = None # type: Optional[Any]
#self.nodes_ref = None
def C(self):
"""torsional constant"""
if self.pid_ref is None:
raise RuntimeError('Element e... | class LineElement(Element): # CBAR, CBEAM, CBEAM3, CBEND
| def __init__(self):
Element.__init__(self)
self.pid_ref = None # type: Optional[Any]
#self.nodes_ref = None
def C(self):
"""torsional constant"""
if self.pid_ref is None:
raise RuntimeError('Element eid=%i has not been '
'cross... | disable=R0904,R0902,E1101,E1103,C0111,C0302,C0103,W0101
from __future__ import annotations
from typing import Tuple, TYPE_CHECKING
import numpy as np
from numpy.linalg import norm
from pyNastran.utils.numpy_utils import integer_types
from pyNastran.bdf.field_writer_8 import set_blank_if_default
from pyNastran.bdf.ca... | 256 | 256 | 1,196 | 22 | 233 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | LineElement | LineElement | 32 | 160 | 32 | 32 | 63de48046062c4d677b29243eae92bfd2c192a7c | bigcode/the-stack | train |
9bf0aa2aae023b3ca5d51e10 | train | function | def check_offt(element):
"""
B,G,O
Note: The character 'O' in the table replaces the obsolete character 'E'
allowed = 'GGG,BGG,GGO,BGO,GOG,BOG,GOO,BOO,GGE,BGE,GEG,BEG,GEE,BEE,GGB,BGB,GBG,BBG,GBB,BBB,B'
"""
if isinstance(element.offt, integer_types):
raise SyntaxError('invalid offt expect... | def check_offt(element):
| """
B,G,O
Note: The character 'O' in the table replaces the obsolete character 'E'
allowed = 'GGG,BGG,GGO,BGO,GOG,BOG,GOO,BOO,GGE,BGE,GEG,BEG,GEE,BEE,GGB,BGB,GBG,BBG,GBB,BBB,B'
"""
if isinstance(element.offt, integer_types):
raise SyntaxError('invalid offt expected a string of length 3; ... | =%s'
' v=%s i=%s n%s=%s n%s=%s' % (
eid, Li, norm(yhat), norm(zhat), v, i, nid1, xyz1, nid2, xyz2))
return yhat, zhat
def check_offt(element):
| 66 | 66 | 222 | 6 | 59 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | check_offt | check_offt | 2,043 | 2,054 | 2,043 | 2,043 | 8637ccc1b8c8768ba22d6dde94ac29d103be99b6 | bigcode/the-stack | train |
2c57ad7fa3fc50c022082a38 | train | function | def get_bar_yz_transform(v, ihat, eid, xyz1, xyz2, nid1, nid2, i, Li):
"""
helper method for ``_get_bar_yz_arrays``
Parameters
----------
v : List[float, float, float]
the projection vector that defines the y-axis (jhat)
ihat : (3, ) float ndarray
the normalized x-axis (not incl... | def get_bar_yz_transform(v, ihat, eid, xyz1, xyz2, nid1, nid2, i, Li):
| """
helper method for ``_get_bar_yz_arrays``
Parameters
----------
v : List[float, float, float]
the projection vector that defines the y-axis (jhat)
ihat : (3, ) float ndarray
the normalized x-axis (not including the CBEAM offset)
eid : int
the element id
xyz1 /... | xyz2, node1.nid, node2.nid, i, Li)
#print(' n1=%s n2=%s' % (n1, n2))
#print(' ib=%s ia=%s' % (ib, ia))
#print(' wa=%s wb=%s' % (wa, wb))
#print(' ioffset=%s i=%s' % (i_offset, i))
#print(' ihat=%s' % (ihat))
#print(' yhat=%s' % (yhat))
#print(' zhat=%s' % (zhat))
#print("")
... | 207 | 207 | 693 | 29 | 177 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | get_bar_yz_transform | get_bar_yz_transform | 1,984 | 2,041 | 1,984 | 1,984 | 9dd162810dd4d2bc9459696b4b0f6e6c3f7129c6 | bigcode/the-stack | train |
8d620f1202300487c1aa6a3c | train | class | class CBAR(LineElement):
"""
+-------+-----+-----+-----+-----+-----+-----+-----+------+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+=======+=====+=====+=====+=====+=====+=====+=====+======+
| CBAR | EID | PID | GA | GB | X1 | X2 | X3 | OFFT |
+-------+-----+-----+-----+----... | class CBAR(LineElement):
| """
+-------+-----+-----+-----+-----+-----+-----+-----+------+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+=======+=====+=====+=====+=====+=====+=====+=====+======+
| CBAR | EID | PID | GA | GB | X1 | X2 | X3 | OFFT |
+-------+-----+-----+-----+-----+-----+-----+-----+-----... | x = [
x1_npoints,
double_or_blank(card, 4, 'x2'),
double_or_blank(card, 5, 'x3'),
double_or_blank(card, 6, 'x4'),
double_or_blank(card, 7, 'x5'),
double_or_blank(card, 8, 'x6'),
]
x = [xi ... | 256 | 256 | 6,470 | 6 | 250 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | CBAR | CBAR | 350 | 1,017 | 350 | 350 | 14de5eceb3c264f3951a0293bb27fd67b6dd9a2b | bigcode/the-stack | train |
1e94d02e546868e552785405 | train | function | def rotate_v_wa_wb(model: BDF, elem, xyz1, xyz2, node1, node2, ihat_offset, i_offset, eid,
Li_offset,
log: SimpleLogger) -> Tuple[NDArray3float, NDArray3float, NDArray3float, NDArray33float]:
"""
Rotates v, wa, wb
Parameters
----------
model : BDF()
BDF... | def rotate_v_wa_wb(model: BDF, elem, xyz1, xyz2, node1, node2, ihat_offset, i_offset, eid,
Li_offset,
log: SimpleLogger) -> Tuple[NDArray3float, NDArray3float, NDArray3float, NDArray33float]:
| """
Rotates v, wa, wb
Parameters
----------
model : BDF()
BDF : assume the model isn't xref'd
None : use the xref'd values
elem : CBAR() / CBEAM()
the CBAR/CBEAM
xyz1 / xyz2 : (3, ) float ndarray
the xyz locations for node 1 / 2
node1 / node2 : GRID()
... | = ', which is required by %s=%s' % (elem.type, elem.eid)
cd1_ref = model.Coord(cd1)
cd2_ref = model.Coord(cd2)
# get the vector v, which defines the projection on to the elemental
# coordinate frame
if elem.g0:
#msg = 'which is required by %s eid=%s\n%s' % (elem.typ... | 256 | 256 | 1,459 | 68 | 187 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | rotate_v_wa_wb | rotate_v_wa_wb | 1,834 | 1,982 | 1,834 | 1,836 | fc57b6d7fe23b2f0bf297ff0aedb4a01eb4fceea | bigcode/the-stack | train |
9988510b15f36af4ddb2060a | train | class | class CBEAM3(LineElement): # was CBAR
_properties = ['node_ids', 'nodes']
"""
Defines a three-node beam element
"""
@classmethod
def _init_from_empty(cls):
eid = 1
pid = 1
x = None
nids = [1, 2, 3]
g0 = 4
return CBEAM3(eid, pid, nids, x, g0,
... | class CBEAM3(LineElement): # was CBAR
| _properties = ['node_ids', 'nodes']
"""
Defines a three-node beam element
"""
@classmethod
def _init_from_empty(cls):
eid = 1
pid = 1
x = None
nids = [1, 2, 3]
g0 = 4
return CBEAM3(eid, pid, nids, x, g0,
wa=None, wb=None, wc=... | w2b = set_blank_if_default(self.wb[1], 0.0)
w3b = set_blank_if_default(self.wb[2], 0.0)
x1, x2, x3 = self.get_x_g0_defaults()
# offt doesn't exist in NX nastran
offt = set_blank_if_default(self.offt, 'GGG')
list_fields = ['CBAR', self.eid, self.Pid(), self.Ga(), self.Gb(), x1,... | 256 | 256 | 4,408 | 14 | 242 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | CBEAM3 | CBEAM3 | 1,020 | 1,437 | 1,020 | 1,020 | 33bbff232f1304bcc726e8636d44c6f42ca4e175 | bigcode/the-stack | train |
64e2b438fe14de58fcde9546 | train | class | class CBARAO(BaseCard):
"""
Per MSC 2016.1
+--------+------+-------+------+-----+--------+-----+----+----+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+========+======+=======+======+=====+========+=====+====+====+
| CBARAO | EID | SCALE | X1 | X2 | X3 | X4 | X5 | X6... | class CBARAO(BaseCard):
| """
Per MSC 2016.1
+--------+------+-------+------+-----+--------+-----+----+----+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
+========+======+=======+======+=====+========+=====+====+====+
| CBARAO | EID | SCALE | X1 | X2 | X3 | X4 | X5 | X6 |
+--------+------+... | .array([field5,
double_or_blank(card, 6, 'x2', 0.),
double_or_blank(card, 7, 'x3', 0.)],
dtype='float64')
else:
raise NotImplementedError('BAROR field5 = %r' % field5)
offt = integer_string_or_blank(card, 8, 'offt',... | 256 | 256 | 1,175 | 7 | 249 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | CBARAO | CBARAO | 235 | 348 | 235 | 235 | d8f1375e096b98e91a1260d9dc65d91012a51fb4 | bigcode/the-stack | train |
174ea24dd1e399c4e2f59d68 | train | class | class CBEND(LineElement):
type = 'CBEND'
_field_map = {
1: 'eid', 2:'pid', 3:'ga', 4:'gb', 8:'geom',
}
_properties = ['node_ids']
def _update_field_helper(self, n, value):
if self.g0 is not None:
if n == 5:
self.g0 = value
else:
... | class CBEND(LineElement):
| type = 'CBEND'
_field_map = {
1: 'eid', 2:'pid', 3:'ga', 4:'gb', 8:'geom',
}
_properties = ['node_ids']
def _update_field_helper(self, n, value):
if self.g0 is not None:
if n == 5:
self.g0 = value
else:
raise KeyError('Field %r... | """reads the x/g0 field for the CBEAM3"""
field6 = integer_double_or_blank(card, 6, 'g0_x1', x1_default)
if isinstance(field6, integer_types):
g0 = field6
x = None
elif isinstance(field6, float):
g0 = None
x = np.array([field6,
double_or_blank(card,... | 256 | 256 | 2,862 | 6 | 249 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | CBEND | CBEND | 1,463 | 1,772 | 1,463 | 1,463 | 7fbebce4440ae301ee50402920efc122672d674f | bigcode/the-stack | train |
d3d125dd09d8c16afceb7583 | train | function | def init_x_g0(card, eid, x1_default, x2_default, x3_default):
"""common method to read the x/g0 field for the CBAR, CBEAM, CBEAM3"""
field5 = integer_double_or_blank(card, 5, 'g0_x1', x1_default)
if isinstance(field5, integer_types):
g0 = field5
x = None
elif isinstance(field5, float):
... | def init_x_g0(card, eid, x1_default, x2_default, x3_default):
| """common method to read the x/g0 field for the CBAR, CBEAM, CBEAM3"""
field5 = integer_double_or_blank(card, 5, 'g0_x1', x1_default)
if isinstance(field5, integer_types):
g0 = field5
x = None
elif isinstance(field5, float):
g0 = None
x = np.array([field5,
... | return self.raw_fields()
def write_card(self, size: int=8, is_double: bool=False) -> str:
card = self.repr_fields()
if size == 8:
return self.comment + print_card_8(card)
return self.comment + print_card_16(card)
def init_x_g0(card, eid, x1_default, x2_default, x3_default):
| 84 | 84 | 281 | 21 | 63 | josiahlund/pyNastran | pyNastran/bdf/cards/elements/bars.py | Python | init_x_g0 | init_x_g0 | 1,774 | 1,795 | 1,774 | 1,774 | 7cbac12c299f3157b3c0b8f7fbf154e76609c677 | bigcode/the-stack | train |
e416ba74a68f3f2c5836c605 | train | function | def depthshow(depth, *args, ax=None, **kwargs):
if ax is None:
ax = plt.gca()
d = depth.copy()
d[d < 0] = np.NaN
ax.imshow(d, *args, **kwargs)
| def depthshow(depth, *args, ax=None, **kwargs):
| if ax is None:
ax = plt.gca()
d = depth.copy()
d[d < 0] = np.NaN
ax.imshow(d, *args, **kwargs)
| 0] >= 0, pts[:,0] < w), np.logical_and(pts[:,1] >= 0, pts[:,1] < h))]
ax.plot(pts[:,0], pts[:,1], *args, **kwargs)
def depthshow(depth, *args, ax=None, **kwargs):
| 64 | 64 | 56 | 14 | 50 | SimonTheVillain/connecting_the_dots | co/plt2d.py | Python | depthshow | depthshow | 52 | 57 | 52 | 52 | 0c26f9b85ea916e644ba05ad8b40de435b26e086 | bigcode/the-stack | train |
ac0cc4f1d89d356d3fbef514 | train | function | def image_cat(ims, vertical=False):
offx = [0]
offy = [0]
if vertical:
width = max([im.shape[1] for im in ims])
offx += [0 for im in ims[:-1]]
offy += [im.shape[0] for im in ims[:-1]]
height = sum([im.shape[0] for im in ims])
else:
height = max([im.shape[0] for im in ims])
offx += [im.sh... | def image_cat(ims, vertical=False):
| offx = [0]
offy = [0]
if vertical:
width = max([im.shape[1] for im in ims])
offx += [0 for im in ims[:-1]]
offy += [im.shape[0] for im in ims[:-1]]
height = sum([im.shape[0] for im in ims])
else:
height = max([im.shape[0] for im in ims])
offx += [im.shape[1] for im in ims[:-1]]
offy ... | mat.fill(bgval)
idx = 0
for r in range(m):
for c in range(m):
if idx < n:
mat[r*h:(r+1)*h, c*w:(c+1)*w] = ims[idx]
idx += 1
return mat
def image_cat(ims, vertical=False):
| 75 | 75 | 252 | 9 | 65 | SimonTheVillain/connecting_the_dots | co/plt2d.py | Python | image_cat | image_cat | 21 | 41 | 21 | 21 | 46356df11bb889d3e1a2702d4cafaebf8ca6594c | bigcode/the-stack | train |
20d04cdb6260bba7f0164d4d | train | function | def image_matrix(ims, bgval=0):
n = ims.shape[0]
m = int( np.ceil(np.sqrt(n)) )
h = ims.shape[1]
w = ims.shape[2]
mat = np.empty((m*h, m*w), dtype=ims.dtype)
mat.fill(bgval)
idx = 0
for r in range(m):
for c in range(m):
if idx < n:
mat[r*h:(r+1)*h, c*w:(c+1)*w] = ims[idx]
idx +... | def image_matrix(ims, bgval=0):
| n = ims.shape[0]
m = int( np.ceil(np.sqrt(n)) )
h = ims.shape[1]
w = ims.shape[2]
mat = np.empty((m*h, m*w), dtype=ims.dtype)
mat.fill(bgval)
idx = 0
for r in range(m):
for c in range(m):
if idx < n:
mat[r*h:(r+1)*h, c*w:(c+1)*w] = ims[idx]
idx += 1
return mat
| import numpy as np
import matplotlib.pyplot as plt
from . import geometry
def image_matrix(ims, bgval=0):
| 27 | 64 | 130 | 11 | 15 | SimonTheVillain/connecting_the_dots | co/plt2d.py | Python | image_matrix | image_matrix | 6 | 19 | 6 | 6 | e7ec52d9526deacc37f1dd87256e82b4db0fee01 | bigcode/the-stack | train |
f18cf4f1a82b60177ef3fe68 | train | function | def line(li, h, w, ax=None, *args, **kwargs):
if ax is None:
ax = plt.gca()
xs = (-li[2] - li[1] * np.array((0, h-1))) / li[0]
ys = (-li[2] - li[0] * np.array((0, w-1))) / li[1]
pts = np.array([(0,ys[0]), (w-1, ys[1]), (xs[0], 0), (xs[1], h-1)])
pts = pts[np.logical_and(np.logical_and(pts[:,0] >= 0, pts[:... | def line(li, h, w, ax=None, *args, **kwargs):
| if ax is None:
ax = plt.gca()
xs = (-li[2] - li[1] * np.array((0, h-1))) / li[0]
ys = (-li[2] - li[0] * np.array((0, w-1))) / li[1]
pts = np.array([(0,ys[0]), (w-1, ys[1]), (xs[0], 0), (xs[1], h-1)])
pts = pts[np.logical_and(np.logical_and(pts[:,0] >= 0, pts[:,0] < w), np.logical_and(pts[:,1] >= 0, pts[:,... | zip(ims, offx, offy):
im[oy:oy + im0.shape[0], ox:ox + im0.shape[1]] = im0
return im, offx, offy
def line(li, h, w, ax=None, *args, **kwargs):
| 64 | 64 | 187 | 17 | 46 | SimonTheVillain/connecting_the_dots | co/plt2d.py | Python | line | line | 43 | 50 | 43 | 43 | 15cc9b21b0e3899f20b4b222ee80dc87d600b4b0 | bigcode/the-stack | train |
d1cf06343b4693caf7119491 | train | class | class Normaliser:
"""
Normalises strings and keeps track of those that (1) do not comply to
Unicode's normal form; (2) have whitespace issues.
"""
def __init__(self, nfc_chars=[]):
"""
Constructor. The optional arg specifies the set of chars that should
not be decomposed.
"""
self.log = logging.getLogge... | class Normaliser:
| """
Normalises strings and keeps track of those that (1) do not comply to
Unicode's normal form; (2) have whitespace issues.
"""
def __init__(self, nfc_chars=[]):
"""
Constructor. The optional arg specifies the set of chars that should
not be decomposed.
"""
self.log = logging.getLogger(__name__)
sel... | import functools
import logging
import unicodedata
class Normaliser:
| 15 | 134 | 447 | 4 | 10 | pavelsof/ipalint | ipalint/strnorm.py | Python | Normaliser | Normaliser | 7 | 73 | 7 | 7 | fa850f684e9db664d3725c2e13988585428a67ee | bigcode/the-stack | train |
c998dcb73caade41d1e37dda | train | class | class VulnerabilityAssessmentScanTriggerType(str, Enum):
on_demand = "OnDemand"
recurring = "Recurring"
| class VulnerabilityAssessmentScanTriggerType(str, Enum):
| on_demand = "OnDemand"
recurring = "Recurring"
| "
class ElasticPoolState(str, Enum):
creating = "Creating"
ready = "Ready"
disabled = "Disabled"
class ElasticPoolLicenseType(str, Enum):
license_included = "LicenseIncluded"
base_price = "BasePrice"
class VulnerabilityAssessmentScanTriggerType(str, Enum):
| 64 | 64 | 26 | 11 | 53 | vchske/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/models/sql_management_client_enums.py | Python | VulnerabilityAssessmentScanTriggerType | VulnerabilityAssessmentScanTriggerType | 642 | 645 | 642 | 643 | 2d26219ff65783ae0b17e039af29709584c92d2f | bigcode/the-stack | train |
2526282160eac0d0b831cf96 | train | class | class ManagedInstanceProxyOverride(str, Enum):
proxy = "Proxy"
redirect = "Redirect"
default = "Default"
| class ManagedInstanceProxyOverride(str, Enum):
| proxy = "Proxy"
redirect = "Redirect"
default = "Default"
| Policy(str, Enum):
disabled = "Disabled"
enabled = "Enabled"
class FailoverGroupReplicationRole(str, Enum):
primary = "Primary"
secondary = "Secondary"
class IdentityType(str, Enum):
system_assigned = "SystemAssigned"
class ManagedInstanceProxyOverride(str, Enum):
| 64 | 64 | 27 | 9 | 55 | vchske/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/models/sql_management_client_enums.py | Python | ManagedInstanceProxyOverride | ManagedInstanceProxyOverride | 328 | 332 | 328 | 329 | 1d6e4ca37b0dc28f7356b4186b3b2125fcfbd88a | bigcode/the-stack | train |
71bf9489c6265c2cc19b7afd | train | class | class CatalogCollationType(str, Enum):
database_default = "DATABASE_DEFAULT"
sql_latin1_general_cp1_ci_as = "SQL_Latin1_General_CP1_CI_AS"
| class CatalogCollationType(str, Enum):
| database_default = "DATABASE_DEFAULT"
sql_latin1_general_cp1_ci_as = "SQL_Latin1_General_CP1_CI_AS"
| = "Include"
exclude = "Exclude"
class ManagedDatabaseStatus(str, Enum):
online = "Online"
offline = "Offline"
shutdown = "Shutdown"
creating = "Creating"
inaccessible = "Inaccessible"
updating = "Updating"
class CatalogCollationType(str, Enum):
| 64 | 64 | 41 | 9 | 55 | vchske/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/models/sql_management_client_enums.py | Python | CatalogCollationType | CatalogCollationType | 499 | 502 | 499 | 500 | 7862b7a5b60e8353cf7cff9084c12d0eeb868511 | bigcode/the-stack | train |
9b936fe28ce8320ea01658c3 | train | class | class DataMaskingRuleState(str, Enum):
disabled = "Disabled"
enabled = "Enabled"
| class DataMaskingRuleState(str, Enum):
| disabled = "Disabled"
enabled = "Enabled"
| = "Enabled"
disabled = "Disabled"
class SecurityAlertPolicyUseServerDefault(str, Enum):
enabled = "Enabled"
disabled = "Disabled"
class DataMaskingState(str, Enum):
disabled = "Disabled"
enabled = "Enabled"
class DataMaskingRuleState(str, Enum):
| 64 | 64 | 22 | 10 | 54 | vchske/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/models/sql_management_client_enums.py | Python | DataMaskingRuleState | DataMaskingRuleState | 53 | 56 | 53 | 54 | 3035a72d9006e519e07c9ace1a23f1a816a7d696 | bigcode/the-stack | train |
3b6b0b47b46a256aa0b84788 | train | class | class CreateMode(str, Enum):
default = "Default"
copy = "Copy"
secondary = "Secondary"
point_in_time_restore = "PointInTimeRestore"
restore = "Restore"
recovery = "Recovery"
restore_external_backup = "RestoreExternalBackup"
restore_external_backup_secondary = "RestoreExternalBackupSecon... | class CreateMode(str, Enum):
| default = "Default"
copy = "Copy"
secondary = "Secondary"
point_in_time_restore = "PointInTimeRestore"
restore = "Restore"
recovery = "Recovery"
restore_external_backup = "RestoreExternalBackup"
restore_external_backup_secondary = "RestoreExternalBackupSecondary"
restore_long_term_re... | Percent"
class CapabilityStatus(str, Enum):
visible = "Visible"
available = "Available"
default = "Default"
disabled = "Disabled"
class PerformanceLevelUnit(str, Enum):
dtu = "DTU"
vcores = "VCores"
class CreateMode(str, Enum):
| 64 | 64 | 94 | 7 | 57 | vchske/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/models/sql_management_client_enums.py | Python | CreateMode | CreateMode | 574 | 585 | 574 | 575 | 85c73abef7e019c80f3f8d11232b7c5a8075167c | bigcode/the-stack | train |
57caef20ead0829dfd8b87c9 | train | class | class DatabaseEdition(str, Enum):
web = "Web"
business = "Business"
basic = "Basic"
standard = "Standard"
premium = "Premium"
premium_rs = "PremiumRS"
free = "Free"
stretch = "Stretch"
data_warehouse = "DataWarehouse"
system = "System"
system2 = "System2"
| class DatabaseEdition(str, Enum):
| web = "Web"
business = "Business"
basic = "Basic"
standard = "Standard"
premium = "Premium"
premium_rs = "PremiumRS"
free = "Free"
stretch = "Stretch"
data_warehouse = "DataWarehouse"
system = "System"
system2 = "System2"
| Default"
ccn = "CCN"
email = "Email"
number = "Number"
ssn = "SSN"
text = "Text"
class GeoBackupPolicyState(str, Enum):
disabled = "Disabled"
enabled = "Enabled"
class DatabaseEdition(str, Enum):
| 64 | 64 | 80 | 7 | 57 | vchske/azure-sdk-for-python | sdk/sql/azure-mgmt-sql/azure/mgmt/sql/models/sql_management_client_enums.py | Python | DatabaseEdition | DatabaseEdition | 75 | 87 | 75 | 76 | cdec9262fc6b452ea304270e6bb1afba311e3a5d | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.