hexsha
stringlengths 40
40
| size
int64 1
1.03M
| ext
stringclasses 10
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 3
239
| max_stars_repo_name
stringlengths 5
130
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
239
| max_issues_repo_name
stringlengths 5
130
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
67k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
239
| max_forks_repo_name
stringlengths 5
130
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 1
1.03M
| avg_line_length
float64 1
958k
| max_line_length
int64 1
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a0a537efd4a98836a350807a0cadde86b67fc7e
| 1,024
|
py
|
Python
|
amas/env.py
|
RidiculousLoop/amas
|
8141f031842a69df9181d2fd242cccd07764b947
|
[
"MIT"
] | null | null | null |
amas/env.py
|
RidiculousLoop/amas
|
8141f031842a69df9181d2fd242cccd07764b947
|
[
"MIT"
] | null | null | null |
amas/env.py
|
RidiculousLoop/amas
|
8141f031842a69df9181d2fd242cccd07764b947
|
[
"MIT"
] | null | null | null |
import asyncio
from multiprocessing import Process
from typing import Coroutine, Iterable, List
from amas.agent import Agent
class Environment(object):
def __init__(self, agents: Iterable[Agent]) -> None:
self.__agents = agents
self.__loop = asyncio.get_event_loop()
self.__proc = None
return None
def __gather(self) -> None:
tasks: List[Coroutine] = []
[tasks.extend(agent.run()) for agent in self.__agents]
g = asyncio.gather(*tuple(tasks))
self.__loop.run_until_complete(g)
return None
def run(self) -> None:
self.__gather()
def parallelize(self) -> None:
self.__proc = Process(target=self.__gather, args=())
self.__proc.start()
return None
def join(self, timeout: float = None) -> None:
if self.__proc is not None:
self.__proc.join(timeout)
return None
def kill(self):
if self.__proc is not None:
self.__proc.kill()
return None
| 26.25641
| 62
| 0.616211
|
4a0a546cf7fbc25be79bd6569d2a79d80c45c41f
| 17,295
|
py
|
Python
|
python/dgl/backend/pytorch/tensor.py
|
harshgrovr/Graphs_Thesis
|
9ffd0d23c8f8b4bd53db9fd5b9bf5776666814e0
|
[
"Apache-2.0"
] | 1
|
2020-09-25T07:44:55.000Z
|
2020-09-25T07:44:55.000Z
|
python/dgl/backend/pytorch/tensor.py
|
xyanAI/dgl
|
36daf66f6216bad4d30651311bcb87aa45dd33d5
|
[
"Apache-2.0"
] | 1
|
2019-12-25T05:02:28.000Z
|
2019-12-25T05:02:28.000Z
|
python/dgl/backend/pytorch/tensor.py
|
xyanAI/dgl
|
36daf66f6216bad4d30651311bcb87aa45dd33d5
|
[
"Apache-2.0"
] | 1
|
2020-05-30T05:15:07.000Z
|
2020-05-30T05:15:07.000Z
|
from __future__ import absolute_import
from distutils.version import LooseVersion
import scipy # Weird bug in new pytorch when import scipy after import torch
import torch as th
import builtins
import numbers
from torch.utils import dlpack
from ... import ndarray as nd
from ..._deprecate import kernel as K
from ...function.base import TargetCode
from ...base import dgl_warning
if LooseVersion(th.__version__) < LooseVersion("1.5.0"):
dgl_warning("Detected an old version of PyTorch. Suggest using torch>=1.5.0 "
"for the best experience.")
def data_type_dict():
return {'float16' : th.float16,
'float32' : th.float32,
'float64' : th.float64,
'uint8' : th.uint8,
'int8' : th.int8,
'int16' : th.int16,
'int32' : th.int32,
'int64' : th.int64,
'bool' : th.bool}
def cpu():
return th.device('cpu')
def tensor(data, dtype=None):
if isinstance(data, numbers.Number):
data = [data]
if isinstance(data, th.Tensor):
return th.as_tensor(data, dtype=dtype, device=data.device)
else:
return th.as_tensor(data, dtype=dtype)
def as_scalar(data):
return data.item()
def get_preferred_sparse_format():
"""Get the preferred sparse matrix format supported by the backend.
Different backends have their preferred backend. This info is useful when
constructing a sparse matrix.
"""
return "coo"
def sparse_matrix(data, index, shape, force_format=False):
fmt = index[0]
if fmt != 'coo':
raise TypeError('Pytorch backend only supports COO format. But got %s.' % fmt)
spmat = th.sparse_coo_tensor(index[1], data, shape)
return spmat, None
def sparse_matrix_indices(spmat):
return ('coo', spmat._indices())
def is_tensor(obj):
return isinstance(obj, th.Tensor)
def shape(input):
return input.shape
def dtype(input):
return input.dtype
def ndim(input):
return input.dim()
def context(input):
return input.device
def device_type(ctx):
return th.device(ctx).type
def device_id(ctx):
ctx = th.device(ctx)
if ctx.index is None:
return 0
else:
return ctx.index
def to_backend_ctx(dglctx):
dev_type = dglctx.device_type
if dev_type == 1:
return th.device('cpu')
elif dev_type == 2:
return th.device('cuda', dglctx.device_id)
else:
raise ValueError('Unsupported DGL device context:', dglctx)
def astype(input, ty):
return input.type(ty)
def asnumpy(input):
if isinstance(input, th.sparse.FloatTensor):
return input.to_dense().cpu().detach().numpy()
else:
return input.cpu().detach().numpy()
def copy_to(input, ctx, **kwargs):
ctx = th.device(ctx)
if ctx.type == 'cpu':
return input.cpu()
elif ctx.type == 'cuda':
if ctx.index is not None:
th.cuda.set_device(ctx.index)
return input.cuda(**kwargs)
else:
raise RuntimeError('Invalid context', ctx)
def sum(input, dim, keepdims=False):
return th.sum(input, dim=dim, keepdim=keepdims)
def reduce_sum(input):
return input.sum()
def mean(input, dim):
return th.mean(input, dim=dim)
def reduce_mean(input):
return input.mean()
def max(input, dim):
# NOTE: the second argmax array is not returned
return th.max(input, dim=dim)[0]
def reduce_max(input):
return input.max()
def min(input, dim):
# NOTE: the second argmin array is not returned
return th.min(input, dim=dim)[0]
def reduce_min(input):
return input.min()
def argsort(input, dim, descending):
return th.argsort(input, dim=dim, descending=descending)
def topk(input, k, dim, descending=True):
return th.topk(input, k, dim, largest=descending)[0]
def argtopk(input, k, dim, descending=True):
return th.topk(input, k, dim, largest=descending)[1]
def exp(input):
return th.exp(input)
def sqrt(input):
return th.sqrt(input)
def softmax(input, dim=-1):
return th.softmax(input, dim=dim)
def cat(seq, dim):
return th.cat(seq, dim=dim)
def stack(seq, dim):
return th.stack(seq, dim=dim)
def split(input, sizes_or_sections, dim):
return th.split(input, sizes_or_sections, dim)
def repeat(input, repeats, dim):
return th.repeat_interleave(input, repeats, dim) # PyTorch 1.1
def gather_row(data, row_index):
return th.index_select(data, 0, row_index.long())
def slice_axis(data, axis, begin, end):
return th.narrow(data, axis, begin, end - begin)
def take(data, indices, dim):
new_shape = data.shape[:dim] + indices.shape + data.shape[dim+1:]
return th.index_select(data, dim, indices.view(-1)).view(new_shape)
def narrow_row(x, start, stop):
return x[start:stop]
def index_add_inplace(data, row_idx, value):
data.index_add_(0, row_idx, value)
def scatter_row(data, row_index, value):
return data.index_copy(0, row_index.long(), value)
def scatter_row_inplace(data, row_index, value):
data[row_index.long()] = value
def squeeze(input, dim):
return th.squeeze(input, dim)
def unsqueeze(input, dim):
return th.unsqueeze(input, dim)
def reshape(input, shape):
return th.reshape(input ,shape)
def swapaxes(input, axis1, axis2):
return th.transpose(input, axis1, axis2)
def zeros(shape, dtype, ctx):
return th.zeros(shape, dtype=dtype, device=ctx)
def zeros_like(input):
return th.zeros_like(input)
def ones(shape, dtype, ctx):
return th.ones(shape, dtype=dtype, device=ctx)
def uniform(shape, dtype, ctx, low, high):
return th.empty(shape, dtype=dtype, device=ctx).uniform_(low, high)
def randint(shape, dtype, ctx, low, high):
return th.randint(low, high, shape, dtype=dtype, device=ctx)
def pad_packed_tensor(input, lengths, value, l_min=None):
old_shape = input.shape
if isinstance(lengths, th.Tensor):
max_len = as_scalar(lengths.max())
else:
max_len = builtins.max(lengths)
if l_min is not None:
max_len = builtins.max(max_len, l_min)
batch_size = len(lengths)
device = input.device
x = input.new(batch_size * max_len, *old_shape[1:])
x.fill_(value)
index = []
for i, l in enumerate(lengths):
index.extend(range(i * max_len, i * max_len + l))
index = th.tensor(index).to(device)
return scatter_row(x, index, input).view(batch_size, max_len, *old_shape[1:])
def pack_padded_tensor(input, lengths):
batch_size, max_len = input.shape[:2]
device = input.device
index = []
for i, l in enumerate(lengths):
index.extend(range(i * max_len, i * max_len + l))
index = th.tensor(index).to(device)
return gather_row(input.view(batch_size * max_len, -1), index)
def boolean_mask(input, mask):
if 'bool' not in str(mask.dtype):
mask = th.tensor(mask, dtype=th.bool)
return input[mask]
def equal(x, y):
return x == y
def logical_not(input):
return ~input
def logical_and(input1, input2):
return input1 & input2
def clone(input):
return input.clone()
def clamp(data, min_val, max_val):
return th.clamp(data, min_val, max_val)
def replace_inf_with_zero(x):
return th.masked_fill(x, th.isinf(x), 0)
def unique(input):
if input.dtype == th.bool:
input = input.type(th.int8)
return th.unique(input)
def full_1d(length, fill_value, dtype, ctx):
return th.full((length,), fill_value, dtype=dtype, device=ctx)
def nonzero_1d(input):
x = th.nonzero(input, as_tuple=False).squeeze()
return x if x.dim() == 1 else x.view(-1)
def sort_1d(input):
return th.sort(input)
def arange(start, stop, dtype=th.int64):
return th.arange(start, stop, dtype=dtype)
def rand_shuffle(arr):
idx = th.randperm(len(arr))
return arr[idx]
def zerocopy_to_dlpack(input):
return dlpack.to_dlpack(input.contiguous())
def zerocopy_from_dlpack(dlpack_tensor):
return dlpack.from_dlpack(dlpack_tensor)
def zerocopy_to_numpy(input):
# NOTE: not zerocopy
return asnumpy(input)
def zerocopy_from_numpy(np_array):
return th.as_tensor(np_array)
def zerocopy_to_dgl_ndarray(data):
return nd.from_dlpack(dlpack.to_dlpack(data.contiguous()))
def zerocopy_to_dgl_ndarray_for_write(input):
return zerocopy_to_dgl_ndarray(input)
def zerocopy_from_dgl_ndarray(data):
if data.shape == (0,):
# NOTE: PyTorch v1.5 does not accept DLPack object representing empty CUDA tensor.
# Related issue: https://github.com/pytorch/pytorch/issues/41182
# The issue will be fixed in v1.6 and later.
return th.tensor([], dtype=getattr(th, data.dtype),
device=to_backend_ctx(data.ctx))
else:
return dlpack.from_dlpack(data.to_dlpack())
class BinaryReduce(th.autograd.Function):
@staticmethod
def forward(ctx, reducer, binary_op, graph, lhs, rhs, lhs_data, rhs_data, out_data,
out_size, lhs_map, rhs_map, out_map):
lhs_data_nd = zerocopy_to_dgl_ndarray(lhs_data)
rhs_data_nd = zerocopy_to_dgl_ndarray(rhs_data)
feat_shape = K.infer_binary_feature_shape(binary_op, lhs_data_nd, rhs_data_nd)
out_shape = feat_shape
if binary_op == 'dot':
out_shape = feat_shape[:-1]
out_data_nd = zerocopy_to_dgl_ndarray(out_data)
K.binary_op_reduce(
reducer if reducer != 'mean' else 'sum',
binary_op, graph, lhs, rhs, lhs_data_nd, rhs_data_nd,
out_data_nd, lhs_map[0], rhs_map[0], out_map[0])
# normalize if mean reducer
# NOTE(zihao): this is a temporary hack and we should have better solution in the future.
if reducer == 'mean':
degs = lhs_data.new_empty((out_data.shape[0],))
degs_nd = zerocopy_to_dgl_ndarray(degs)
if lhs != TargetCode.DST: # src or edge
target = lhs
n = lhs_data.shape[0]
in_map = lhs_map[0]
else: # rhs != TargetCode.DST
target = rhs
n = rhs_data.shape[0]
in_map = rhs_map[0]
in_ones = lhs_data.new_ones((n,))
in_ones_nd = zerocopy_to_dgl_ndarray(in_ones)
K.copy_reduce(
'sum', graph, target, in_ones_nd, degs_nd, in_map, out_map[0])
# reshape
degs = degs.reshape((out_data.shape[0],) + (1,) * (out_data.dim() - 1)).clamp(min=1)
out_data = out_data / degs
else:
degs = None
# save_for_backward can only save variables
ctx.backward_cache = (reducer, binary_op, graph, lhs, rhs, lhs_map,
rhs_map, out_map, feat_shape, degs)
ctx.save_for_backward(lhs_data, rhs_data, out_data)
return out_data
@staticmethod
def backward(ctx, grad_out):
reducer, binary_op, graph, lhs, rhs, lhs_map, rhs_map, out_map, \
feat_shape, degs = ctx.backward_cache
lhs_data, rhs_data, out_data = ctx.saved_tensors
lhs_data_nd = zerocopy_to_dgl_ndarray(lhs_data)
rhs_data_nd = zerocopy_to_dgl_ndarray(rhs_data)
out_data_nd = zerocopy_to_dgl_ndarray(out_data)
grad_lhs = None
grad_rhs = None
if reducer == 'mean':
grad_out = grad_out / degs
grad_out_nd = zerocopy_to_dgl_ndarray(grad_out)
if ctx.needs_input_grad[5]:
grad_lhs = grad_out.new_empty((lhs_data_nd.shape[0],) + feat_shape)
K.backward_lhs_binary_op_reduce(
reducer if reducer != 'mean' else 'sum',
binary_op, graph, lhs, rhs, lhs_data_nd, rhs_data_nd,
out_data_nd, grad_out_nd, zerocopy_to_dgl_ndarray(grad_lhs),
lhs_map[1], rhs_map[1], out_map[1])
grad_lhs = _reduce_grad(grad_lhs, lhs_data_nd.shape)
if ctx.needs_input_grad[6]:
grad_rhs = grad_out.new_empty((rhs_data_nd.shape[0],) + feat_shape)
K.backward_rhs_binary_op_reduce(
reducer if reducer != 'mean' else 'sum',
binary_op, graph, lhs, rhs, lhs_data_nd, rhs_data_nd,
out_data_nd, grad_out_nd, zerocopy_to_dgl_ndarray(grad_rhs),
lhs_map[1], rhs_map[1], out_map[1])
grad_rhs = _reduce_grad(grad_rhs, rhs_data_nd.shape)
return None, None, None, None, None, grad_lhs, grad_rhs, None, None, None, \
None, None
def binary_reduce(reducer, binary_op, graph, lhs, rhs, lhs_data, rhs_data,
out_size, lhs_map=(None, None), rhs_map=(None, None), out_map=(None, None)):
lhs_data_nd = zerocopy_to_dgl_ndarray(lhs_data)
rhs_data_nd = zerocopy_to_dgl_ndarray(rhs_data)
feat_shape = K.infer_binary_feature_shape(binary_op, lhs_data_nd, rhs_data_nd)
out_shape = feat_shape
if binary_op == 'dot':
out_shape = feat_shape[:-1]
out_data = lhs_data.new_empty((out_size,) + out_shape)
return BinaryReduce.apply(
reducer, binary_op, graph, lhs, rhs, lhs_data, rhs_data, out_data,
out_size, lhs_map, rhs_map, out_map)
class CopyReduce(th.autograd.Function):
@staticmethod
def forward(ctx, reducer, graph, target, in_data, out_data, out_size, in_map,
out_map):
in_data_nd = zerocopy_to_dgl_ndarray(in_data)
out_data_nd = zerocopy_to_dgl_ndarray(out_data)
K.copy_reduce(
reducer if reducer != 'mean' else 'sum',
graph, target, in_data_nd, out_data_nd, in_map[0], out_map[0])
# normalize if mean reducer
# NOTE(zihao): this is a temporary hack and we should have better solution in the future.
if reducer == 'mean':
in_ones = in_data.new_ones((in_data.shape[0],))
degs = in_data.new_empty((out_data.shape[0],))
in_ones_nd = zerocopy_to_dgl_ndarray(in_ones)
degs_nd = zerocopy_to_dgl_ndarray(degs)
K.copy_reduce(
'sum', graph, target, in_ones_nd, degs_nd, in_map[0], out_map[0])
# reshape
degs = degs.reshape((out_data.shape[0],) + (1,) * (out_data.dim() - 1)).clamp(min=1)
out_data = out_data / degs
else:
degs = None
# save_for_backward can only save variables
ctx.backward_cache = (reducer, graph, target, in_map, out_map, degs)
ctx.save_for_backward(in_data, out_data)
return out_data
@staticmethod
def backward(ctx, grad_out):
reducer, graph, target, in_map, out_map, degs = ctx.backward_cache
in_data, out_data = ctx.saved_tensors
in_data_nd = zerocopy_to_dgl_ndarray(in_data)
out_data_nd = zerocopy_to_dgl_ndarray(out_data)
grad_in = None
if reducer == 'mean':
grad_out = grad_out / degs
grad_out_nd = zerocopy_to_dgl_ndarray(grad_out)
if ctx.needs_input_grad[3]:
grad_in = grad_out.new_empty(in_data_nd.shape)
K.backward_copy_reduce(
reducer if reducer != 'mean' else 'sum',
graph, target, in_data_nd, out_data_nd, grad_out_nd,
zerocopy_to_dgl_ndarray(grad_in), in_map[1], out_map[1])
return None, None, None, grad_in, None, None, None, None
def copy_reduce(reducer, graph, target, in_data, out_size, in_map=(None, None),
out_map=(None, None)):
out_data = in_data.new_empty((out_size,) + in_data.shape[1:])
return CopyReduce.apply(reducer, graph, target, in_data, out_data, out_size, in_map, out_map)
def _reduce_grad(grad, shape):
"""Reduce gradient on the broadcast dimension
If there is broadcast in forward pass, gradients need to be reduced on
broadcast dimension. This function checks the input tensor shape and
gradient shape and perform the reduction.
Parameters
----------
grad: Tensor
Gradient tensor
shape: tuple
Shape of input tensor
Returns
-------
Tensor
"""
grad_shape = grad.shape[1:]
in_shape = shape[1:]
if in_shape == grad_shape:
# no need to reduce
return grad
num_to_squeeze = len(grad_shape) - len(in_shape)
# pad inshape
in_shape = (1,) * num_to_squeeze + in_shape
reduce_idx = th.nonzero(th.tensor(grad_shape) - th.tensor(in_shape))
reduce_idx += 1 # skip batch dim
grad = grad.sum(dim=tuple(reduce_idx), keepdim=True)
return grad.view(shape)
def sync():
# Pytorch performs computation synchronously, so no need for synchronization.
pass
def attach_grad(x):
if x.grad is not None:
x.grad.zero_()
return x
else:
return x.requires_grad_()
def backward(x, head_gradient=None):
if head_gradient is not None and head_gradient.shape[0] == 1 and len(head_gradient.shape) == 1:
# Fix for torch 1.3.1
head_gradient = th.tensor(head_gradient.item()).to(head_gradient.device)
x.backward(head_gradient)
def grad(x):
return x.grad
def is_no_grad(x):
return x.grad is None or (x.grad == 0).all()
def is_recording():
return th.is_grad_enabled()
class record_grad(object):
def __init__(self):
pass
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, exc_traceback):
pass
no_grad = th.no_grad
| 32.027778
| 99
| 0.650014
|
4a0a54d63ea36c3a368bfa2105462c768eb8fad8
| 11,476
|
py
|
Python
|
mmdet/models/dense_heads/light_rpn_head.py
|
DayBreak-u/thundernet_mmdetection
|
9430592316134c390d9094560cfdb848d3e195ac
|
[
"Apache-2.0"
] | 22
|
2021-02-27T08:21:09.000Z
|
2022-03-01T03:05:24.000Z
|
mmdet/models/dense_heads/light_rpn_head.py
|
ouyanghuiyu/thundernet_mmdetection
|
9430592316134c390d9094560cfdb848d3e195ac
|
[
"Apache-2.0"
] | 3
|
2021-03-04T09:05:55.000Z
|
2021-10-07T02:19:02.000Z
|
mmdet/models/dense_heads/light_rpn_head.py
|
DayBreak-u/thundernet_mmdetection
|
9430592316134c390d9094560cfdb848d3e195ac
|
[
"Apache-2.0"
] | 2
|
2021-02-27T08:21:10.000Z
|
2021-03-05T17:00:27.000Z
|
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmcv.ops import batched_nms
from ..builder import HEADS
from .anchor_head import AnchorHead
from .rpn_test_mixin import RPNTestMixin
from mmdet.core import merge_aug_proposals
class h_sigmoid(nn.Module):
def __init__(self, inplace=True):
super(h_sigmoid, self).__init__()
self.relu = nn.ReLU6(inplace=inplace)
def forward(self, x):
return self.relu(x + 3) / 6
@HEADS.register_module()
class LightRPNHead(RPNTestMixin, AnchorHead):
"""RPN head.
Args:
in_channels (int): Number of channels in the input feature map.
""" # noqa: W605
def __init__(self, in_channels, **kwargs):
super(LightRPNHead, self).__init__(1, in_channels, **kwargs)
def _init_layers(self):
"""Initialize layers of the head."""
self.rpn_conv_exp = nn.Conv2d(
self.in_channels, self.feat_channels, 1, padding=0)
self.rpn_conv_dw = nn.Conv2d(
self.feat_channels, self.feat_channels, 5, padding=2, groups=self.feat_channels)
self.rpn_conv_linear = nn.Conv2d(
self.feat_channels, self.feat_channels, 1, padding=0)
self.rpn_cls = nn.Conv2d(self.feat_channels,
self.num_anchors * self.cls_out_channels, 1)
self.rpn_reg = nn.Conv2d(self.feat_channels, self.num_anchors * 4, 1)
self.sam = nn.Conv2d(
self.feat_channels, self.in_channels, 1, padding=0,bias=False)
self.bn = nn.BatchNorm2d(self.in_channels)
self.act = h_sigmoid()
def init_weights(self):
"""Initialize weights of the head."""
normal_init(self.rpn_conv_exp, std=0.01)
normal_init(self.rpn_conv_dw, std=0.01)
normal_init(self.rpn_conv_linear, std=0.01)
normal_init(self.rpn_cls, std=0.01)
normal_init(self.rpn_reg, std=0.01)
normal_init(self.sam, std=0.01)
def forward_single(self, x):
"""Forward feature map of a single scale level."""
rpn_out = self.rpn_conv_exp(x)
rpn_out = F.relu(rpn_out, inplace=True)
rpn_out = self.rpn_conv_dw(rpn_out)
rpn_out = F.relu(rpn_out, inplace=True)
rpn_out = self.rpn_conv_linear(rpn_out)
rpn_out = F.relu(rpn_out, inplace=True)
sam = self.act(self.bn(self.sam(rpn_out)))
x = x * sam
rpn_cls_score = self.rpn_cls(rpn_out)
rpn_bbox_pred = self.rpn_reg(rpn_out)
return rpn_cls_score, rpn_bbox_pred, x
def simple_test_rpn(self, x, img_metas):
"""Test without augmentation.
Args:
x (tuple[Tensor]): Features from the upstream network, each is
a 4D-tensor.
img_metas (list[dict]): Meta info of each image.
Returns:
list[Tensor]: Proposals of each image.
"""
rpn_outs = self(x)
x = rpn_outs[-1]
outs = rpn_outs[:2]
proposal_list = self.get_bboxes(*outs, img_metas)
return proposal_list, x
def aug_test_rpn(self, feats, img_metas):
samples_per_gpu = len(img_metas[0])
aug_proposals = [[] for _ in range(samples_per_gpu)]
x_out = []
for x, img_meta in zip(feats, img_metas):
proposal_list, x = self.simple_test_rpn(x, img_meta)
x_out.append(x)
for i, proposals in enumerate(proposal_list):
aug_proposals[i].append(proposals)
# reorganize the order of 'img_metas' to match the dimensions
# of 'aug_proposals'
aug_img_metas = []
for i in range(samples_per_gpu):
aug_img_meta = []
for j in range(len(img_metas)):
aug_img_meta.append(img_metas[j][i])
aug_img_metas.append(aug_img_meta)
# after merging, proposals will be rescaled to the original image size
merged_proposals = [
merge_aug_proposals(proposals, aug_img_meta, self.test_cfg)
for proposals, aug_img_meta in zip(aug_proposals, aug_img_metas)
]
return merged_proposals, tuple(x_out)
def forward_train(self,
x,
img_metas,
gt_bboxes,
gt_labels=None,
gt_bboxes_ignore=None,
proposal_cfg=None,
**kwargs):
"""
Args:
x (list[Tensor]): Features from FPN.
img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
gt_bboxes (Tensor): Ground truth bboxes of the image,
shape (num_gts, 4).
gt_labels (Tensor): Ground truth labels of each box,
shape (num_gts,).
gt_bboxes_ignore (Tensor): Ground truth bboxes to be
ignored, shape (num_ignored_gts, 4).
proposal_cfg (mmcv.Config): Test / postprocessing configuration,
if None, test_cfg would be used
Returns:
tuple:
losses: (dict[str, Tensor]): A dictionary of loss components.
proposal_list (list[Tensor]): Proposals of each image.
"""
rpn_outs = self(x)
x = rpn_outs[-1]
outs = rpn_outs[:2]
if gt_labels is None:
loss_inputs = outs + (gt_bboxes, img_metas)
else:
loss_inputs = outs + (gt_bboxes, gt_labels, img_metas)
losses = self.loss(*loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)
if proposal_cfg is None:
return losses
else:
proposal_list = self.get_bboxes(*outs, img_metas, cfg=proposal_cfg)
return losses, proposal_list, x
def loss(self,
cls_scores,
bbox_preds,
gt_bboxes,
img_metas,
gt_bboxes_ignore=None):
"""Compute losses of the head.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (N, num_anchors * num_classes, H, W)
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W)
gt_bboxes (list[Tensor]): Ground truth bboxes for each image with
shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.
img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
gt_bboxes_ignore (None | list[Tensor]): specify which bounding
boxes can be ignored when computing the loss.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
losses = super(LightRPNHead, self).loss(
cls_scores,
bbox_preds,
gt_bboxes,
None,
img_metas,
gt_bboxes_ignore=gt_bboxes_ignore)
return dict(
loss_rpn_cls=losses['loss_cls'], loss_rpn_bbox=losses['loss_bbox'])
def _get_bboxes_single(self,
cls_scores,
bbox_preds,
mlvl_anchors,
img_shape,
scale_factor,
cfg,
rescale=False):
"""Transform outputs for a single batch item into bbox predictions.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (num_anchors * num_classes, H, W).
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (num_anchors * 4, H, W).
mlvl_anchors (list[Tensor]): Box reference for each scale level
with shape (num_total_anchors, 4).
img_shape (tuple[int]): Shape of the input image,
(height, width, 3).
scale_factor (ndarray): Scale factor of the image arange as
(w_scale, h_scale, w_scale, h_scale).
cfg (mmcv.Config): Test / postprocessing configuration,
if None, test_cfg would be used.
rescale (bool): If True, return boxes in original image space.
Returns:
Tensor: Labeled boxes in shape (n, 5), where the first 4 columns
are bounding box positions (tl_x, tl_y, br_x, br_y) and the
5-th column is a score between 0 and 1.
"""
cfg = self.test_cfg if cfg is None else cfg
# bboxes from different level should be independent during NMS,
# level_ids are used as labels for batched NMS to separate them
level_ids = []
mlvl_scores = []
mlvl_bbox_preds = []
mlvl_valid_anchors = []
for idx in range(len(cls_scores)):
rpn_cls_score = cls_scores[idx]
rpn_bbox_pred = bbox_preds[idx]
assert rpn_cls_score.size()[-2:] == rpn_bbox_pred.size()[-2:]
rpn_cls_score = rpn_cls_score.permute(1, 2, 0)
if self.use_sigmoid_cls:
rpn_cls_score = rpn_cls_score.reshape(-1)
scores = rpn_cls_score.sigmoid()
else:
rpn_cls_score = rpn_cls_score.reshape(-1, 2)
# We set FG labels to [0, num_class-1] and BG label to
# num_class in RPN head since mmdet v2.5, which is unified to
# be consistent with other head since mmdet v2.0. In mmdet v2.0
# to v2.4 we keep BG label as 0 and FG label as 1 in rpn head.
scores = rpn_cls_score.softmax(dim=1)[:, 0]
rpn_bbox_pred = rpn_bbox_pred.permute(1, 2, 0).reshape(-1, 4)
anchors = mlvl_anchors[idx]
if cfg.nms_pre > 0 and scores.shape[0] > cfg.nms_pre:
# sort is faster than topk
# _, topk_inds = scores.topk(cfg.nms_pre)
ranked_scores, rank_inds = scores.sort(descending=True)
topk_inds = rank_inds[:cfg.nms_pre]
scores = ranked_scores[:cfg.nms_pre]
rpn_bbox_pred = rpn_bbox_pred[topk_inds, :]
anchors = anchors[topk_inds, :]
mlvl_scores.append(scores)
mlvl_bbox_preds.append(rpn_bbox_pred)
mlvl_valid_anchors.append(anchors)
level_ids.append(
scores.new_full((scores.size(0),), idx, dtype=torch.long))
scores = torch.cat(mlvl_scores)
anchors = torch.cat(mlvl_valid_anchors)
rpn_bbox_pred = torch.cat(mlvl_bbox_preds)
proposals = self.bbox_coder.decode(
anchors, rpn_bbox_pred, max_shape=img_shape)
ids = torch.cat(level_ids)
if cfg.min_bbox_size > 0:
w = proposals[:, 2] - proposals[:, 0]
h = proposals[:, 3] - proposals[:, 1]
valid_inds = torch.nonzero(
(w >= cfg.min_bbox_size)
& (h >= cfg.min_bbox_size),
as_tuple=False).squeeze()
if valid_inds.sum().item() != len(proposals):
proposals = proposals[valid_inds, :]
scores = scores[valid_inds]
ids = ids[valid_inds]
# TODO: remove the hard coded nms type
nms_cfg = dict(type='nms', iou_threshold=cfg.nms_thr)
dets, keep = batched_nms(proposals, scores, ids, nms_cfg)
return dets[:cfg.nms_post]
| 40.408451
| 92
| 0.578425
|
4a0a553a03fe66de94a959cb40e17a62217fd9a6
| 35,234
|
py
|
Python
|
mne/viz/_brain/_brain.py
|
hardik-prajapati/mne-python
|
7410696b8897c8782ae293e1c453a43b20197acd
|
[
"BSD-3-Clause"
] | 1
|
2019-12-11T05:07:08.000Z
|
2019-12-11T05:07:08.000Z
|
mne/viz/_brain/_brain.py
|
Gaoqunxia/mne-python
|
71a854d8eafe21676e545d8286b51422f34b26c3
|
[
"BSD-3-Clause"
] | null | null | null |
mne/viz/_brain/_brain.py
|
Gaoqunxia/mne-python
|
71a854d8eafe21676e545d8286b51422f34b26c3
|
[
"BSD-3-Clause"
] | null | null | null |
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Eric Larson <larson.eric.d@gmail.com>
# Oleh Kozynets <ok7mailbox@gmail.com>
# Guillaume Favelier <guillaume.favelier@gmail.com>
# jona-sassenhagen <jona.sassenhagen@gmail.com>
# Joan Massich <mailsik@gmail.com>
#
# License: Simplified BSD
import numpy as np
import os
from os.path import join as pjoin
from ...label import read_label
from .colormap import calculate_lut
from .view import lh_views_dict, rh_views_dict, View
from .surface import Surface
from .utils import mesh_edges, smoothing_matrix
from ..utils import _check_option, logger, verbose
class _Brain(object):
u"""Class for visualizing a brain.
It is used for creating meshes of the given subject's
cortex. The activation data can be shown on a mesh using add_data
method. Figures, meshes, activation data and other information
are stored as attributes of a class instance.
Parameters
----------
subject_id : str
Subject name in Freesurfer subjects dir.
hemi : str
Hemisphere id (ie 'lh', 'rh', 'both', or 'split'). In the case
of 'both', both hemispheres are shown in the same window.
In the case of 'split' hemispheres are displayed side-by-side
in different viewing panes.
surf : str
freesurfer surface mesh name (ie 'white', 'inflated', etc.).
title : str
Title for the window.
cortex : str or None
Specifies how the cortical surface is rendered.
The name of one of the preset cortex styles can be:
``'classic'`` (default), ``'high_contrast'``,
``'low_contrast'``, or ``'bone'`` or a valid color name.
Setting this to ``None`` is equivalent to ``(0.5, 0.5, 0.5)``.
alpha : float in [0, 1]
Alpha level to control opacity of the cortical surface.
size : float | tuple(float, float)
The size of the window, in pixels. can be one number to specify
a square window, or the (width, height) of a rectangular window.
background : tuple(int, int, int)
The color definition of the background: (red, green, blue).
foreground : matplotlib color
Color of the foreground (will be used for colorbars and text).
None (default) will use black or white depending on the value
of ``background``.
figure : list of Figure | None | int
If None (default), a new window will be created with the appropriate
views. For single view plots, the figure can be specified as int to
retrieve the corresponding Mayavi window.
subjects_dir : str | None
If not None, this directory will be used as the subjects directory
instead of the value set using the SUBJECTS_DIR environment
variable.
views : list | str
views to use.
offset : bool
If True, aligs origin with medial wall. Useful for viewing inflated
surface where hemispheres typically overlap (Default: True).
show_toolbar : bool
If True, toolbars will be shown for each view.
offscreen : bool
If True, rendering will be done offscreen (not shown). Useful
mostly for generating images or screenshots, but can be buggy.
Use at your own risk.
interaction : str
Not supported yet.
Can be "trackball" (default) or "terrain", i.e. a turntable-style
camera.
units : str
Can be 'm' or 'mm' (default).
Attributes
----------
geo : dict
A dictionary of pysurfer.Surface objects for each hemisphere.
overlays : dict
The overlays.
Notes
-----
This table shows the capabilities of each Brain backend ("✓" for full
support, and "-" for partial support):
.. table::
:widths: auto
+---------------------------+--------------+-----------------------+
| 3D function: | surfer.Brain | mne.viz._brain._Brain |
+===========================+==============+=======================+
| add_data | ✓ | - |
+---------------------------+--------------+-----------------------+
| add_foci | ✓ | - |
+---------------------------+--------------+-----------------------+
| add_label | ✓ | - |
+---------------------------+--------------+-----------------------+
| add_text | ✓ | - |
+---------------------------+--------------+-----------------------+
| close | ✓ | ✓ |
+---------------------------+--------------+-----------------------+
| data | ✓ | ✓ |
+---------------------------+--------------+-----------------------+
| foci | ✓ | |
+---------------------------+--------------+-----------------------+
| index_for_time | ✓ | ✓ |
+---------------------------+--------------+-----------------------+
| labels | ✓ | |
+---------------------------+--------------+-----------------------+
| labels_dict | ✓ | |
+---------------------------+--------------+-----------------------+
| overlays | ✓ | - |
+---------------------------+--------------+-----------------------+
| remove_data | ✓ | |
+---------------------------+--------------+-----------------------+
| remove_foci | ✓ | |
+---------------------------+--------------+-----------------------+
| remove_labels | ✓ | - |
+---------------------------+--------------+-----------------------+
| save_image | ✓ | ✓ |
+---------------------------+--------------+-----------------------+
| screenshot | ✓ | ✓ |
+---------------------------+--------------+-----------------------+
| show_view | ✓ | - |
+---------------------------+--------------+-----------------------+
"""
def __init__(self, subject_id, hemi, surf, title=None,
cortex=None, alpha=1.0, size=800, background="black",
foreground=None, figure=None, subjects_dir=None,
views=['lateral'], offset=True, show_toolbar=False,
offscreen=False, interaction=None, units='mm'):
from ..backends.renderer import _Renderer, _check_3d_figure
from matplotlib.colors import colorConverter
if interaction is not None:
raise ValueError('"interaction" parameter is not supported.')
if hemi in ('both', 'split'):
self._hemis = ('lh', 'rh')
elif hemi in ('lh', 'rh'):
self._hemis = (hemi, )
else:
raise KeyError('hemi has to be either "lh", "rh", "split", '
'or "both"')
if isinstance(background, str):
background = colorConverter.to_rgb(background)
if isinstance(foreground, str):
foreground = colorConverter.to_rgb(foreground)
if isinstance(views, str):
views = [views]
n_row = len(views)
col_dict = dict(lh=1, rh=1, both=1, split=2)
n_col = col_dict[hemi]
if isinstance(size, int):
fig_size = (size, size)
elif isinstance(size, tuple):
fig_size = size
else:
raise ValueError('"size" parameter must be int or tuple.')
self._foreground = foreground
self._hemi = hemi
self._units = units
self._title = title
self._subject_id = subject_id
self._subjects_dir = subjects_dir
self._views = views
self._n_times = None
self._scalarbar = False
# for now only one color bar can be added
# since it is the same for all figures
self._colorbar_added = False
# array of data used by TimeViewer
self._data = {}
self.geo, self._hemi_meshes, self._overlays = {}, {}, {}
# load geometry for one or both hemispheres as necessary
offset = None if (not offset or hemi != 'both') else 0.0
if figure is not None and not isinstance(figure, int):
_check_3d_figure(figure)
self._renderer = _Renderer(size=fig_size, bgcolor=background,
shape=(n_row, n_col), fig=figure)
for h in self._hemis:
# Initialize a Surface object as the geometry
geo = Surface(subject_id, h, surf, subjects_dir, offset,
units=self._units)
# Load in the geometry and curvature
geo.load_geometry()
geo.load_curvature()
self.geo[h] = geo
for ri, v in enumerate(views):
for hi, h in enumerate(['lh', 'rh']):
views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict
if not (hemi in ['lh', 'rh'] and h != hemi):
ci = hi if hemi == 'split' else 0
self._renderer.subplot(ri, ci)
self._renderer.mesh(x=self.geo[h].coords[:, 0],
y=self.geo[h].coords[:, 1],
z=self.geo[h].coords[:, 2],
triangles=self.geo[h].faces,
color=self.geo[h].grey_curv)
self._renderer.set_camera(azimuth=views_dict[v].azim,
elevation=views_dict[v].elev)
# Force rendering
self._renderer.show()
@verbose
def add_data(self, array, fmin=None, fmid=None, fmax=None,
thresh=None, center=None, transparent=False, colormap="auto",
alpha=1, vertices=None, smoothing_steps=None, time=None,
time_label="time index=%d", colorbar=True,
hemi=None, remove_existing=None, time_label_size=None,
initial_time=None, scale_factor=None, vector_alpha=None,
verbose=None):
u"""Display data from a numpy array on the surface.
This provides a similar interface to
:meth:`surfer.Brain.add_overlay`, but it displays
it with a single colormap. It offers more flexibility over the
colormap, and provides a way to display four-dimensional data
(i.e., a timecourse) or five-dimensional data (i.e., a
vector-valued timecourse).
.. note:: ``fmin`` sets the low end of the colormap, and is separate
from thresh (this is a different convention from
:meth:`surfer.Brain.add_overlay`).
Parameters
----------
array : numpy array, shape (n_vertices[, 3][, n_times])
Data array. For the data to be understood as vector-valued
(3 values per vertex corresponding to X/Y/Z surface RAS),
then ``array`` must be have all 3 dimensions.
If vectors with no time dimension are desired, consider using a
singleton (e.g., ``np.newaxis``) to create a "time" dimension
and pass ``time_label=None`` (vector values are not supported).
fmin : float
Minimum value in colormap (uses real fmin if None).
fmid : float
Intermediate value in colormap (fmid between fmin and
fmax if None).
fmax : float
Maximum value in colormap (uses real max if None).
thresh : None or float
Not supported yet.
if not None, values below thresh will not be visible
center : float or None
if not None, center of a divergent colormap, changes the meaning of
fmin, fmax and fmid.
transparent : bool
if True: use a linear transparency between fmin and fmid
and make values below fmin fully transparent (symmetrically for
divergent colormaps)
colormap : str, list of color, or array
name of matplotlib colormap to use, a list of matplotlib colors,
or a custom look up table (an n x 4 array coded with RBGA values
between 0 and 255), the default "auto" chooses a default divergent
colormap, if "center" is given (currently "icefire"), otherwise a
default sequential colormap (currently "rocket").
alpha : float in [0, 1]
alpha level to control opacity of the overlay.
vertices : numpy array
vertices for which the data is defined (needed if len(data) < nvtx)
smoothing_steps : int or None
number of smoothing steps (smoothing is used if len(data) < nvtx)
Default : 20
time : numpy array
time points in the data array (if data is 2D or 3D)
time_label : str | callable | None
format of the time label (a format string, a function that maps
floating point time values to strings, or None for no label)
colorbar : bool
whether to add a colorbar to the figure
hemi : str | None
If None, it is assumed to belong to the hemisphere being
shown. If two hemispheres are being shown, an error will
be thrown.
remove_existing : bool
Not supported yet.
Remove surface added by previous "add_data" call. Useful for
conserving memory when displaying different data in a loop.
time_label_size : int
Not supported yet.
Font size of the time label (default 14)
initial_time : float | None
Time initially shown in the plot. ``None`` to use the first time
sample (default).
scale_factor : float | None (default)
Not supported yet.
The scale factor to use when displaying glyphs for vector-valued
data.
vector_alpha : float | None
Not supported yet.
alpha level to control opacity of the arrows. Only used for
vector-valued data. If None (default), ``alpha`` is used.
%(verbose)s
Notes
-----
If the data is defined for a subset of vertices (specified
by the "vertices" parameter), a smoothing method is used to interpolate
the data onto the high resolution surface. If the data is defined for
subsampled version of the surface, smoothing_steps can be set to None,
in which case only as many smoothing steps are applied until the whole
surface is filled with non-zeros.
Due to a Mayavi (or VTK) alpha rendering bug, ``vector_alpha`` is
clamped to be strictly < 1.
"""
_check_option('transparent', type(transparent), [bool])
# those parameters are not supported yet, only None is allowed
_check_option('thresh', thresh, [None])
_check_option('remove_existing', remove_existing, [None])
_check_option('time_label_size', time_label_size, [None])
_check_option('scale_factor', scale_factor, [None])
_check_option('vector_alpha', vector_alpha, [None])
hemi = self._check_hemi(hemi)
array = np.asarray(array)
# Create time array and add label if > 1D
if array.ndim <= 1:
time_idx = 0
else:
# check time array
if time is None:
time = np.arange(array.shape[-1])
else:
time = np.asarray(time)
if time.shape != (array.shape[-1],):
raise ValueError('time has shape %s, but need shape %s '
'(array.shape[-1])' %
(time.shape, (array.shape[-1],)))
if self._n_times is None:
self._n_times = len(time)
self._times = time
elif len(time) != self._n_times:
raise ValueError("New n_times is different from previous "
"n_times")
elif not np.array_equal(time, self._times):
raise ValueError("Not all time values are consistent with "
"previously set times.")
# initial time
if initial_time is None:
time_idx = 0
else:
time_idx = self.index_for_time(initial_time)
# time label
if isinstance(time_label, str):
time_label_fmt = time_label
def time_label(x):
return time_label_fmt % x
self._data["time_label"] = time_label
self._data["time"] = time
self._data["time_idx"] = 0
y_txt = 0.05 + 0.1 * bool(colorbar)
if time is not None and len(array.shape) == 2:
# we have scalar_data with time dimension
act_data = array[:, time_idx]
else:
# we have scalar data without time
act_data = array
fmin, fmid, fmax = _update_limits(
fmin, fmid, fmax, center, array
)
self._data['time'] = time
self._data['initial_time'] = initial_time
self._data['time_label'] = time_label
self._data['time_idx'] = time_idx
# data specific for a hemi
self._data[hemi + '_array'] = array
self._data['alpha'] = alpha
self._data['colormap'] = colormap
self._data['center'] = center
self._data['fmin'] = fmin
self._data['fmid'] = fmid
self._data['fmax'] = fmax
# Create smoothing matrix if necessary
if len(act_data) < self.geo[hemi].x.shape[0]:
if vertices is None:
raise ValueError('len(data) < nvtx (%s < %s): the vertices '
'parameter must not be None'
% (len(act_data), self.geo[hemi].x.shape[0]))
adj_mat = mesh_edges(self.geo[hemi].faces)
smooth_mat = smoothing_matrix(vertices,
adj_mat,
smoothing_steps)
act_data = smooth_mat.dot(act_data)
self._data[hemi + '_smooth_mat'] = smooth_mat
dt_max = fmax
dt_min = fmin if center is None else -1 * fmax
ctable = self.update_lut(transparent=transparent)
for ri, v in enumerate(self._views):
views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict
if self._hemi != 'split':
ci = 0
else:
ci = 0 if hemi == 'lh' else 1
self._renderer.subplot(ri, ci)
mesh = self._renderer.mesh(x=self.geo[hemi].coords[:, 0],
y=self.geo[hemi].coords[:, 1],
z=self.geo[hemi].coords[:, 2],
triangles=self.geo[hemi].faces,
color=None,
colormap=ctable,
vmin=dt_min,
vmax=dt_max,
scalars=act_data)
if array.ndim >= 2 and callable(time_label):
self._renderer.text2d(x_window=0.95, y_window=y_txt,
size=time_label_size,
text=time_label(time[time_idx]),
justification='right')
if colorbar and not self._colorbar_added:
self._renderer.scalarbar(source=mesh, n_labels=8,
bgcolor=(0.5, 0.5, 0.5))
self._colorbar_added = True
self._renderer.set_camera(azimuth=views_dict[v].azim,
elevation=views_dict[v].elev)
def add_label(self, label, color=None, alpha=1, scalar_thresh=None,
borders=False, hemi=None, subdir=None):
"""Add an ROI label to the image.
Parameters
----------
label : str | instance of Label
label filepath or name. Can also be an instance of
an object with attributes "hemi", "vertices", "name", and
optionally "color" and "values" (if scalar_thresh is not None).
color : matplotlib-style color | None
anything matplotlib accepts: string, RGB, hex, etc. (default
"crimson")
alpha : float in [0, 1]
alpha level to control opacity
scalar_thresh : None or number
threshold the label ids using this value in the label
file's scalar field (i.e. label only vertices with
scalar >= thresh)
borders : bool | int
Show only label borders. If int, specify the number of steps
(away from the true border) along the cortical mesh to include
as part of the border definition.
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, an error will
be thrown.
subdir : None | str
If a label is specified as name, subdir can be used to indicate
that the label file is in a sub-directory of the subject's
label directory rather than in the label directory itself (e.g.
for ``$SUBJECTS_DIR/$SUBJECT/label/aparc/lh.cuneus.label``
``brain.add_label('cuneus', subdir='aparc')``).
Notes
-----
To remove previously added labels, run Brain.remove_labels().
"""
from matplotlib.colors import colorConverter
if isinstance(label, str):
hemi = self._check_hemi(hemi)
if color is None:
color = "crimson"
if os.path.isfile(label):
filepath = label
label_name = os.path.basename(filepath).split('.')[1]
else:
label_name = label
label_fname = ".".join([hemi, label_name, 'label'])
if subdir is None:
filepath = pjoin(self._subjects_dir, self._subject_id,
'label', label_fname)
else:
filepath = pjoin(self._subjects_dir, self._subject_id,
'label', subdir, label_fname)
if not os.path.exists(filepath):
raise ValueError('Label file %s does not exist'
% filepath)
label = read_label(filepath)
ids = label.vertices
else:
# try to extract parameters from label instance
try:
hemi = label.hemi
ids = label.vertices
if label.name is None:
label_name = 'unnamed'
else:
label_name = str(label.name)
if color is None:
if hasattr(label, 'color') and label.color is not None:
color = label.color
else:
color = "crimson"
if scalar_thresh is not None:
scalars = label.values
except Exception:
raise ValueError('Label was not a filename (str), and could '
'not be understood as a class. The class '
'must have attributes "hemi", "vertices", '
'"name", and (if scalar_thresh is not None)'
'"values"')
hemi = self._check_hemi(hemi)
if scalar_thresh is not None:
ids = ids[scalars >= scalar_thresh]
# XXX: add support for label_name
self._label_name = label_name
label = np.zeros(self.geo[hemi].coords.shape[0])
label[ids] = 1
color = colorConverter.to_rgba(color, alpha)
cmap = np.array([(0, 0, 0, 0,), color])
ctable = np.round(cmap * 255).astype(np.uint8)
for ri, v in enumerate(self._views):
if self._hemi != 'split':
ci = 0
else:
ci = 0 if hemi == 'lh' else 1
self._renderer.subplot(ri, ci)
self._renderer.mesh(x=self.geo[hemi].coords[:, 0],
y=self.geo[hemi].coords[:, 1],
z=self.geo[hemi].coords[:, 2],
triangles=self.geo[hemi].faces,
scalars=label,
color=None,
colormap=ctable,
backface_culling=False)
self._renderer.set_camera(azimuth=0.,
elevation=90.)
def add_foci(self, coords, coords_as_verts=False, map_surface=None,
scale_factor=1, color="white", alpha=1, name=None,
hemi=None):
"""Add spherical foci, possibly mapping to displayed surf.
The foci spheres can be displayed at the coordinates given, or
mapped through a surface geometry. In other words, coordinates
from a volume-based analysis in MNI space can be displayed on an
inflated average surface by finding the closest vertex on the
white surface and mapping to that vertex on the inflated mesh.
Parameters
----------
coords : numpy array
x, y, z coordinates in stereotaxic space (default) or array of
vertex ids (with ``coord_as_verts=True``)
coords_as_verts : bool
whether the coords parameter should be interpreted as vertex ids
map_surface : Freesurfer surf or None
surface to map coordinates through, or None to use raw coords
scale_factor : float
Controls the size of the foci spheres (relative to 1cm).
color : matplotlib color code
HTML name, RBG tuple, or hex code
alpha : float in [0, 1]
opacity of focus gylphs
name : str
internal name to use
hemi : str | None
If None, it is assumed to belong to the hemipshere being
shown. If two hemispheres are being shown, an error will
be thrown.
"""
from matplotlib.colors import colorConverter
hemi = self._check_hemi(hemi)
# those parameters are not supported yet, only None is allowed
_check_option('map_surface', map_surface, [None])
# Figure out how to interpret the first parameter
if coords_as_verts:
coords = self.geo[hemi].coords[coords]
# Convert the color code
if not isinstance(color, tuple):
color = colorConverter.to_rgb(color)
if self._units == 'm':
scale_factor = scale_factor / 1000.
for ri, v in enumerate(self._views):
views_dict = lh_views_dict if hemi == 'lh' else rh_views_dict
if self._hemi != 'split':
ci = 0
else:
ci = 0 if hemi == 'lh' else 1
self._renderer.subplot(ri, ci)
self._renderer.sphere(center=coords, color=color,
scale=(10. * scale_factor),
opacity=alpha)
self._renderer.set_camera(azimuth=views_dict[v].azim,
elevation=views_dict[v].elev)
def add_text(self, x, y, text, name=None, color=None, opacity=1.0,
row=-1, col=-1, font_size=None, justification=None):
"""Add a text to the visualization.
Parameters
----------
x : Float
x coordinate
y : Float
y coordinate
text : str
Text to add
name : str
Name of the text (text label can be updated using update_text())
color : Tuple
Color of the text. Default is the foreground color set during
initialization (default is black or white depending on the
background color).
opacity : Float
Opacity of the text. Default: 1.0
row : int
Row index of which brain to use
col : int
Column index of which brain to use
"""
# XXX: support `name` should be added when update_text/remove_text
# are implemented
# _check_option('name', name, [None])
self._renderer.text2d(x_window=x, y_window=y, text=text, color=color,
size=font_size, justification=justification)
def remove_labels(self, labels=None):
"""Remove one or more previously added labels from the image.
Parameters
----------
labels : None | str | list of str
Labels to remove. Can be a string naming a single label, or None to
remove all labels. Possible names can be found in the Brain.labels
attribute.
"""
pass
def index_for_time(self, time, rounding='closest'):
"""Find the data time index closest to a specific time point.
Parameters
----------
time : scalar
Time.
rounding : 'closest' | 'up' | 'down'
How to round if the exact time point is not an index.
Returns
-------
index : int
Data time index closest to time.
"""
if self._n_times is None:
raise RuntimeError("Brain has no time axis")
times = self._times
# Check that time is in range
tmin = np.min(times)
tmax = np.max(times)
max_diff = (tmax - tmin) / (len(times) - 1) / 2
if time < tmin - max_diff or time > tmax + max_diff:
err = ("time = %s lies outside of the time axis "
"[%s, %s]" % (time, tmin, tmax))
raise ValueError(err)
if rounding == 'closest':
idx = np.argmin(np.abs(times - time))
elif rounding == 'up':
idx = np.nonzero(times >= time)[0][0]
elif rounding == 'down':
idx = np.nonzero(times <= time)[0][-1]
else:
err = "Invalid rounding parameter: %s" % repr(rounding)
raise ValueError(err)
return idx
def close(self):
"""Close all figures and cleanup data structure."""
self._renderer.close()
def show_view(self, view=None, roll=None, distance=None):
"""Orient camera to display view."""
views_dict = lh_views_dict if self._hemi == 'lh' else rh_views_dict
if isinstance(view, str):
view = views_dict.get(view)
elif isinstance(view, dict):
view = View(azim=view['azimuth'],
elev=view['elevation'])
self._renderer.set_camera(azimuth=view.azim,
elevation=view.elev)
def save_image(self, filename, mode='rgb'):
"""Save view from all panels to disk.
Parameters
----------
filename: string
path to new image file
mode : string
Either 'rgb' or 'rgba' for values to return.
"""
self._renderer.screenshot(mode=mode, filename=filename)
def screenshot(self, mode='rgb'):
"""Generate a screenshot of current view.
Parameters
----------
mode : string
Either 'rgb' or 'rgba' for values to return.
Returns
-------
screenshot : array
Image pixel values.
"""
return self._renderer.screenshot(mode)
def update_lut(self, fmin=None, fmid=None, fmax=None, transparent=True):
u"""Update color map.
Parameters
----------
fmin : float | None
Minimum value in colormap.
fmid : float | None
Intermediate value in colormap (fmid between fmin and
fmax).
fmax : float | None
Maximum value in colormap.
"""
alpha = self._data['alpha']
center = self._data['center']
colormap = self._data['colormap']
fmin = self._data['fmin'] if fmin is None else fmin
fmid = self._data['fmid'] if fmid is None else fmid
fmax = self._data['fmax'] if fmax is None else fmax
self._data['ctable'] = \
calculate_lut(colormap, alpha=alpha, fmin=fmin, fmid=fmid,
fmax=fmax, center=center, transparent=transparent)
return self._data['ctable']
@property
def overlays(self):
return self._overlays
@property
def data(self):
u"""Data used by time viewer and color bar widgets."""
return self._data
@property
def views(self):
return self._views
@property
def hemis(self):
return self._hemis
def _show(self):
"""Request rendering of the window."""
try:
return self._renderer.show()
except RuntimeError:
logger.info("No active/running renderer available.")
def _check_hemi(self, hemi):
u"""Check for safe single-hemi input, returns str."""
if hemi is None:
if self._hemi not in ['lh', 'rh']:
raise ValueError('hemi must not be None when both '
'hemispheres are displayed')
else:
hemi = self._hemi
elif hemi not in ['lh', 'rh']:
extra = ' or None' if self._hemi in ['lh', 'rh'] else ''
raise ValueError('hemi must be either "lh" or "rh"' +
extra + ", got " + str(hemi))
return hemi
def _update_limits(fmin, fmid, fmax, center, array):
if center is None:
if fmin is None:
fmin = array.min() if array.size > 0 else 0
if fmax is None:
fmax = array.max() if array.size > 0 else 1
else:
if fmin is None:
fmin = 0
if fmax is None:
fmax = np.abs(center - array).max() if array.size > 0 else 1
if fmid is None:
fmid = (fmin + fmax) / 2.
if fmin >= fmid:
raise RuntimeError('min must be < mid, got %0.4g >= %0.4g'
% (fmin, fmid))
if fmid >= fmax:
raise RuntimeError('mid must be < max, got %0.4g >= %0.4g'
% (fmid, fmax))
return fmin, fmid, fmax
| 41.795967
| 79
| 0.511551
|
4a0a556137d7f622b065a2285a86867edf320052
| 11,497
|
py
|
Python
|
ext/opentelemetry-ext-otcollector/tests/test_otcollector_trace_exporter.py
|
nirsky/opentelemetry-python
|
8d09319c43a24b05d14128361de2c9afe8c856b6
|
[
"Apache-2.0"
] | null | null | null |
ext/opentelemetry-ext-otcollector/tests/test_otcollector_trace_exporter.py
|
nirsky/opentelemetry-python
|
8d09319c43a24b05d14128361de2c9afe8c856b6
|
[
"Apache-2.0"
] | null | null | null |
ext/opentelemetry-ext-otcollector/tests/test_otcollector_trace_exporter.py
|
nirsky/opentelemetry-python
|
8d09319c43a24b05d14128361de2c9afe8c856b6
|
[
"Apache-2.0"
] | null | null | null |
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
import unittest
from unittest import mock
import grpc
from google.protobuf.timestamp_pb2 import Timestamp
from opencensus.proto.trace.v1 import trace_pb2
import opentelemetry.ext.otcollector.util as utils
from opentelemetry import trace as trace_api
from opentelemetry.ext.otcollector.trace_exporter import (
CollectorSpanExporter,
translate_to_collector,
)
from opentelemetry.sdk import trace
from opentelemetry.sdk.trace.export import SpanExportResult
from opentelemetry.trace import TraceFlags
# pylint: disable=no-member
class TestCollectorSpanExporter(unittest.TestCase):
def test_constructor(self):
mock_get_node = mock.Mock()
patch = mock.patch(
"opentelemetry.ext.otcollector.util.get_node",
side_effect=mock_get_node,
)
service_name = "testServiceName"
host_name = "testHostName"
client = grpc.insecure_channel("")
endpoint = "testEndpoint"
with patch:
exporter = CollectorSpanExporter(
service_name=service_name,
host_name=host_name,
endpoint=endpoint,
client=client,
)
self.assertIs(exporter.client, client)
self.assertEqual(exporter.endpoint, endpoint)
mock_get_node.assert_called_with(service_name, host_name)
def test_get_collector_span_kind(self):
result = utils.get_collector_span_kind(trace_api.SpanKind.SERVER)
self.assertIs(result, trace_pb2.Span.SpanKind.SERVER)
result = utils.get_collector_span_kind(trace_api.SpanKind.CLIENT)
self.assertIs(result, trace_pb2.Span.SpanKind.CLIENT)
result = utils.get_collector_span_kind(trace_api.SpanKind.CONSUMER)
self.assertIs(result, trace_pb2.Span.SpanKind.SPAN_KIND_UNSPECIFIED)
result = utils.get_collector_span_kind(trace_api.SpanKind.PRODUCER)
self.assertIs(result, trace_pb2.Span.SpanKind.SPAN_KIND_UNSPECIFIED)
result = utils.get_collector_span_kind(trace_api.SpanKind.INTERNAL)
self.assertIs(result, trace_pb2.Span.SpanKind.SPAN_KIND_UNSPECIFIED)
def test_proto_timestamp_from_time_ns(self):
result = utils.proto_timestamp_from_time_ns(12345)
self.assertIsInstance(result, Timestamp)
self.assertEqual(result.nanos, 12345)
# pylint: disable=too-many-locals
# pylint: disable=too-many-statements
def test_translate_to_collector(self):
trace_id = 0x6E0C63257DE34C926F9EFCD03927272E
span_id = 0x34BF92DEEFC58C92
parent_id = 0x1111111111111111
base_time = 683647322 * 10 ** 9 # in ns
start_times = (
base_time,
base_time + 150 * 10 ** 6,
base_time + 300 * 10 ** 6,
)
durations = (50 * 10 ** 6, 100 * 10 ** 6, 200 * 10 ** 6)
end_times = (
start_times[0] + durations[0],
start_times[1] + durations[1],
start_times[2] + durations[2],
)
span_context = trace_api.SpanContext(
trace_id,
span_id,
is_remote=False,
trace_flags=TraceFlags(TraceFlags.SAMPLED),
trace_state=trace_api.TraceState({"testKey": "testValue"}),
)
parent_context = trace_api.SpanContext(
trace_id, parent_id, is_remote=False
)
other_context = trace_api.SpanContext(
trace_id, span_id, is_remote=False
)
event_attributes = {
"annotation_bool": True,
"annotation_string": "annotation_test",
"key_float": 0.3,
}
event_timestamp = base_time + 50 * 10 ** 6
event = trace.Event(
name="event0",
timestamp=event_timestamp,
attributes=event_attributes,
)
link_attributes = {"key_bool": True}
link_1 = trace_api.Link(
context=other_context, attributes=link_attributes
)
link_2 = trace_api.Link(
context=parent_context, attributes=link_attributes
)
span_1 = trace.Span(
name="test1",
context=span_context,
parent=parent_context,
events=(event,),
links=(link_1,),
kind=trace_api.SpanKind.CLIENT,
)
span_2 = trace.Span(
name="test2",
context=parent_context,
parent=None,
kind=trace_api.SpanKind.SERVER,
)
span_3 = trace.Span(
name="test3",
context=other_context,
links=(link_2,),
parent=span_2.get_context(),
)
otel_spans = [span_1, span_2, span_3]
otel_spans[0].start(start_time=start_times[0])
otel_spans[0].set_attribute("key_bool", False)
otel_spans[0].set_attribute("key_string", "hello_world")
otel_spans[0].set_attribute("key_float", 111.22)
otel_spans[0].set_attribute("key_int", 333)
otel_spans[0].set_status(
trace_api.Status(
trace_api.status.StatusCanonicalCode.INTERNAL,
"test description",
)
)
otel_spans[0].end(end_time=end_times[0])
otel_spans[1].start(start_time=start_times[1])
otel_spans[1].end(end_time=end_times[1])
otel_spans[2].start(start_time=start_times[2])
otel_spans[2].end(end_time=end_times[2])
output_spans = translate_to_collector(otel_spans)
self.assertEqual(len(output_spans), 3)
self.assertEqual(
output_spans[0].trace_id, b"n\x0cc%}\xe3L\x92o\x9e\xfc\xd09''."
)
self.assertEqual(
output_spans[0].span_id, b"4\xbf\x92\xde\xef\xc5\x8c\x92"
)
self.assertEqual(
output_spans[0].name, trace_pb2.TruncatableString(value="test1")
)
self.assertEqual(
output_spans[1].name, trace_pb2.TruncatableString(value="test2")
)
self.assertEqual(
output_spans[2].name, trace_pb2.TruncatableString(value="test3")
)
self.assertEqual(
output_spans[0].start_time.seconds,
int(start_times[0] / 1000000000),
)
self.assertEqual(
output_spans[0].end_time.seconds, int(end_times[0] / 1000000000)
)
self.assertEqual(output_spans[0].kind, trace_api.SpanKind.CLIENT.value)
self.assertEqual(output_spans[1].kind, trace_api.SpanKind.SERVER.value)
self.assertEqual(
output_spans[0].parent_span_id, b"\x11\x11\x11\x11\x11\x11\x11\x11"
)
self.assertEqual(
output_spans[2].parent_span_id, b"\x11\x11\x11\x11\x11\x11\x11\x11"
)
self.assertEqual(
output_spans[0].status.code,
trace_api.status.StatusCanonicalCode.INTERNAL.value,
)
self.assertEqual(output_spans[0].status.message, "test description")
self.assertEqual(len(output_spans[0].tracestate.entries), 1)
self.assertEqual(output_spans[0].tracestate.entries[0].key, "testKey")
self.assertEqual(
output_spans[0].tracestate.entries[0].value, "testValue"
)
self.assertEqual(
output_spans[0].attributes.attribute_map["key_bool"].bool_value,
False,
)
self.assertEqual(
output_spans[0]
.attributes.attribute_map["key_string"]
.string_value.value,
"hello_world",
)
self.assertEqual(
output_spans[0].attributes.attribute_map["key_float"].double_value,
111.22,
)
self.assertEqual(
output_spans[0].attributes.attribute_map["key_int"].int_value, 333
)
self.assertEqual(
output_spans[0].time_events.time_event[0].time.seconds, 683647322
)
self.assertEqual(
output_spans[0]
.time_events.time_event[0]
.annotation.description.value,
"event0",
)
self.assertEqual(
output_spans[0]
.time_events.time_event[0]
.annotation.attributes.attribute_map["annotation_bool"]
.bool_value,
True,
)
self.assertEqual(
output_spans[0]
.time_events.time_event[0]
.annotation.attributes.attribute_map["annotation_string"]
.string_value.value,
"annotation_test",
)
self.assertEqual(
output_spans[0]
.time_events.time_event[0]
.annotation.attributes.attribute_map["key_float"]
.double_value,
0.3,
)
self.assertEqual(
output_spans[0].links.link[0].trace_id,
b"n\x0cc%}\xe3L\x92o\x9e\xfc\xd09''.",
)
self.assertEqual(
output_spans[0].links.link[0].span_id,
b"4\xbf\x92\xde\xef\xc5\x8c\x92",
)
self.assertEqual(
output_spans[0].links.link[0].type,
trace_pb2.Span.Link.Type.TYPE_UNSPECIFIED,
)
self.assertEqual(
output_spans[2].links.link[0].type,
trace_pb2.Span.Link.Type.PARENT_LINKED_SPAN,
)
self.assertEqual(
output_spans[0]
.links.link[0]
.attributes.attribute_map["key_bool"]
.bool_value,
True,
)
def test_export(self):
mock_client = mock.MagicMock()
mock_export = mock.MagicMock()
mock_client.Export = mock_export
host_name = "testHostName"
collector_exporter = CollectorSpanExporter(
client=mock_client, host_name=host_name
)
trace_id = 0x6E0C63257DE34C926F9EFCD03927272E
span_id = 0x34BF92DEEFC58C92
span_context = trace_api.SpanContext(
trace_id,
span_id,
is_remote=False,
trace_flags=TraceFlags(TraceFlags.SAMPLED),
)
otel_spans = [
trace.Span(
name="test1",
context=span_context,
kind=trace_api.SpanKind.CLIENT,
)
]
result_status = collector_exporter.export(otel_spans)
self.assertEqual(SpanExportResult.SUCCESS, result_status)
# pylint: disable=unsubscriptable-object
export_arg = mock_export.call_args[0]
service_request = next(export_arg[0])
output_spans = getattr(service_request, "spans")
output_node = getattr(service_request, "node")
self.assertEqual(len(output_spans), 1)
self.assertIsNotNone(getattr(output_node, "library_info"))
self.assertIsNotNone(getattr(output_node, "service_info"))
output_identifier = getattr(output_node, "identifier")
self.assertEqual(
getattr(output_identifier, "host_name"), "testHostName"
)
| 36.268139
| 79
| 0.616161
|
4a0a559463a85757a42ba71a9dedca02c59e4314
| 121
|
py
|
Python
|
tests/Usage.py
|
astronalta/gamepython
|
3927dfbb0ae9706cd99d4f15ea792b30512dd4c1
|
[
"MIT"
] | null | null | null |
tests/Usage.py
|
astronalta/gamepython
|
3927dfbb0ae9706cd99d4f15ea792b30512dd4c1
|
[
"MIT"
] | null | null | null |
tests/Usage.py
|
astronalta/gamepython
|
3927dfbb0ae9706cd99d4f15ea792b30512dd4c1
|
[
"MIT"
] | null | null | null |
import os
os.system(os.path.join("..", "bin", "jogo") + " --help")
os.system(os.path.join("..", "bin", "jogo") + " -h")
| 24.2
| 56
| 0.520661
|
4a0a55eeba54edd27785e267bd9ff0a3df193143
| 2,202
|
py
|
Python
|
ooobuild/lo/ucb/x_cached_dynamic_result_set_factory.py
|
Amourspirit/ooo_uno_tmpl
|
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
|
[
"Apache-2.0"
] | null | null | null |
ooobuild/lo/ucb/x_cached_dynamic_result_set_factory.py
|
Amourspirit/ooo_uno_tmpl
|
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
|
[
"Apache-2.0"
] | null | null | null |
ooobuild/lo/ucb/x_cached_dynamic_result_set_factory.py
|
Amourspirit/ooo_uno_tmpl
|
64e0c86fd68f24794acc22d63d8d32ae05dd12b8
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
#
# Interface Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.ucb
import typing
from abc import abstractmethod
from ..uno.x_interface import XInterface as XInterface_8f010a43
if typing.TYPE_CHECKING:
from .x_content_identifier_mapping import XContentIdentifierMapping as XContentIdentifierMapping_56ef1044
from .x_dynamic_result_set import XDynamicResultSet as XDynamicResultSet_e0360d0a
class XCachedDynamicResultSetFactory(XInterface_8f010a43):
"""
creates a CachedDynamicResultSet.
Pay attention to instantiate this helper on client side where your want to read the data respectively where you have instantiated the listener to the XDynamicResultSet.
The needed stub on server side can be created using XCachedDynamicResultSetStubFactory.
See Also:
`API XCachedDynamicResultSetFactory <https://api.libreoffice.org/docs/idl/ref/interfacecom_1_1sun_1_1star_1_1ucb_1_1XCachedDynamicResultSetFactory.html>`_
"""
__ooo_ns__: str = 'com.sun.star.ucb'
__ooo_full_ns__: str = 'com.sun.star.ucb.XCachedDynamicResultSetFactory'
__ooo_type_name__: str = 'interface'
__pyunointerface__: str = 'com.sun.star.ucb.XCachedDynamicResultSetFactory'
@abstractmethod
def createCachedDynamicResultSet(self, SourceStub: 'XDynamicResultSet_e0360d0a', ContentIdentifierMapping: 'XContentIdentifierMapping_56ef1044') -> 'XDynamicResultSet_e0360d0a':
"""
creates a remote optimizes XDynamicResultSet.
"""
__all__ = ['XCachedDynamicResultSetFactory']
| 42.346154
| 181
| 0.7802
|
4a0a591c2ef1f9311a932db9e06994bdde99d3ae
| 1,683
|
py
|
Python
|
cloudedbats_wurb/wurb_core/__init__.py
|
cloudedbats/cloudedbats_wurb
|
e3b7639cf9fb9a6415675bde68c0990131db0291
|
[
"MIT"
] | 1
|
2021-09-20T07:43:06.000Z
|
2021-09-20T07:43:06.000Z
|
cloudedbats_wurb/wurb_core/__init__.py
|
cloudedbats/cloudedbats_wurb
|
e3b7639cf9fb9a6415675bde68c0990131db0291
|
[
"MIT"
] | null | null | null |
cloudedbats_wurb/wurb_core/__init__.py
|
cloudedbats/cloudedbats_wurb
|
e3b7639cf9fb9a6415675bde68c0990131db0291
|
[
"MIT"
] | 2
|
2019-04-15T22:07:52.000Z
|
2021-06-09T05:44:47.000Z
|
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Project: http://cloudedbats.org
# Copyright (c) 2016-2018 Arnold Andreasson
# License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit).
from .wurb_utils import singleton
# Lib modules.
from .lib.solartime import SolarTime
from .lib.dsp4bats.frequency_domain_utils import DbfsSpectrumUtil
# # Check if librosa is available.
# try:
# import librosa
# from .lib.dsp4bats.time_domain_utils import SignalUtil
# except: pass
# Base classes for sound streaming.
from .lib.dsp4bats.sound_stream_manager import SoundStreamManager
from .lib.dsp4bats.sound_stream_manager import SoundSourceBase
from .lib.dsp4bats.sound_stream_manager import SoundProcessBase
from .lib.dsp4bats.sound_stream_manager import SoundTargetBase
# Special code for Petterson M500. Designed for Windows USB.
from wurb_core.lib.pettersson_m500_batmic import PetterssonM500BatMic
# WURB Modules.
from .wurb_sunset_sunrise import WurbSunsetSunrise # Singleton.
from .wurb_gps_reader import WurbGpsReader # Singleton.
from .wurb_settings import WurbSettings
from .wurb_state_machine import WurbStateMachine
from .wurb_scheduler import WurbScheduler
from .wurb_logging import WurbLogging
# Sound data flow from microphone to file.
from .wurb_recorder import get_device_list
from .wurb_recorder import get_device_index
from .wurb_recorder import SoundSource
from .wurb_recorder import SoundSourceM500
from .wurb_recorder import SoundProcess
from .wurb_recorder import SoundTarget
from .wurb_recorder import WurbRecorder
# Sound detection.
from .wurb_sound_detector import SoundDetector
# Main app.
from .wurb_application import WurbApplication
| 35.0625
| 79
| 0.825906
|
4a0a598055ac0cfe6e245c1477fc35fa744e7785
| 35,199
|
py
|
Python
|
tflib.py
|
RyanDunham98/PrimateFaceRecognition
|
bea00972cbde323daf79c84bd26b0f545511fddc
|
[
"MIT"
] | null | null | null |
tflib.py
|
RyanDunham98/PrimateFaceRecognition
|
bea00972cbde323daf79c84bd26b0f545511fddc
|
[
"MIT"
] | null | null | null |
tflib.py
|
RyanDunham98/PrimateFaceRecognition
|
bea00972cbde323daf79c84bd26b0f545511fddc
|
[
"MIT"
] | null | null | null |
"""Functions for building tensorflow graph
"""
# MIT License
#
# Copyright (c) 2018 Debayan Deb
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import tensorflow as tf
import tensorflow.contrib.slim as slim
#input a list of tensors
def average_tensors(tensors, name=None):
if len(tensors) == 1:
return tf.identity(tensors[0], name=name)
else:
# Each tensor in the list should be of the same size
expanded_tensors = []
for t in tensors:
#Returns a tensor with an additional dimension inserted at
#index axis, axis = 0 which is rows
#This operation is useful if you want to add a batch dimension to a single element
#batch is the number of images trained at once
expanded_t = tf.expand_dims(t, 0)
#add expanded tensor to new list of tensors
expanded_tensors.append(expanded_t)
#Concatenates tensors along one dimension(axis = 0) rows
average_tensor = tf.concat(axis=0, values=expanded_tensors)
#Computes the mean of elements across dimensions of a tensor
average_tensor = tf.reduce_mean(average_tensor, 0, name=name)
return average_tensor
#tower is a function for computing inference and gradients for a single model replica
def average_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of gradients. The outer list is over different
towers. The inner list is over the gradient calculation in each tower.
Returns:
List of gradients where the gradient has been averaged across all towers.
"""
if len(tower_grads) == 1:
return tower_grads[0]
else:
average_grads = []
for grad_ in zip(*tower_grads):
# Note that each grad looks like the following:
# (grad0_gpu0, ... , grad0_gpuN)
average_grad = None if grad_[0]==None else average_tensors(grad_)
average_grads.append(average_grad)
return average_grads
def apply_gradient(update_gradient_vars, grads, optimizer, learning_rate, learning_rate_multipliers=None):
assert(len(grads)==len(update_gradient_vars))
if learning_rate_multipliers is None: learning_rate_multipliers = {}
# Build a dictionary to save multiplier config
# format -> {scope_name: ((grads, vars), lr_multi)}
learning_rate_dict = {}
learning_rate_dict['__default__'] = ([], 1.0)
for scope, multiplier in learning_rate_multipliers.items():
assert scope != '__default__'
learning_rate_dict[scope] = ([], multiplier)
# Scan all the variables, insert into dict
scopes = learning_rate_dict.keys()
for var, grad in zip(update_gradient_vars, grads):
count = 0
scope_temp = ''
for scope in scopes:
if scope in var.name:
scope_temp = scope
count += 1
assert count <= 1, "More than one multiplier scopes appear in variable: %s" % var.name
if count == 0: scope_temp = '__default__'
if grad is not None:
learning_rate_dict[scope_temp][0].append((grad, var))
# Build a optimizer for each multiplier scope
apply_gradient_ops = []
print('\nLearning rate multipliers:')
for scope, scope_content in learning_rate_dict.items():
scope_grads_vars, multiplier = scope_content
print('%s:\n # variables: %d\n lr_multi: %f' % (scope, len(scope_grads_vars), multiplier))
if len(scope_grads_vars) == 0:
continue
scope_learning_rate = multiplier * learning_rate
if optimizer=='ADAGRAD':
opt = tf.train.AdagradOptimizer(scope_learning_rate)
elif optimizer=='ADADELTA':
opt = tf.train.AdadeltaOptimizer(scope_learning_rate, rho=0.9, epsilon=1e-6)
elif optimizer=='ADAM':
opt = tf.train.AdamOptimizer(scope_learning_rate, beta1=0.9, beta2=0.999, epsilon=0.1)
elif optimizer=='RMSPROP':
opt = tf.train.RMSPropOptimizer(scope_learning_rate, decay=0.9, momentum=0.9, epsilon=1.0)
elif optimizer=='MOM':
opt = tf.train.MomentumOptimizer(scope_learning_rate, 0.9, use_nesterov=False)
elif optimizer=='SGD':
opt = tf.train.GradientDescentOptimizer(scope_learning_rate)
else:
raise ValueError('Invalid optimization algorithm')
apply_gradient_ops.append(opt.apply_gradients(scope_grads_vars))
print('')
apply_gradient_op = tf.group(*apply_gradient_ops)
return apply_gradient_op
#finds the rank 1 accuracy
def rank_accuracy(logits, label, batch_size, k=1):
#Finds values and indices of the k largest entries for the last dimension
_, arg_top = tf.nn.top_k(logits, k)
#casts a tensor to a new type
label = tf.cast(label, tf.int32)
#reshapes a tesor
label = tf.reshape(label, [batch_size, 1])
#Constructs a tensor by tiling a given tensor.
label = tf.tile(label, [1, k])
#Computes the "logical or" of elements across dimensions of a tensor
correct = tf.reduce_any(tf.equal(label, arg_top), axis=1)
#Computes the mean of elements across dimensions of a tensor.
accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
return accuracy
def collect_watch_list():
'''Collect the variables in watch list.
Tensors or Varialbes can be addto collection 'watchlist' with
the type of tuple ('name', var/tensor). The functions collects
them and returns a dict for evaluate
'''
watch_list = {}
for pair in tf.get_collection('watch_list'):
watch_list[pair[0]] = pair[1]
return watch_list
def save_model(sess, saver, model_dir, global_step):
with sess.graph.as_default():
checkpoint_path = os.path.join(model_dir, 'ckpt')
metagraph_path = os.path.join(model_dir, 'graph.meta')
print('Saving variables...')
saver.save(sess, checkpoint_path, global_step=global_step, write_meta_graph=False)
if not os.path.exists(metagraph_path):
print('Saving metagraph...')
saver.export_meta_graph(metagraph_path)
def restore_model(sess, var_list, model_dir, restore_scopes=None):
''' Load the variable values from a checkpoint file into pre-defined graph.
Filter the variables so that they contain at least one of the given keywords.'''
with sess.graph.as_default():
if restore_scopes is not None:
var_list = [var for var in var_list if any([scope in var.name for scope in restore_scopes])]
model_dir = os.path.expanduser(model_dir)
ckpt_file = tf.train.latest_checkpoint(model_dir)
print('Restoring variables from %s ...' % ckpt_file)
saver = tf.train.Saver(var_list)
saver.restore(sess, ckpt_file)
def load_model(sess, model_path, scope=None):
''' Load the the graph and variables values from a model path.
Model path is either a a frozen graph or a directory with both
a .meta file and checkpoint files.'''
with sess.graph.as_default():
model_path = os.path.expanduser(model_path)
if (os.path.isfile(model_path)):
# Frozen grpah
print('Model filename: %s' % model_path)
with gfile.FastGFile(model_path,'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
else:
# Load grapha and variables separatedly.
meta_files = [file for file in os.listdir(model_path) if file.endswith('.meta')]
assert len(meta_files) == 1
meta_file = os.path.join(model_path, meta_files[0])
ckpt_file = tf.train.latest_checkpoint(model_path)
print('Metagraph file: %s' % meta_file)
print('Checkpoint file: %s' % ckpt_file)
saver = tf.train.import_meta_graph(meta_file, clear_devices=True, import_scope=scope)
saver.restore(sess, ckpt_file)
def euclidean_distance(X, Y, sqrt=False):
'''Compute the distance between each X and Y.
Args:
X: a (m x d) tensor
Y: a (d x n) tensor
Returns:
diffs: an m x n distance matrix.
'''
with tf.name_scope('EuclideanDistance'):
XX = tf.reduce_sum(tf.square(X), 1, keep_dims=True)
YY = tf.reduce_sum(tf.square(Y), 0, keep_dims=True)
XY = tf.matmul(X, Y)
diffs = XX + YY - 2*XY
if sqrt == True:
diffs = tf.sqrt(tf.maximum(0.0, diffs))
return diffs
#softmax is an activation function that turns numbers aka logits into probabilities that sum to one.
#function outputs a vector that represents the probability distributions of a list of potential outcomes
def cosine_softmax(prelogits, label, num_classes, weight_decay, gamma=16.0, reuse=None):
nrof_features = prelogits.shape[1].value
with tf.variable_scope('Logits', reuse=reuse):
weights = tf.get_variable('weights', shape=(nrof_features, num_classes),
regularizer=slim.l2_regularizer(weight_decay),
initializer=slim.xavier_initializer(),
# initializer=tf.truncated_normal_initializer(stddev=0.1),
dtype=tf.float32)
alpha = tf.get_variable('alpha', shape=(),
regularizer=slim.l2_regularizer(1e-2),
initializer=tf.constant_initializer(1.00),
trainable=True,
dtype=tf.float32)
weights_normed = tf.nn.l2_normalize(weights, dim=0)
prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1)
if gamma == 'auto':
gamma = tf.nn.softplus(alpha)
else:
assert type(gamma) == float
gamma = tf.constant(gamma)
logits = gamma * tf.matmul(prelogits_normed, weights_normed)
cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\
labels=label, logits=logits), name='cross_entropy')
tf.summary.scalar('gamma', gamma)
tf.add_to_collection('watch_list', ('gamma', gamma))
return logits, cross_entropy
def norm_loss(prelogits, alpha, reuse=None):
with tf.variable_scope('NormLoss', reuse=reuse):
sigma = tf.get_variable('sigma', shape=(),
# regularizer=slim.l2_regularizer(weight_decay),
initializer=tf.constant_initializer(0.1),
trainable=True,
dtype=tf.float32)
prelogits_norm = tf.reduce_sum(tf.square(prelogits), axis=1)
# norm_loss = alpha * tf.square(tf.sqrt(prelogits_norm) - sigma)
norm_loss = alpha * prelogits_norm
norm_loss = tf.reduce_mean(norm_loss, axis=0, name='norm_loss')
# tf.summary.scalar('sigma', sigma)
# tf.add_to_collection('watch_list', ('sigma', sigma))
return norm_loss
#function proposed in sphereface
#To this end, we propose the angular softmax (A-Softmax) loss that enables convolutional neural
#networks (CNNs) to learn angularly discriminative features.Geometrically, A-Softmax loss can be
#viewed as imposing discriminative constraints on a hypersphere manifold, which intrinsically matches
#the prior that faces also lie on a manifold.
def angular_softmax(prelogits, label, num_classes, global_step,
m, lamb_min, lamb_max, weight_decay, reuse=None):
num_features = prelogits.shape[1].value
batch_size = tf.shape(prelogits)[0]
lamb_min = lamb_min
lamb_max = lamb_max
lambda_m_theta = [
lambda x: x**0,
lambda x: x**1,
lambda x: 2.0*(x**2) - 1.0,
lambda x: 4.0*(x**3) - 3.0*x,
lambda x: 8.0*(x**4) - 8.0*(x**2) + 1.0,
lambda x: 16.0*(x**5) - 20.0*(x**3) + 5.0*x
]
with tf.variable_scope('AngularSoftmax', reuse=reuse):
weights = tf.get_variable('weights', shape=(num_features, num_classes),
regularizer=slim.l2_regularizer(1e-4),
initializer=slim.xavier_initializer(),
# initializer=tf.truncated_normal_initializer(stddev=0.1),
trainable=True,
dtype=tf.float32)
lamb = tf.get_variable('lambda', shape=(),
initializer=tf.constant_initializer(lamb_max),
trainable=False,
dtype=tf.float32)
prelogits_norm = tf.sqrt(tf.reduce_sum(tf.square(prelogits), axis=1, keep_dims=True))
weights_normed = tf.nn.l2_normalize(weights, dim=0)
prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1)
# Compute cosine and phi
cos_theta = tf.matmul(prelogits_normed, weights_normed)
cos_theta = tf.minimum(1.0, tf.maximum(-1.0, cos_theta))
theta = tf.acos(cos_theta)
cos_m_theta = lambda_m_theta[m](cos_theta)
k = tf.floor(m*theta / 3.14159265)
phi_theta = tf.pow(-1.0, k) * cos_m_theta - 2.0 * k
cos_theta = cos_theta * prelogits_norm
phi_theta = phi_theta * prelogits_norm
lamb_new = tf.maximum(lamb_min, lamb_max/(1.0+0.1*tf.cast(global_step, tf.float32)))
update_lamb = tf.assign(lamb, lamb_new)
# Compute loss
with tf.control_dependencies([update_lamb]):
label_dense = tf.one_hot(label, num_classes, dtype=tf.float32)
logits = cos_theta
logits -= label_dense * cos_theta * 1.0 / (1.0+lamb)
logits += label_dense * phi_theta * 1.0 / (1.0+lamb)
cross_entropy = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\
labels=label, logits=logits), name='cross_entropy')
tf.add_to_collection('watch_list', ('lamb', lamb))
return cross_entropy
def split_softmax(prelogits, label, num_classes,
global_step, weight_decay, gamma=16.0, reuse=None):
nrof_features = prelogits.shape[1].value
batch_size = tf.shape(prelogits)[0]
with tf.variable_scope('SplitSoftmax', reuse=reuse):
weights = tf.get_variable('weights', shape=(num_classes, nrof_features),
regularizer=slim.l2_regularizer(weight_decay),
initializer=slim.xavier_initializer(),
# initializer=tf.truncated_normal_initializer(stddev=0.1),
# initializer=tf.constant_initializer(0),
trainable=True,
dtype=tf.float32)
alpha = tf.get_variable('alpha', shape=(),
regularizer=slim.l2_regularizer(1e-2),
initializer=tf.constant_initializer(1.00),
trainable=True,
dtype=tf.float32)
beta = tf.get_variable('beta', shape=(),
# regularizer=slim.l2_regularizer(1e-2),
initializer=tf.constant_initializer(0.0),
trainable=True,
dtype=tf.float32)
sigma = tf.get_variable('sigma', shape=(),
regularizer=slim.l2_regularizer(1e-1),
initializer=tf.constant_initializer(1.0),
trainable=True,
dtype=tf.float32)
threshold_pos = tf.get_variable('threshold_pos', shape=(),
initializer=tf.constant_initializer(16.0),
trainable=False,
dtype=tf.float32)
threshold_neg = tf.get_variable('threshold_neg', shape=(),
initializer=tf.constant_initializer(0.0),
trainable=False,
dtype=tf.float32)
# Normalizing the vecotors
weights_normed = tf.nn.l2_normalize(weights, dim=1)
prelogits_normed = tf.nn.l2_normalize(prelogits, dim=1)
# weights_normed = weights
# prelogits_normed = prelogits
# Caluculate Centers
centers, label_center, center_idx, center_weight = centers_by_label(prelogits_normed, label)
centers = tf.gather(centers, center_idx)
centers_normed = tf.nn.l2_normalize(centers, dim=1)
coef = 1.0
# Label and logits between batch and examplars
label_mat_glob = tf.one_hot(label, num_classes, dtype=tf.float32)
label_mask_pos_glob = tf.cast(label_mat_glob, tf.bool)
label_mask_neg_glob = tf.logical_not(label_mask_pos_glob)
# label_exp_batch = tf.expand_dims(label, 1)
# label_exp_glob = tf.expand_dims(label_history, 1)
# label_mat_glob = tf.equal(label_exp_batch, tf.transpose(label_exp_glob))
# label_mask_pos_glob = tf.cast(label_mat_glob, tf.bool)
# label_mask_neg_glob = tf.logical_not(label_mat_glob)
# dist_mat_glob = euclidean_distance(prelogits_normed, tf.transpose(weights_normed), False)
dist_mat_glob = tf.matmul(prelogits_normed, tf.transpose(weights_normed)) # + beta
dist_pos_glob = tf.boolean_mask(dist_mat_glob, label_mask_pos_glob)
dist_neg_glob = tf.boolean_mask(dist_mat_glob, label_mask_neg_glob)
logits_glob = coef * dist_mat_glob
logits_pos_glob = tf.boolean_mask(logits_glob, label_mask_pos_glob)
logits_neg_glob = tf.boolean_mask(logits_glob, label_mask_neg_glob)
# Label and logits within batch
label_exp_batch = tf.expand_dims(label, 1)
label_mat_batch = tf.equal(label_exp_batch, tf.transpose(label_exp_batch))
label_mask_pos_batch = tf.cast(label_mat_batch, tf.bool)
label_mask_neg_batch = tf.logical_not(label_mask_pos_batch)
mask_non_diag = tf.logical_not(tf.cast(tf.eye(batch_size), tf.bool))
label_mask_pos_batch = tf.logical_and(label_mask_pos_batch, mask_non_diag)
# dist_mat_batch = euclidean_distance(prelogits_normed, tf.transpose(prelogits_normed), False)
dist_mat_batch = tf.matmul(prelogits_normed, tf.transpose(prelogits_normed))
dist_pos_batch = tf.boolean_mask(dist_mat_batch, label_mask_pos_batch)
dist_neg_batch = tf.boolean_mask(dist_mat_batch, label_mask_neg_batch)
logits_batch = coef * dist_mat_batch
logits_pos_batch = tf.boolean_mask(logits_batch, label_mask_pos_batch)
logits_neg_batch = tf.boolean_mask(logits_batch, label_mask_neg_batch)
# num_anchor = 32
# prelogits_anchor = tf.reshape(prelogits_normed[:num_anchor], [num_anchor, 1, nrof_features])
# prelogits_refer = tf.reshape(prelogits_normed[num_anchor:], [num_anchor, -1, nrof_features])
# dist_anchor = tf.reduce_sum(tf.square(prelogits_anchor-prelogits_refer), axis=2)
# dist_anchor = tf.reshape(dist_anchor, [-1])
# logits_anchor = -0.5 * gamma * dist_anchor
logits_pos = logits_pos_glob
logits_neg = logits_neg_glob
dist_pos = dist_pos_glob
dist_neg = dist_neg_glob
# epsilon_trsd = 0.3
t_pos = coef * (threshold_pos)
t_neg = coef * (threshold_neg)
if gamma == 'auto':
# gamma = tf.nn.softplus(alpha)
gamma = tf.log(tf.exp(1.0) + tf.exp(alpha))
elif type(gamma) == tuple:
t_min, decay = gamma
epsilon = 1e-5
t = t_min + 1.0/(epsilon + decay*tf.cast(global_step, tf.float32))
gamma = 1.0 / t
else:
assert type(gamma) == float
gamma = tf.constant(gamma)
hinge_loss = lambda x: tf.nn.relu(1.0 + x)
margin_func = hinge_loss
# Losses
losses = []
# num_pos = tf.cast(0.95 * tf.cast(tf.size(logits_pos), tf.float32), tf.int32)
# # num_neg = tf.cast(0.75 * tf.cast(tf.size(logits_neg), tf.float32), tf.int32)
# q_d = tf.pow(tf.sqrt(dist_neg), 2-nrof_features)*tf.pow(1-0.25*dist_neg, (3-nrof_features)/2)
# tf.add_to_collection('watch_list', ('q_d', tf.reduce_sum(q_d)))
# q_d = tf.minimum(1.0, 1 * q_d / tf.reduce_sum(q_d))
# tf.add_to_collection('watch_list', ('q_d', tf.reduce_mean(q_d)))
# sample_mask = tf.random_uniform(shape=tf.shape(logits_neg)) <= q_d
# sample_mask = logits_neg >= tf.reduce_min(logits_pos)
# _logits_neg = tf.boolean_mask(logits_neg, sample_mask)
# tf.add_to_collection('watch_list', ('sample_ratio',
# tf.cast(tf.size(_logits_neg),tf.float32) / tf.cast(tf.size(logits_neg),tf.float32)))
# gamma2 = 1 / 0.01
_logits_pos = tf.reshape(logits_pos, [batch_size, -1])
_logits_neg = tf.reshape(logits_neg, [batch_size, -1])
norm = tf.square(tf.reduce_sum(tf.square(prelogits), axis=1, keep_dims=True))
norm_weights = tf.norm(tf.gather(weights, label), axis=1, keep_dims=True)
t_pos = (beta)
t_neg = (beta)
_logits_pos = _logits_pos * gamma
_logits_neg = _logits_neg * gamma
# _logits_neg, _ = tf.nn.top_k(_logits_neg, num_neg)
# _logits_pos, _ = tf.nn.top_k(_logits_pos, num_pos)
# _logits_neg = tf.boolean_mask(_logits_neg, sample_mask)
# _logits_pos = -tf.reduce_logsumexp(-_logits_pos)# , axis=1)[:,None]
_logits_neg = tf.reduce_logsumexp(_logits_neg, axis=1)[:,None]
# _logits_pos = tf.reduce_mean(_logits_pos)
#-- Simulate Ranking
# se_neg = tf.reduce_sum(tf.exp(_logits_neg))
# min_pos = tf.reduce_min(_logits_pos)
# t_pos = tf.stop_gradient(tf.log(se_neg))
# t_neg = tf.stop_gradient(tf.log(se_neg - tf.exp(_logits_neg)))
# norm = tf.reshape(prelogits[:,-1], [batch_size, -1])
# norm_weighted = tf.exp(-norm)
# norm_weighted = norm / tf.reduce_sum(norm) * tf.cast(tf.size(norm), tf.float32)
# sigma_batch = tf.reshape(tf.gather(sigma, label), [batch_size, -1])
m = 5.0
# tf.add_to_collection('watch_list', ('m',m))
factor = 1 / tf.cast(batch_size, tf.float32)
bias = tf.log(tf.cast(num_classes, tf.float32))
loss_pos = tf.nn.relu(m + _logits_neg - _logits_pos) * 0.5
loss_neg = tf.nn.relu(m + _logits_neg - _logits_pos) * 0.5
loss = tf.reduce_mean((loss_pos + loss_neg), name='split_loss')
losses.extend([loss])
tf.add_to_collection('watch_list', ('split_loss', loss))
# Global loss
# weights_batch = tf.gather(weights_normed, label)
# _logits_pos_glob = tf.reduce_sum(tf.square(prelogits_normed - weights_batch), axis=1) * coef * gamma
_logits_pos_glob = tf.reshape(logits_pos_glob, [batch_size, -1]) * gamma
_logits_neg_glob = tf.reshape(logits_neg_glob, [batch_size, -1]) * gamma
_logits_neg_glob = tf.reduce_logsumexp(_logits_neg_glob) # , axis=1)[:,None]
loss_glob = tf.reduce_mean(tf.nn.relu(1 + _logits_neg_glob - _logits_pos_glob), name='loss_glob')
# losses.append(loss_glob)
# tf.add_to_collection('watch_list', ('loss_glob', loss_glob))
# Weight decay
loss_weight = tf.reduce_sum( 1e-7 * tf.square(weights_normed), name='loss_weight')
# losses.append(loss_weight)
# tf.add_to_collection('watch_list', ('loss_weight', loss_weight))
# Split Softmax
# _logits_pos_glob = tf.reshape(logits_pos_glob, [batch_size, -1]) * gamma
# _logits_neg_glob = tf.reshape(logits_neg_glob, [batch_size, -1]) * gamma
# _logits_pos_glob = tf.log(tf.reduce_sum(tf.exp(_logits_pos_glob) + num_classes-1, axis=1)[:,None])
# _logits_neg_glob = tf.reduce_logsumexp(_logits_neg_glob, axis=1)[:,None]
# _t_pos = t_pos * gamma
# _t_neg = t_neg * gamma
# loss_pos = tf.reduce_mean(tf.nn.softplus(_t_pos - _logits_pos_glob), name='loss_pos')
# loss_neg = tf.reduce_mean(tf.nn.softplus(_logits_neg_glob - _t_neg), name='loss_neg')
# losses.extend([loss_pos, loss_neg])
# Batch Center loss
# centers_batch = tf.gather(centers, center_idx)
centers_batch = tf.gather(weights_normed, label)
dist_center = tf.reduce_sum(tf.square(prelogits_normed - centers_batch), axis=1)
loss_center = tf.reduce_mean(1.0*dist_center, name='loss_center')
# losses.append(loss_center)
# tf.add_to_collection('watch_list', ('loss_center', loss_center))
# Update threshold
if not threshold_pos in tf.trainable_variables():
# -- Mean threshold
mean_pos, var_pos = tf.nn.moments(dist_pos, axes=[0])
mean_neg, var_neg = tf.nn.moments(dist_neg, axes=[0])
std_pos = tf.sqrt(var_pos)
std_neg = tf.sqrt(var_neg)
threshold_batch = std_neg*mean_pos / (std_pos+std_neg) + std_pos*mean_neg / (std_pos+std_neg)
threshold_pos_batch = threshold_neg_batch = threshold_batch
# -- Logits
# threshold_pos_batch = tf.reduce_logsumexp(_logits_neg)
# threshold_neg_batch = -tf.reduce_logsumexp(-_logits_pos)
# -- Quantile
# diff_pos_sorted, _ = tf.nn.top_k(logits_pos, 2)
# diff_neg_sorted, _ = tf.nn.top_k(logits_neg, 2704237)
# threshold_pos_batch = diff_neg_sorted[-1]
# threshold_neg_batch = diff_pos_sorted[-1]
threshold_neg_batch = tf.reduce_min(_logits_pos)
threshold_pos_batch = tf.reduce_max(_logits_neg)
# -- Update
diff_threshold_pos = threshold_pos - threshold_pos_batch
diff_threshold_neg = threshold_neg - threshold_neg_batch
diff_threshold_pos = 0.1 * diff_threshold_pos
diff_threshold_neg = 0.1 * diff_threshold_neg
threshold_pos_update_op = tf.assign_sub(threshold_pos, diff_threshold_pos)
threshold_neg_update_op = tf.assign_sub(threshold_neg, diff_threshold_neg)
threshold_update_op = tf.group(threshold_pos_update_op, threshold_neg_update_op)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, threshold_update_op)
# Update centers
if not weights in tf.trainable_variables():
weights_batch = tf.gather(weights, label)
diff_centers = weights_batch - prelogits
unique_label, unique_idx, unique_count = tf.unique_with_counts(label)
appear_times = tf.gather(unique_count, unique_idx)
appear_times = tf.reshape(appear_times, [-1, 1])
diff_centers = diff_centers / tf.cast((1 + appear_times), tf.float32)
diff_centers = 0.5 * diff_centers
centers_update_op = tf.scatter_sub(weights, label, diff_centers)
# centers_decay_op = tf.assign_sub(weights, 2*weight_decay*weights)# weight decay
centers_update_op = tf.group(centers_update_op)
tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, centers_update_op)
# if not sigma in tf.trainable_variables():
# weights_batch = tf.gather(weights, label)
# diff_centers = weights_batch - prelogits
# _, var_pos = tf.nn.moments(diff_centers, axes=[0])
# sigma_batch = tf.reduce_mean(tf.sqrt(var_pos))
# diff_sigma = sigma - sigma_batch
# diff_sigma = 0.01 * diff_sigma
# sigma_update_op = tf.assign_sub(sigma, diff_sigma)
# tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, sigma_update_op)
# Analysis
mean_dist_pos = tf.reduce_mean(dist_pos, name='mean_dist_pos')
mean_dist_neg = tf.reduce_mean(dist_neg, name='mean_dist_neg')
acc_pos = tf.reduce_mean(tf.cast(tf.greater_equal(logits_pos, t_pos), tf.float32), name='acc_pos')
acc_neg = tf.reduce_mean(tf.cast(tf.less(logits_neg, t_neg), tf.float32), name='acc_neg')
tf.summary.scalar('threshold_pos', threshold_pos)
tf.summary.scalar('mean_dist_pos', mean_dist_pos)
tf.summary.scalar('mean_dist_neg', mean_dist_neg)
tf.summary.scalar('acc_pos', acc_pos)
tf.summary.scalar('acc_neg', acc_neg)
tf.summary.scalar('gamma', gamma)
tf.summary.scalar('alpha', alpha)
tf.summary.scalar('beta', beta)
tf.summary.histogram('dist_pos', dist_pos)
tf.summary.histogram('dist_neg', dist_neg)
# tf.summary.histogram('dist_neg_min', _logits_neg / coef)
# tf.summary.histogram('sigma', sigma)
# tf.add_to_collection('watch_list', ('alpha', alpha))
tf.add_to_collection('watch_list', ('gamma', gamma))
tf.add_to_collection('watch_list', ('alpha', alpha))
tf.add_to_collection('watch_list', ('beta', beta))
# tf.add_to_collection('watch_list', ('t_pos', t_pos))
# tf.add_to_collection('watch_list', ('t_neg', tf.reduce_mean(t_neg)))
# tf.add_to_collection('watch_list', ('dpos', mean_dist_pos))
# tf.add_to_collection('watch_list', ('dneg', mean_dist_neg))
# tf.add_to_collection('watch_list', ('loss_pos', loss_pos))
# tf.add_to_collection('watch_list', ('loss_neg', loss_neg))
# tf.add_to_collection('watch_list', ('sigma', sigma))
# tf.add_to_collection('watch_list', ('logits_pos', tf.reduce_mean(_logits_pos)))
# tf.add_to_collection('watch_list', ('logits_neg', tf.reduce_mean(_logits_neg)))
# tf.add_to_collection('watch_list', ('acc_pos', acc_pos))
# tf.add_to_collection('watch_list', ('acc_neg', acc_neg))
return losses
def centers_by_label(features, label):
# Compute centers within batch
unique_label, unique_idx, unique_count = tf.unique_with_counts(label)
num_centers = tf.size(unique_label)
appear_times = tf.gather(unique_count, unique_idx)
appear_times = tf.reshape(appear_times, [-1, 1])
weighted_prelogits = features / tf.cast(appear_times, tf.float32)
centers = tf.unsorted_segment_sum(weighted_prelogits, unique_idx, num_centers)
return centers, unique_label, unique_idx, unique_count
def cluster_loss(prelogits, label, num_classes,
weight_decay, gamma=16.0, reuse=None):
embedding_size = prelogits.shape[1].value
batch_size = tf.shape(prelogits)[0]
with tf.variable_scope('ClusterLoss', reuse=reuse):
alpha = tf.get_variable('alpha', shape=(),
# regularizer=slim.l2_regularizer(weight_decay),
initializer=tf.constant_initializer(1.0),
trainable=True,
dtype=tf.float32)
gamma = gamma
prelogits = tf.nn.l2_normalize(prelogits, dim=1)
centers, label_center, center_idx, center_weight = centers_by_label(prelogits, label)
centers = tf.nn.l2_normalize(centers, dim=1)
num_centers = tf.size(label_center)
# Compute distance between centers
dist_centers_mat = euclidean_distance(centers, tf.transpose(centers))
mask_non_diag = tf.logical_not(tf.cast(tf.eye(num_centers), tf.bool))
mask_triu = tf.cast(tf.matrix_band_part(tf.ones((num_centers, num_centers)), 0, -1), tf.bool)
mask_triu = tf.logical_and(mask_non_diag, mask_triu)
dist_centers_vec = tf.boolean_mask(dist_centers_mat, mask_triu)
# Compute distance between instance and ceners
centers_batch = tf.gather(centers, center_idx)
dist_instance = euclidean_distance(prelogits, tf.transpose(centers))
label_dense = tf.one_hot(center_idx, num_centers, dtype=tf.float32)
label_pos = tf.cast(label_dense, tf.bool)
label_neg = tf.logical_not(label_pos)
dist_instance_pos = tf.boolean_mask(dist_instance, label_pos)
dist_instance_neg = tf.boolean_mask(dist_instance, label_neg)
# Losses
alpha = 1.0
gamma = 20.0
dist_instance_pos = tf.reshape(dist_instance_pos, [batch_size, -1])
dist_instance_neg = tf.reshape(dist_instance_neg, [batch_size, -1])
logits_pos = - 0.5 * 2 * dist_instance_pos * gamma
logits_neg = - 0.5 * dist_centers_vec * gamma
# logits_pos = tf.reduce_mean(logits_pos)
logits_neg = tf.reduce_logsumexp(logits_neg)#, axis=1)[:,None]
# min_dist_centers = -tf.reduce_logsumexp(-dist_centers_vec)
# loss_instance = tf.identity(alpha*dist_instance_pos - min_dist_centers)
loss_instance = tf.reduce_mean(tf.nn.softplus(logits_neg - logits_pos))
losses = [loss_instance]
# Analysis
tf.summary.histogram('prelogits', prelogits)
# tf.summary.scalar('min_dist_centers', min_dist_centers)
# tf.summary.histogram('min_dist_centers', min_dist_centers)
tf.summary.histogram('dist_centers_vec', dist_centers_vec)
tf.summary.histogram('dist_instances_pos', dist_instance_pos)
# tf.add_to_collection('watch_list', ('dcenters', min_dist_centers))
tf.add_to_collection('watch_list', ('loss', loss_instance))
# tf.add_to_collection('watch_list', ('alpha', alpha))
return losses
def binary_loss(prelogits, label, num_classes,
weight_decay, gamma=16.0, reuse=None):
nrof_features = prelogits.shape[1].value
batch_size = tf.shape(prelogits)[0]
with tf.variable_scope('BinaryLoss', reuse=reuse):
weights = tf.get_variable('weights', shape=(num_classes, nrof_features),
# regularizer=slim.l2_regularizer(weight_decay),
initializer=tf.truncated_normal_initializer(stddev=1.0),
# initializer=tf.constant_initializer(1.0),
trainable=True,
dtype=tf.float32)
weights_normed = tf.nn.sigmoid(weights)
prelogits_normed = prelogits
weights_batch = tf.gather(weights_normed, label)
closs = tf.nn.sigmoid_cross_entropy_with_logits(logits=prelogits_normed, labels=weights_batch)
closs = tf.reduce_sum(closs, axis=1)
closs = tf.reduce_mean(closs, name='cross_entropy')
p_pos = tf.reduce_mean(weights_normed, axis=0)
p_neg = tf.reduce_mean(1-weights_normed, axis=0)
eloss = (p_pos * tf.log(p_pos) + p_neg * tf.log(p_neg))
eloss = tf.reduce_sum(eloss, name='entropy')
losses = [closs, eloss]
tf.add_to_collection('watch_list', ('closs', closs))
tf.add_to_collection('watch_list', ('eloss', eloss))
return losses
| 46.375494
| 111
| 0.654791
|
4a0a5fc37d030967265068a15669bb31fec835c8
| 37,800
|
py
|
Python
|
pyfcm/fcm.py
|
belegnar/PyFCM
|
f33765a107191057c796cf829661a8c9933218f2
|
[
"MIT"
] | null | null | null |
pyfcm/fcm.py
|
belegnar/PyFCM
|
f33765a107191057c796cf829661a8c9933218f2
|
[
"MIT"
] | null | null | null |
pyfcm/fcm.py
|
belegnar/PyFCM
|
f33765a107191057c796cf829661a8c9933218f2
|
[
"MIT"
] | null | null | null |
from .baseapi import BaseAPI
from .errors import InvalidDataError
class FCMNotification(BaseAPI):
def notify_single_device(self,
registration_id=None,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
click_action=None,
badge=None,
color=None,
tag=None,
body_loc_key=None,
body_loc_args=None,
title_loc_key=None,
title_loc_args=None,
content_available=None,
android_channel_id=None,
timeout=5,
extra_notification_kwargs=None,
extra_kwargs=None):
"""
Send push notification to a single device
Args:
registration_id (list, optional): FCM device registration ID
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to display in the notification tray
message_icon (str, optional): Icon that apperas next to the notification
sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
click_action (str, optional): Action associated with a user click on the notification
badge (str, optional): Badge of notification
color (str, optional): Color of the icon
tag (str, optional): Group notification by tag
body_loc_key (str, optional): Indicates the key to the body string for localization
body_loc_args (list, optional): Indicates the string value to replace format
specifiers in body string for localization
title_loc_key (str, optional): Indicates the key to the title string for localization
title_loc_args (list, optional): Indicates the string value to replace format
specifiers in title string for localization
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: Mostly from changes in the response of FCM,
contact the project owner to resolve the issue
"""
if registration_id is None:
raise InvalidDataError('Invalid registration ID')
# [registration_id] cos we're sending to a single device
payload = self.parse_payload(
registration_ids=[registration_id],
message_body=message_body,
message_title=message_title,
message_icon=message_icon,
sound=sound,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run, data_message=data_message, click_action=click_action,
badge=badge,
color=color,
tag=tag,
body_loc_key=body_loc_key,
body_loc_args=body_loc_args,
title_loc_key=title_loc_key,
title_loc_args=title_loc_args,
android_channel_id=android_channel_id,
content_available=content_available,
extra_notification_kwargs=extra_notification_kwargs,
**(extra_kwargs or {})
)
self.send_request([payload], timeout)
return self.parse_responses()
async def anotify_single_device(self,
registration_id=None,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
click_action=None,
badge=None,
color=None,
tag=None,
body_loc_key=None,
body_loc_args=None,
title_loc_key=None,
title_loc_args=None,
content_available=None,
android_channel_id=None,
timeout=5,
extra_notification_kwargs=None,
extra_kwargs=None):
"""
Send push notification to a single device
Args:
registration_id (list, optional): FCM device registration ID
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to display in the notification tray
message_icon (str, optional): Icon that apperas next to the notification
sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
click_action (str, optional): Action associated with a user click on the notification
badge (str, optional): Badge of notification
color (str, optional): Color of the icon
tag (str, optional): Group notification by tag
body_loc_key (str, optional): Indicates the key to the body string for localization
body_loc_args (list, optional): Indicates the string value to replace format
specifiers in body string for localization
title_loc_key (str, optional): Indicates the key to the title string for localization
title_loc_args (list, optional): Indicates the string value to replace format
specifiers in title string for localization
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: Mostly from changes in the response of FCM,
contact the project owner to resolve the issue
"""
if registration_id is None:
raise InvalidDataError('Invalid registration ID')
# [registration_id] cos we're sending to a single device
payload = self.parse_payload(
registration_ids=[registration_id],
message_body=message_body,
message_title=message_title,
message_icon=message_icon,
sound=sound,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run, data_message=data_message, click_action=click_action,
badge=badge,
color=color,
tag=tag,
body_loc_key=body_loc_key,
body_loc_args=body_loc_args,
title_loc_key=title_loc_key,
title_loc_args=title_loc_args,
android_channel_id=android_channel_id,
content_available=content_available,
extra_notification_kwargs=extra_notification_kwargs,
**(extra_kwargs or {})
)
await self.asend_request([payload], timeout)
result = await self.aparse_responses()
return result
def single_device_data_message(self,
registration_id=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
content_available=None,
android_channel_id=None,
timeout=5,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Send push message to a single device
Args:
registration_id (list, optional): FCM device registration ID
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: Mostly from changes in the response of FCM,
contact the project owner to resolve the issue
"""
if registration_id is None:
raise InvalidDataError('Invalid registration ID')
# [registration_id] cos we're sending to a single device
payload = self.parse_payload(
registration_ids=[registration_id],
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run,
data_message=data_message,
content_available=content_available,
remove_notification=True,
android_channel_id=android_channel_id,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs
)
self.send_request([payload], timeout)
return self.parse_responses()
def notify_multiple_devices(self,
registration_ids=None,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
click_action=None,
badge=None,
color=None,
tag=None,
body_loc_key=None,
body_loc_args=None,
title_loc_key=None,
title_loc_args=None,
content_available=None,
android_channel_id=None,
timeout=5,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends push notification to multiple devices, can send to over 1000 devices
Args:
registration_ids (list, optional): FCM device registration IDs
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to display in the notification tray
message_icon (str, optional): Icon that apperas next to the notification
sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
click_action (str, optional): Action associated with a user click on the notification
badge (str, optional): Badge of notification
color (str, optional): Color of the icon
tag (str, optional): Group notification by tag
body_loc_key (str, optional): Indicates the key to the body string for localization
body_loc_args (list, optional): Indicates the string value to replace format
specifiers in body string for localization
title_loc_key (str, optional): Indicates the key to the title string for localization
title_loc_args (list, optional): Indicates the string value to replace format
specifiers in title string for localization
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM,
create a new github issue to resolve it.
"""
if not isinstance(registration_ids, list):
raise InvalidDataError('Invalid registration IDs (should be list)')
payloads = []
registration_id_chunks = self.registration_id_chunks(registration_ids)
for registration_ids in registration_id_chunks:
# appends a payload with a chunk of registration ids here
payloads.append(self.parse_payload(
registration_ids=registration_ids,
message_body=message_body,
message_title=message_title,
message_icon=message_icon,
sound=sound,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run, data_message=data_message,
click_action=click_action,
badge=badge,
color=color,
tag=tag,
body_loc_key=body_loc_key,
body_loc_args=body_loc_args,
title_loc_key=title_loc_key,
title_loc_args=title_loc_args,
content_available=content_available,
android_channel_id=android_channel_id,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs
))
self.send_request(payloads, timeout)
return self.parse_responses()
def multiple_devices_data_message(self,
registration_ids=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
content_available=None,
timeout=5,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends push message to multiple devices, can send to over 1000 devices
Args:
registration_ids (list, optional): FCM device registration IDs
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
content_available (bool, optional): Inactive client app is awoken
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM,
create a new github issue to resolve it.
"""
if not isinstance(registration_ids, list):
raise InvalidDataError('Invalid registration IDs (should be list)')
payloads = []
registration_id_chunks = self.registration_id_chunks(registration_ids)
for registration_ids in registration_id_chunks:
# appends a payload with a chunk of registration ids here
payloads.append(self.parse_payload(
registration_ids=registration_ids,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run,
data_message=data_message,
content_available=content_available,
remove_notification=True,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs)
)
self.send_request(payloads, timeout)
return self.parse_responses()
def notify_topic_subscribers(self,
topic_name=None,
message_body=None,
message_title=None,
message_icon=None,
sound=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
click_action=None,
badge=None,
color=None,
tag=None,
body_loc_key=None,
body_loc_args=None,
title_loc_key=None,
title_loc_args=None,
content_available=None,
android_channel_id=None,
timeout=5,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends push notification to multiple devices subscribed to a topic
Args:
topic_name (str, optional): Name of the topic to deliver messages to
message_body (str, optional): Message string to display in the notification tray
message_title (str, optional): Message title to display in the notification tray
message_icon (str, optional): Icon that apperas next to the notification
sound (str, optional): The sound file name to play. Specify "Default" for device default sound.
condition (str, optiona): Topic condition to deliver messages to
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to `None`.
delay_while_idle (bool, optional): deprecated
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to `None`
which uses the FCM default of 4 weeks.
restricted_package_name (str, optional): Name of package
low_priority (bool, optional): Whether to send notification with
the low priority flag. Defaults to `False`.
dry_run (bool, optional): If `True` no message will be sent but request will be tested.
data_message (dict, optional): Custom key-value pairs
click_action (str, optional): Action associated with a user click on the notification
badge (str, optional): Badge of notification
color (str, optional): Color of the icon
tag (str, optional): Group notification by tag
body_loc_key (str, optional): Indicates the key to the body string for localization
body_loc_args (list, optional): Indicates the string value to replace format
specifiers in body string for localization
title_loc_key (str, optional): Indicates the key to the title string for localization
title_loc_args (list, optional): Indicates the string value to replace format
specifiers in title string for localization
content_available (bool, optional): Inactive client app is awoken
android_channel_id (str, optional): Starting in Android 8.0 (API level 26),
all notifications must be assigned to a channel. For each channel, you can set the
visual and auditory behavior that is applied to all notifications in that channel.
Then, users can change these settings and decide which notification channels from
your app should be intrusive or visible at all.
timeout (int, optional): set time limit for the request
extra_notification_kwargs (dict, optional): More notification keyword arguments
extra_kwargs (dict, optional): More keyword arguments
Returns:
dict: Response from FCM server (`multicast_id`, `success`, `failure`, `canonical_ids`, `results`)
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided
or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM,
create a new github issue to resolve it.
"""
payload = self.parse_payload(
topic_name=topic_name,
condition=condition,
message_body=message_body,
message_title=message_title,
message_icon=message_icon,
sound=sound,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run, data_message=data_message, click_action=click_action,
badge=badge,
color=color,
tag=tag,
body_loc_key=body_loc_key,
body_loc_args=body_loc_args,
title_loc_key=title_loc_key,
title_loc_args=title_loc_args,
content_available=content_available,
android_channel_id=android_channel_id,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs
)
self.send_request([payload], timeout)
return self.parse_responses()
def topic_subscribers_data_message(self,
topic_name=None,
condition=None,
collapse_key=None,
delay_while_idle=False,
time_to_live=None,
restricted_package_name=None,
low_priority=False,
dry_run=False,
data_message=None,
content_available=None,
timeout=5,
extra_notification_kwargs=None,
extra_kwargs={}):
"""
Sends data notification to multiple devices subscribed to a topic
Args:
topic_name (topic_name): Name of the topic to deliver messages to
condition (condition): Topic condition to deliver messages to
A topic name is a string that can be formed with any character in [a-zA-Z0-9-_.~%]
data_message (dict): Data message payload to send alone or with the notification message
Keyword Args:
collapse_key (str, optional): Identifier for a group of messages
that can be collapsed so that only the last message gets sent
when delivery can be resumed. Defaults to ``None``.
delay_while_idle (bool, optional): If ``True`` indicates that the
message should not be sent until the device becomes active.
time_to_live (int, optional): How long (in seconds) the message
should be kept in FCM storage if the device is offline. The
maximum time to live supported is 4 weeks. Defaults to ``None``
which uses the FCM default of 4 weeks.
low_priority (boolean, optional): Whether to send notification with
the low priority flag. Defaults to ``False``.
restricted_package_name (str, optional): Package name of the
application where the registration IDs must match in order to
receive the message. Defaults to ``None``.
dry_run (bool, optional): If ``True`` no message will be sent but
request will be tested.
Returns:
:tuple:`multicast_id(long), success(int), failure(int), canonical_ids(int), results(list)`:
Response from FCM server.
Raises:
AuthenticationError: If :attr:`api_key` is not set or provided or there is an error authenticating the sender.
FCMServerError: Internal server error or timeout error on Firebase cloud messaging server
InvalidDataError: Invalid data provided
InternalPackageError: JSON parsing error, mostly from changes in the response of FCM, create a new github issue to resolve it.
"""
if extra_kwargs is None:
extra_kwargs = {}
payload = self.parse_payload(topic_name=topic_name,
condition=condition,
collapse_key=collapse_key,
delay_while_idle=delay_while_idle,
time_to_live=time_to_live,
restricted_package_name=restricted_package_name,
low_priority=low_priority,
dry_run=dry_run,
data_message=data_message,
content_available=content_available,
remove_notification=True,
extra_notification_kwargs=extra_notification_kwargs,
**extra_kwargs)
self.send_request([payload], timeout)
return self.parse_responses()
| 55.752212
| 138
| 0.574206
|
4a0a61ce0916932d74b1dc6e384a4da3983ecff6
| 1,565
|
py
|
Python
|
opsmop/facts/chaos.py
|
lachmanfrantisek/opsmop
|
562ae2d753ff84b3d794a6815d0436753e82d2a0
|
[
"Apache-2.0"
] | null | null | null |
opsmop/facts/chaos.py
|
lachmanfrantisek/opsmop
|
562ae2d753ff84b3d794a6815d0436753e82d2a0
|
[
"Apache-2.0"
] | null | null | null |
opsmop/facts/chaos.py
|
lachmanfrantisek/opsmop
|
562ae2d753ff84b3d794a6815d0436753e82d2a0
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 Michael DeHaan LLC, <michael@michaeldehaan.net>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
import platform
from opsmop.core.common import memoize
from opsmop.facts.facts import Facts
import random as prandom
prandom.seed()
# TODO: there are a LOT of facts to add yet! We are just starting out
# contributions are very welcome
class ChaosFacts(Facts):
"""
As this evolves, facts can be dynamically injected into this base class based on platform, allowing a subclass
for things like LinuxFacts. When this happens, we can have a "facts/" package.
"""
def random(self):
return prandom.random()
def choice(self, args):
return prandom.choice(*args)
def constants(self):
"""
This returns all facts that do not take parameters .
Mostly for the DebugFacts() implementation
"""
return dict(
random = self.random(),
)
def invalidate(self):
pass
Chaos = ChaosFacts()
if __name__ == "__main__":
print(Chaos.constants())
| 28.981481
| 114
| 0.697764
|
4a0a62ac8826cfaa6f69e059a19095d63e7099bc
| 2,641
|
py
|
Python
|
Test/main.py
|
OnurBahadir/slm_simulation
|
b0cdc5b120f1f9a428e39071953be76fb4d30ef9
|
[
"MIT"
] | null | null | null |
Test/main.py
|
OnurBahadir/slm_simulation
|
b0cdc5b120f1f9a428e39071953be76fb4d30ef9
|
[
"MIT"
] | null | null | null |
Test/main.py
|
OnurBahadir/slm_simulation
|
b0cdc5b120f1f9a428e39071953be76fb4d30ef9
|
[
"MIT"
] | null | null | null |
import numpy as np
import time
import slmpy
import cv2
from pymba import Vimba, VimbaException
from ccd_vimba import display_frame
slmWaiting = 0.8 #seconds
step = 90 # superpixels length n X n {10,15,20,30,60,120}
phase = 30 # 0 - 255
#concentration points
r1=700
r2=800
c1=700
c2=800
def getIntensity(r1,r2,c1,c2,image):
return 0.299*np.mean(image[r1:r2:,c1:c2:,0]) +0.587*np.mean(image[r1:r2:,c1:c2:,1])+0.114*np.mean(image[r1:r2:,c1:c2:,2])
#SLM initialize
slm = slmpy.SLMdisplay(monitor = 1,isImageLock = True)
col,row = slm.getSize() #return col,row
#col = 1920
#row = 1080
#initialize pattern
#slmPattern=np.random.randint(0,255,(row,col)).astype('uint8')
slmPattern=np.zeros((row,col)).astype('uint8')
#save initial pattern
cv2.imwrite("slm_pattern_initial.jpeg",slmPattern)
#update slm with init pattern
slm.updateArray(slmPattern)
# wait for update
time.sleep(slmWaiting)
#Reading image from CCD
with Vimba() as vimba:
camera = vimba.camera(0)
camera.open()
camera.arm('SingleFrame')
frame = camera.acquire_frame()
ccd_init=display_frame(frame, 0)
cv2.imwrite("ccd_init.jpeg",ccd_init)
camera.disarm()
camera.close()
with Vimba() as vimba:
camera = vimba.camera(0)
camera.open()
camera.arm('SingleFrame')
for r in range(0,row,step):
for c in range(0,col,step):
frame = camera.acquire_frame()
image=display_frame(frame, 0)
intensity=getIntensity(r1, r2, c1, c2,image)
phase_i=slmPattern[r:(r+step):,c:(c+step):]
for ph in range(0,255,phase):
slmPattern[r:(r+step):,c:(c+step):]=ph
slm.updateArray(slmPattern)
time.sleep(slmWaiting)
frame = camera.acquire_frame()
image=display_frame(frame, 0)
intent_temp=getIntensity(r1, r2, c1, c2,image)
if(intent_temp>intensity):
phase_i =ph
intensity=intent_temp
slmPattern[r:(r+step):,c:(c+step):]=phase_i
slm.updateArray(slmPattern)
time.sleep(slmWaiting)
camera.disarm()
camera.close()
cv2.imwrite("slm_pattern_final.jpeg",slmPattern)
time.sleep(2)
with Vimba() as vimba:
camera = vimba.camera(0)
camera.open()
camera.arm('SingleFrame')
frame = camera.acquire_frame()
ccd_final=display_frame(frame, 0)
cv2.imwrite("ccd_final.jpeg",ccd_final)
camera.disarm()
camera.close()
time.sleep(2)
slm.close()
time.sleep(2)
| 22.381356
| 126
| 0.616055
|
4a0a64c15a4e7ee8cb6b44410b279aa61493a0fb
| 1,445
|
py
|
Python
|
htmlparser.py
|
caleber/com.bojin
|
6c162b48dbe20260ffedecfcd348f835561e6ca6
|
[
"MIT"
] | null | null | null |
htmlparser.py
|
caleber/com.bojin
|
6c162b48dbe20260ffedecfcd348f835561e6ca6
|
[
"MIT"
] | null | null | null |
htmlparser.py
|
caleber/com.bojin
|
6c162b48dbe20260ffedecfcd348f835561e6ca6
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'laifuyu'
from html.parser import HTMLParser
from html.entities import name2codepoint
from globalpkg.log import logger
class MyHTMLParser(HTMLParser):
def __init__(self, strict):
super().__init__(strict)
self.start_tag = ''
self.starttag_arrts = []
self.starttag_data = []
def handle_starttag(self, tag, attrs):
logger.debug('Start tag: %s' % tag)
tmp_list = [tag, attrs]
self.start_tag = tag
self.starttag_arrts.append(tmp_list)
def handle_endtag(self, tag):
pass
logger.debug('End tag: %s' % tag)
def handle_data(self, data):
logger.debug('Data %s' % data)
tmp_list = [self.start_tag, data]
self.starttag_data.append(tmp_list)
def handle_comment(self, data):
pass
logger.debug('Comment:%s' % data)
def handle_entityref(self, name):
c = chr(name2codepoint[name])
logger.debug('Named ent:%s' % c)
def handle_charref(self, name):
if name.startswitch('x'):
c = chr(int(name[1:], 16))
else:
c = chr(int(name))
logger.debug('Num ent:%s' % c)
def handle_decl(self, data):
pass
#logger.info('Decl:' % data)
def get_starttag_attrs(self):
return self.starttag_arrts
def get_starttag_data(self):
return self.starttag_data
| 23.306452
| 44
| 0.6
|
4a0a658ad45b6f30093adaaf978d7e9d4b9199e5
| 3,517
|
py
|
Python
|
gui/kivy/uix/dialogs/fee_dialog.py
|
GetAywa/electrum-aywa
|
07a548bd14cdf563da49c1f1e52644b833ca972e
|
[
"MIT"
] | null | null | null |
gui/kivy/uix/dialogs/fee_dialog.py
|
GetAywa/electrum-aywa
|
07a548bd14cdf563da49c1f1e52644b833ca972e
|
[
"MIT"
] | null | null | null |
gui/kivy/uix/dialogs/fee_dialog.py
|
GetAywa/electrum-aywa
|
07a548bd14cdf563da49c1f1e52644b833ca972e
|
[
"MIT"
] | null | null | null |
from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from electrum_dash.util import fee_levels
from electrum_dash_gui.kivy.i18n import _
Builder.load_string('''
<FeeDialog@Popup>
id: popup
title: _('Transaction Fees')
size_hint: 0.8, 0.8
pos_hint: {'top':0.9}
BoxLayout:
orientation: 'vertical'
BoxLayout:
orientation: 'horizontal'
size_hint: 1, 0.5
Label:
id: fee_per_kb
text: ''
Slider:
id: slider
range: 0, 4
step: 1
on_value: root.on_slider(self.value)
BoxLayout:
orientation: 'horizontal'
size_hint: 1, 0.5
Label:
text: _('Dynamic Fees')
CheckBox:
id: dynfees
on_active: root.on_checkbox(self.active)
Widget:
size_hint: 1, 1
BoxLayout:
orientation: 'horizontal'
size_hint: 1, 0.5
Button:
text: 'Cancel'
size_hint: 0.5, None
height: '48dp'
on_release: popup.dismiss()
Button:
text: 'OK'
size_hint: 0.5, None
height: '48dp'
on_release:
root.on_ok()
root.dismiss()
''')
class FeeDialog(Factory.Popup):
def __init__(self, app, config, callback):
Factory.Popup.__init__(self)
self.app = app
self.config = config
self.fee_rate = self.config.fee_per_kb()
self.callback = callback
self.dynfees = self.config.get('dynamic_fees', True)
self.ids.dynfees.active = self.dynfees
self.update_slider()
self.update_text()
def update_text(self):
value = int(self.ids.slider.value)
self.ids.fee_per_kb.text = self.get_fee_text(value)
def update_slider(self):
slider = self.ids.slider
if self.dynfees:
slider.range = (0, 4)
slider.step = 1
slider.value = self.config.get('fee_level', 2)
else:
slider.range = (0, 9)
slider.step = 1
slider.value = self.config.static_fee_index(self.fee_rate)
def get_fee_text(self, value):
if self.ids.dynfees.active:
tooltip = fee_levels[value]
if self.config.has_fee_estimates():
dynfee = self.config.dynfee(value)
tooltip += '\n' + (self.app.format_amount_and_units(dynfee)) + '/kB'
else:
fee_rate = self.config.static_fee(value)
tooltip = self.app.format_amount_and_units(fee_rate) + '/kB'
if self.config.has_fee_estimates():
i = self.config.reverse_dynfee(fee_rate)
tooltip += '\n' + (_('low fee') if i < 0 else 'Within %d blocks'%i)
return tooltip
def on_ok(self):
value = int(self.ids.slider.value)
self.config.set_key('dynamic_fees', self.dynfees, False)
if self.dynfees:
self.config.set_key('fee_level', value, True)
else:
self.config.set_key('fee_per_kb', self.config.static_fee(value), True)
self.callback()
def on_slider(self, value):
self.update_text()
def on_checkbox(self, b):
self.dynfees = b
self.update_slider()
self.update_text()
| 31.123894
| 84
| 0.547057
|
4a0a65d01bacb33530241e638d99183a4fdbf875
| 1,799
|
py
|
Python
|
utils/test_model.py
|
XintianHan/ADV_ECG
|
3b36eb9b5daaf98bee154fb4ce0c62ec3aab8841
|
[
"MIT"
] | 17
|
2020-03-09T17:41:55.000Z
|
2022-02-23T02:49:53.000Z
|
utils/test_model.py
|
XintianHan/ADV_ECG
|
3b36eb9b5daaf98bee154fb4ce0c62ec3aab8841
|
[
"MIT"
] | 1
|
2020-07-29T23:07:23.000Z
|
2021-03-18T01:26:41.000Z
|
utils/test_model.py
|
XintianHan/ADV_ECG
|
3b36eb9b5daaf98bee154fb4ce0c62ec3aab8841
|
[
"MIT"
] | 9
|
2020-03-12T01:35:47.000Z
|
2021-11-28T09:17:24.000Z
|
import numpy as np
import torch
import sys
import global_variables
import torch.nn.functional as F
device = global_variables.device
# Function for testing the model
def test_model(loader, model):
"""
Help function that tests the model's performance on a dataset
@param: loader - data loader for the dataset to test against
"""
correct = 0
total = 0
model.eval()
for data, labels in loader:
data_batch, label_batch = data.to(device), labels.to(device)
outputs = F.softmax(model(data_batch), dim=1)
predicted = outputs.max(1, keepdim=True)[1]
total += label_batch.size(0)
correct += predicted.eq(label_batch.view_as(predicted)).sum().item()
return (100 * correct / total)
# Function for calculating the F1 score
def cal_F1(loader, model):
"""
Help function that tests the model's performance on a dataset
@param: loader - data loader for the dataset to test against
"""
correct = 0
total = 0
model.eval()
cof_mat = np.zeros ((4,4))
Ns = np.zeros(4)
ns = np.zeros(4)
for data, labels in loader:
data_batch, label_batch = data.to(device), labels.to(device)
outputs = F.softmax(model(data_batch), dim=1)
predicted = outputs.max(1, keepdim=True)[1]
total += label_batch.size(0)
correct += predicted.eq(label_batch.view_as(predicted)).sum().item()
acc = label_batch.view_as(predicted)
for (a,p) in zip(acc, predicted):
cof_mat[a][p] += 1
Ns[a] += 1
ns[p] += 1
F1 = 0.0
for i in range(len(Ns)):
tempF = cof_mat[i][i]*2.0 /(Ns[i] + ns[i])
F1 = F1+ tempF
print('F1'+str(i)+':',tempF)
F1 = F1/4.0
print('cofmat',cof_mat)
return 100 * correct / total, F1
| 33.314815
| 76
| 0.617009
|
4a0a66ff62e84c2065c796ede1b98a57140b0cab
| 5,567
|
py
|
Python
|
dvc/remote/hdfs.py
|
vyloy/dvc
|
60c89adeb5dcc293d8661d6aabeb1da6d05466f5
|
[
"Apache-2.0"
] | 1
|
2019-04-16T19:51:03.000Z
|
2019-04-16T19:51:03.000Z
|
dvc/remote/hdfs.py
|
vyloy/dvc
|
60c89adeb5dcc293d8661d6aabeb1da6d05466f5
|
[
"Apache-2.0"
] | null | null | null |
dvc/remote/hdfs.py
|
vyloy/dvc
|
60c89adeb5dcc293d8661d6aabeb1da6d05466f5
|
[
"Apache-2.0"
] | null | null | null |
from __future__ import unicode_literals
import os
import re
import getpass
import posixpath
import logging
from subprocess import Popen, PIPE
from dvc.config import Config
from dvc.remote.base import RemoteBase, RemoteCmdError
from dvc.utils import fix_env, tmp_fname
logger = logging.getLogger(__name__)
class RemoteHDFS(RemoteBase):
scheme = "hdfs"
REGEX = r"^hdfs://((?P<user>.*)@)?.*$"
PARAM_CHECKSUM = "checksum"
def __init__(self, repo, config):
super(RemoteHDFS, self).__init__(repo, config)
self.url = config.get(Config.SECTION_REMOTE_URL, "/")
self.prefix = self.url
self.user = self.group("user")
if not self.user:
self.user = config.get(
Config.SECTION_REMOTE_USER, getpass.getuser()
)
self.path_info = {"scheme": "hdfs", "user": self.user}
def hadoop_fs(self, cmd, user=None):
cmd = "hadoop fs -" + cmd
if user:
cmd = "HADOOP_USER_NAME={} ".format(user) + cmd
# NOTE: close_fds doesn't work with redirected stdin/stdout/stderr.
# See https://github.com/iterative/dvc/issues/1197.
close_fds = os.name != "nt"
executable = os.getenv("SHELL") if os.name != "nt" else None
p = Popen(
cmd,
shell=True,
close_fds=close_fds,
executable=executable,
env=fix_env(os.environ),
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
)
out, err = p.communicate()
if p.returncode != 0:
raise RemoteCmdError(self.scheme, cmd, p.returncode, err)
return out.decode("utf-8")
@staticmethod
def _group(regex, s, gname):
match = re.match(regex, s)
assert match is not None
return match.group(gname)
def checksum(self, path_info):
regex = r".*\t.*\t(?P<checksum>.*)"
stdout = self.hadoop_fs(
"checksum {}".format(path_info["path"]), user=path_info["user"]
)
return self._group(regex, stdout, "checksum")
def copy(self, from_info, to_info):
dname = posixpath.dirname(to_info["path"])
self.hadoop_fs("mkdir -p {}".format(dname), user=to_info["user"])
self.hadoop_fs(
"cp -f {} {}".format(from_info["path"], to_info["path"]),
user=to_info["user"],
)
def rm(self, path_info):
self.hadoop_fs(
"rm -f {}".format(path_info["path"]), user=path_info["user"]
)
def save_info(self, path_info):
if path_info["scheme"] != "hdfs":
raise NotImplementedError
assert path_info.get("path")
return {self.PARAM_CHECKSUM: self.checksum(path_info)}
def remove(self, path_info):
if path_info["scheme"] != "hdfs":
raise NotImplementedError
assert path_info.get("path")
logger.debug("Removing {}".format(path_info["path"]))
self.rm(path_info)
def exists(self, path_info):
assert not isinstance(path_info, list)
assert path_info["scheme"] == "hdfs"
try:
self.hadoop_fs("test -e {}".format(path_info["path"]))
return True
except RemoteCmdError:
return False
def upload(self, from_infos, to_infos, names=None):
names = self._verify_path_args(to_infos, from_infos, names)
for from_info, to_info, name in zip(from_infos, to_infos, names):
if to_info["scheme"] != "hdfs":
raise NotImplementedError
if from_info["scheme"] != "local":
raise NotImplementedError
self.hadoop_fs(
"mkdir -p {}".format(posixpath.dirname(to_info["path"])),
user=to_info["user"],
)
tmp_file = tmp_fname(to_info["path"])
self.hadoop_fs(
"copyFromLocal {} {}".format(from_info["path"], tmp_file),
user=to_info["user"],
)
self.hadoop_fs(
"mv {} {}".format(tmp_file, to_info["path"]),
user=to_info["user"],
)
def download(
self,
from_infos,
to_infos,
no_progress_bar=False,
names=None,
resume=False,
):
names = self._verify_path_args(from_infos, to_infos, names)
for to_info, from_info, name in zip(to_infos, from_infos, names):
if from_info["scheme"] != "hdfs":
raise NotImplementedError
if to_info["scheme"] == "hdfs":
self.copy(from_info, to_info)
continue
if to_info["scheme"] != "local":
raise NotImplementedError
dname = os.path.dirname(to_info["path"])
if not os.path.exists(dname):
os.makedirs(dname)
tmp_file = tmp_fname(to_info["path"])
self.hadoop_fs(
"copyToLocal {} {}".format(from_info["path"], tmp_file),
user=from_info["user"],
)
os.rename(tmp_file, to_info["path"])
def list_cache_paths(self):
try:
self.hadoop_fs("test -e {}".format(self.prefix))
except RemoteCmdError:
return []
stdout = self.hadoop_fs("ls -R {}".format(self.prefix))
lines = stdout.split("\n")
flist = []
for line in lines:
if not line.startswith("-"):
continue
flist.append(line.split()[-1])
return flist
| 29.455026
| 75
| 0.552721
|
4a0a673fc3b79dce3fce060a52e55b55f6dec9f5
| 14,328
|
py
|
Python
|
easyreg/brainstorm.py
|
ebrahimebrahim/easyreg
|
f767e68af8c2f230f45ef8a5219db9d8ff2b17f0
|
[
"Apache-2.0"
] | null | null | null |
easyreg/brainstorm.py
|
ebrahimebrahim/easyreg
|
f767e68af8c2f230f45ef8a5219db9d8ff2b17f0
|
[
"Apache-2.0"
] | null | null | null |
easyreg/brainstorm.py
|
ebrahimebrahim/easyreg
|
f767e68af8c2f230f45ef8a5219db9d8ff2b17f0
|
[
"Apache-2.0"
] | null | null | null |
"""
Framework described in
Data augmentation using learned transformationsfor one-shot medical image segmentation
http://www.mit.edu/~adalca/files/papers/cvpr2019_brainstorm.pdf
"""
from .net_utils import gen_identity_map
import mermaid.finite_differences as fdt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .net_utils import Bilinear
import pynd.segutils as pynd_segutils
class convBlock(nn.Module):
"""
A convolutional block including conv, BN, nonliear activiation, residual connection
"""
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=1,
bias=True, batchnorm=False, residual=False, max_pool=False, nonlinear=nn.LeakyReLU(0.2)):
"""
:param in_channels:
:param out_channels:
:param kernel_size:
:param stride:
:param padding:
:param bias:
:param batchnorm:
:param residual:
:param nonlinear:
"""
super(convBlock, self).__init__()
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, bias=bias)
self.bn = nn.BatchNorm3d(out_channels) if batchnorm else None
self.nonlinear = nonlinear
self.residual = residual
self.max_pool = nn.MaxPool3d(kernel_size=(2,2,2),stride=2) if max_pool else None
def forward(self, x):
x= self.conv(x)
if self.bn:
x = self.bn(x)
if self.nonlinear:
x = self.nonlinear(x)
if self.residual:
x += x
if not self.max_pool:
return x
else:
y= self.max_pool(x)
return x, y
class TransformCVPR2019(nn.Module):
"""
unet architecture for voxelmorph models presented in the CVPR 2018 paper.
You may need to modify this code (e.g., number of layers) to suit your project needs.
:param vol_size: volume size. e.g. (256, 256, 256)
:param enc_nf: list of encoder filters. right now it needs to be 1x4.
e.g. [16,32,32,32]
:param dec_nf: list of decoder filters. right now it must be 1x6 (like voxelmorph-1) or 1x7 (voxelmorph-2)
:return: the keras reg_model
"""
def __init__(self, img_sz, opt=None):
super(TransformCVPR2019, self).__init__()
self.is_train = opt['tsk_set'][('train',False,'if is in train mode')]
opt_voxelmorph = opt['tsk_set']['reg']['aug_trans_net']
self.initial_reg_factor = opt_voxelmorph[('initial_reg_factor', 1., 'initial regularization factor')]
enc_filters = [16, 32, 32, 32 ]
dec_filters = [32, 32, 32, 32, 32, 16, 16]
self.enc_filter = enc_filters
self.dec_filter = dec_filters
input_channel =2
output_channel= 3
self.input_channel = input_channel
self.output_channel = output_channel
self.img_sz = img_sz
self.spacing = 1. / ( np.array(img_sz) - 1)
self.loss_fn = None #NCCLoss()
self.epoch = -1
self.print_count = 0
self.id_transform = gen_identity_map(self.img_sz, 1.0).cuda()
self.encoders = nn.ModuleList()
self.decoders = nn.ModuleList()
self.bilinear = Bilinear(zero_boundary=True)
for i in range(len(enc_filters)):
if i==0:
self.encoders.append(convBlock(input_channel, enc_filters[i], stride=1, max_pool=True, bias=True))
if i>0 and i<len(enc_filters)-1:
self.encoders.append(convBlock(enc_filters[i-1], enc_filters[i], stride=1,max_pool=True, bias=True))
if i ==len(enc_filters)-1:
self.encoders.append(convBlock(enc_filters[i-1], enc_filters[i], stride=1,max_pool=False, bias=True))
self.decoders.append(convBlock(enc_filters[3] + enc_filters[2],dec_filters[0], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[0] + enc_filters[1],dec_filters[1], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[1] + enc_filters[0],dec_filters[2], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[2],dec_filters[3], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[3],dec_filters[4], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[4],dec_filters[5], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[5], dec_filters[6],stride=1, bias=True))
self.final_conv = nn.Conv3d(dec_filters[6], output_channel, kernel_size=3, stride=1, padding=1, bias=True)
self.flow = nn.Conv3d(output_channel, output_channel, kernel_size=3, stride=1, padding=1, bias=True)
def set_loss_fn(self, loss_fn):
""" set loss function"""
self.loss_fn = loss_fn
def set_cur_epoch(self, cur_epoch=-1):
""" set current epoch"""
self.epoch = cur_epoch
def forward(self, source, target):
id_map = self.id_transform.clone()
x_enc_0, x = self.encoders[0](torch.cat((source, target), dim=1))
x_enc_1, x = self.encoders[1](x)
x_enc_2, x = self.encoders[2](x)
x_enc_3 = self.encoders[3](x)
x = F.interpolate(x_enc_3,scale_factor=2)
x = torch.cat((x, x_enc_2),dim=1)
x = self.decoders[0](x)
x = F.interpolate(x, scale_factor=2)
x = torch.cat((x, x_enc_1), dim=1)
x = self.decoders[1](x)
x = F.interpolate(x, scale_factor=2)
x = torch.cat((x, x_enc_0), dim=1)
x = self.decoders[2](x)
x = self.decoders[3](x)
x = self.decoders[4](x)
x = self.decoders[5](x)
x = self.decoders[6](x)
x = self.final_conv(x)
disp_field = self.flow(x)
deform_field = disp_field + id_map
warped_source = self.bilinear(source, deform_field)
self.warped = warped_source
self.target = target
self.disp_field = disp_field
if self.train:
self.print_count += 1
return warped_source, deform_field, disp_field
def get_extra_to_plot(self):
return None, None
def check_if_update_lr(self):
return False, None
def scale_reg_loss(self,sched='l2'):
disp = self.disp_field
fd = fdt.FD_torch(self.spacing*2)
dfx = fd.dXc(disp[:, 0, ...])
dfy = fd.dYc(disp[:, 1, ...])
dfz = fd.dZc(disp[:, 2, ...])
l2 = dfx**2+dfy**2+dfz**2
reg = l2.mean()
return reg
def get_sim_loss(self):
sim_loss = self.loss_fn.get_loss(self.warped,self.target)
sim_loss = sim_loss / self.warped.shape[0]
return sim_loss
def weights_init(self):
for m in self.modules():
classname = m.__class__.__name__
if classname.find('Conv') != -1:
if not m.weight is None:
nn.init.xavier_normal_(m.weight.data)
if not m.bias is None:
m.bias.data.zero_()
def get_loss(self):
reg_factor =self.initial_reg_factor
sim_loss = self.get_sim_loss()
reg_loss = self.scale_reg_loss()
if self.print_count % 10 == 0:
print('current sim loss is{}, current_reg_loss is {}, and reg_factor is {} '.format(sim_loss.item(),
reg_loss.item(),
reg_factor))
return sim_loss+ reg_factor*reg_loss
class AppearanceCVPR2019(nn.Module):
"""
unet architecture for voxelmorph models presented in the CVPR 2018 paper.
You may need to modify this code (e.g., number of layers) to suit your project needs.
:param vol_size: volume size. e.g. (256, 256, 256)
:param enc_nf: list of encoder filters. right now it needs to be 1x4.
e.g. [16,32,32,32]
:param dec_nf: list of decoder filters. right now it must be 1x6 (like voxelmorph-1) or 1x7 (voxelmorph-2)
:return: the keras reg_model
"""
def __init__(self, img_sz, opt=None):
super(AppearanceCVPR2019, self).__init__()
self.is_train = opt['tsk_set'][('train',False,'if is in train mode')]
opt_voxelmorph = opt['tsk_set']['reg']['aug_appear_net']
self.initial_reg_factor = opt_voxelmorph[('initial_reg_factor', 1., 'initial regularization factor')]
self.sim_factor = opt_voxelmorph[('sim_factor', 1., 'initial regularization factor')]
enc_filters = [16, 32, 32, 32, 32, 32]
dec_filters = [64, 64, 32, 32, 32, 16, 16]
self.enc_filter = enc_filters
self.dec_filter = dec_filters
input_channel =2
output_channel= 3
self.input_channel = 2
self.output_channel = 3
self.img_sz = img_sz
self.spacing = 1. / ( np.array(img_sz) - 1)
self.loss_fn = None #NCCLoss()
self.epoch = -1
self.print_count = 0
self.encoders = nn.ModuleList()
self.decoders = nn.ModuleList()
self.bilinear = Bilinear(zero_boundary=True)
for i in range(len(enc_filters)):
if i == 0:
self.encoders.append(convBlock(input_channel, enc_filters[i], stride=1, max_pool=True, bias=True))
if i > 0 and i < len(enc_filters) - 1:
self.encoders.append(convBlock(enc_filters[i - 1], enc_filters[i], stride=1, max_pool=True, bias=True))
if i == len(enc_filters) - 1:
self.encoders.append(convBlock(enc_filters[i - 1], enc_filters[i], stride=1, max_pool=False, bias=True))
self.decoders.append(convBlock(enc_filters[5] + enc_filters[4], dec_filters[0], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[0] + enc_filters[3], dec_filters[1], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[1] + enc_filters[2], dec_filters[2], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[2] + enc_filters[1], dec_filters[3], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[3] + enc_filters[0], dec_filters[4], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[4], dec_filters[5], stride=1, bias=True))
self.decoders.append(convBlock(dec_filters[5], dec_filters[6], stride=1, bias=True))
self.final_conv = nn.Conv3d(dec_filters[6], output_channel, kernel_size=3, stride=1, padding=1, bias=True)
self.color = nn.Conv3d(output_channel, 1, kernel_size=3, stride=1, padding=1, bias=True)
self.mask = None
self.target =None
self.reconst = None
self.delta = None
# identity transform for computing displacement
def set_loss_fn(self, loss_fn):
""" set loss function"""
self.loss_fn = loss_fn
def set_cur_epoch(self, cur_epoch=-1):
""" set current epoch"""
self.epoch = cur_epoch
def forward(self, source, target):
x_enc_0,x = self.encoders[0](torch.cat((source, target), dim=1))
x_enc_1,x = self.encoders[1](x)
x_enc_2,x = self.encoders[2](x)
x_enc_3,x = self.encoders[3](x)
x_enc_4,x = self.encoders[4](x)
x_enc_5 = self.encoders[5](x)
x = F.interpolate(x_enc_5,scale_factor=2)
x = torch.cat((x, x_enc_4),dim=1)
x = self.decoders[0](x)
x = F.interpolate(x,size=x_enc_3.shape[2:])
x = torch.cat((x, x_enc_3), dim=1)
x = self.decoders[1](x)
x = F.interpolate(x, scale_factor=2)
x = torch.cat((x, x_enc_2), dim=1)
x = self.decoders[2](x)
x = F.interpolate(x, scale_factor=2)
x = torch.cat((x, x_enc_1), dim=1)
x = self.decoders[3](x)
x = F.interpolate(x, scale_factor=2)
x = torch.cat((x, x_enc_0), dim=1)
x = self.decoders[4](x)
x = self.decoders[5](x)
x = self.decoders[6](x)
x = self.final_conv(x)
delta = self.color(x)
reconst = source + delta
self.delta = delta
self.reconst = reconst
self.target = target
if self.train:
self.print_count += 1
return reconst,delta,delta
def get_extra_to_plot(self):
return None, None
def check_if_update_lr(self):
return False, None
def get_sim_loss(self):
sim_loss = self.loss_fn.get_loss(self.reconst,self.target)
sim_loss = sim_loss / self.reconst.shape[0]
sim_loss = sim_loss *self.sim_factor
return sim_loss
def weights_init(self):
for m in self.modules():
classname = m.__class__.__name__
if classname.find('Conv') != -1:
if not m.weight is None:
nn.init.xavier_normal_(m.weight.data)
if not m.bias is None:
m.bias.data.zero_()
def scale_reg_loss(self):
def __compute_contour(seg_data):
contours = pynd_segutils.seg2contour(seg_data,exclude_zero=True, contour_type='both')[None]
contours[contours > 0] = 1
return torch.Tensor(contours).cuda()
if self.mask is None:
import SimpleITK as sitk
atlas_path = '/playpen-raid/zyshen/data/oai_seg/atlas_label.nii.gz'
seg = sitk.GetArrayFromImage(sitk.ReadImage(atlas_path))
contour = __compute_contour(seg)
self.mask = 1.0 - contour
delta = self.delta
fd = fdt.FD_torch(self.spacing * 2)
dfx = fd.dXc(delta[:, 0, ...])
dfy = fd.dYc(delta[:, 0, ...])
dfz = fd.dZc(delta[:, 0, ...])
dabs = dfx.abs() + dfy.abs() + dfz.abs()
l2 = self.mask*dabs
reg = l2.mean()
return reg
def get_loss(self):
reg_factor = self.initial_reg_factor
sim_loss = self.get_sim_loss()
reg_loss = self.scale_reg_loss()
if self.print_count % 10 == 0:
print('current sim loss is{}, current_reg_loss is {}, and reg_factor is {} '.format(sim_loss.item(),
reg_loss.item(),
reg_factor))
return sim_loss+ reg_factor*reg_loss
| 39.254795
| 120
| 0.59792
|
4a0a67ae277424b086487e6c51bb18949545671b
| 4,203
|
py
|
Python
|
content/test/faceswap/plugins/train/model/villain.py
|
gwdgithubnom/gjgr
|
581957a296b13a4231ea1e67ec62083b7da445bf
|
[
"MIT"
] | 3
|
2019-08-08T03:27:26.000Z
|
2020-08-17T13:11:24.000Z
|
content/test/faceswap/plugins/train/model/villain.py
|
gwdgithubnom/gjgr
|
581957a296b13a4231ea1e67ec62083b7da445bf
|
[
"MIT"
] | 6
|
2020-03-04T23:21:03.000Z
|
2020-07-23T07:46:40.000Z
|
content/test/faceswap/plugins/train/model/villain.py
|
gwdgithubnom/gjgr
|
581957a296b13a4231ea1e67ec62083b7da445bf
|
[
"MIT"
] | 2
|
2019-09-26T08:52:22.000Z
|
2020-03-27T00:33:00.000Z
|
#!/usr/bin/env python3
""" Original - VillainGuy model
Based on the original https://www.reddit.com/r/deepfakes/ code sample + contribs
Adapted from a model by VillainGuy (https://github.com/VillainGuy) """
from keras.initializers import RandomNormal
from keras.layers import add, Dense, Flatten, Input, Reshape
from keras.models import Model as KerasModel
from lib.model.layers import PixelShuffler
from .original import logger, Model as OriginalModel
class Model(OriginalModel):
""" Villain Faceswap Model """
def __init__(self, *args, **kwargs):
logger.debug("Initializing %s: (args: %s, kwargs: %s",
self.__class__.__name__, args, kwargs)
self.configfile = kwargs.get("configfile", None)
kwargs["input_shape"] = (128, 128, 3)
kwargs["encoder_dim"] = 512 if self.config["lowmem"] else 1024
self.kernel_initializer = RandomNormal(0, 0.02)
super().__init__(*args, **kwargs)
logger.debug("Initialized %s", self.__class__.__name__)
def encoder(self):
""" Encoder Network """
kwargs = dict(kernel_initializer=self.kernel_initializer)
input_ = Input(shape=self.input_shape)
in_conv_filters = self.input_shape[0]
if self.input_shape[0] > 128:
in_conv_filters = 128 + (self.input_shape[0] - 128) // 4
dense_shape = self.input_shape[0] // 16
var_x = self.blocks.conv(input_, in_conv_filters, res_block_follows=True, **kwargs)
tmp_x = var_x
res_cycles = 8 if self.config.get("lowmem", False) else 16
for _ in range(res_cycles):
nn_x = self.blocks.res_block(var_x, 128, **kwargs)
var_x = nn_x
# consider adding scale before this layer to scale the residual chain
var_x = add([var_x, tmp_x])
var_x = self.blocks.conv(var_x, 128, **kwargs)
var_x = PixelShuffler()(var_x)
var_x = self.blocks.conv(var_x, 128, **kwargs)
var_x = PixelShuffler()(var_x)
var_x = self.blocks.conv(var_x, 128, **kwargs)
var_x = self.blocks.conv_sep(var_x, 256, **kwargs)
var_x = self.blocks.conv(var_x, 512, **kwargs)
if not self.config.get("lowmem", False):
var_x = self.blocks.conv_sep(var_x, 1024, **kwargs)
var_x = Dense(self.encoder_dim, **kwargs)(Flatten()(var_x))
var_x = Dense(dense_shape * dense_shape * 1024, **kwargs)(var_x)
var_x = Reshape((dense_shape, dense_shape, 1024))(var_x)
var_x = self.blocks.upscale(var_x, 512, **kwargs)
return KerasModel(input_, var_x)
def decoder(self):
""" Decoder Network """
kwargs = dict(kernel_initializer=self.kernel_initializer)
decoder_shape = self.input_shape[0] // 8
input_ = Input(shape=(decoder_shape, decoder_shape, 512))
var_x = input_
var_x = self.blocks.upscale(var_x, 512, res_block_follows=True, **kwargs)
var_x = self.blocks.res_block(var_x, 512, **kwargs)
var_x = self.blocks.upscale(var_x, 256, res_block_follows=True, **kwargs)
var_x = self.blocks.res_block(var_x, 256, **kwargs)
var_x = self.blocks.upscale(var_x, self.input_shape[0], res_block_follows=True, **kwargs)
var_x = self.blocks.res_block(var_x, self.input_shape[0], **kwargs)
var_x = self.blocks.conv2d(var_x, 3,
kernel_size=5,
padding="same",
activation="sigmoid",
name="face_out")
outputs = [var_x]
if self.config.get("mask_type", None):
var_y = input_
var_y = self.blocks.upscale(var_y, 512)
var_y = self.blocks.upscale(var_y, 256)
var_y = self.blocks.upscale(var_y, self.input_shape[0])
var_y = self.blocks.conv2d(var_y, 1,
kernel_size=5,
padding="same",
activation="sigmoid",
name="mask_out")
outputs.append(var_y)
return KerasModel(input_, outputs=outputs)
| 45.193548
| 97
| 0.598858
|
4a0a67bf65cb33706e08b681a8856850427ccad8
| 3,080
|
py
|
Python
|
src/emotionplot.py
|
mil-tokyo/SharedCharacterStories
|
0ade6bfe9f97ec9b9a96852b50b9392f640cf64f
|
[
"MIT"
] | 3
|
2019-06-06T10:10:33.000Z
|
2020-09-09T00:07:26.000Z
|
src/emotionplot.py
|
mil-tokyo/SharedCharacterStories
|
0ade6bfe9f97ec9b9a96852b50b9392f640cf64f
|
[
"MIT"
] | null | null | null |
src/emotionplot.py
|
mil-tokyo/SharedCharacterStories
|
0ade6bfe9f97ec9b9a96852b50b9392f640cf64f
|
[
"MIT"
] | 1
|
2019-06-06T10:21:33.000Z
|
2019-06-06T10:21:33.000Z
|
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import seaborn as sns
def plot_result(result, N=1):
fig = plt.figure(figsize=(12, 3))
cols_1 = ['char1_sent1_valence', 'char1_sent1_arousal',
'char1_sent2_valence', 'char1_sent2_arousal',
'char1_sent3_valence', 'char1_sent3_arousal',
'char1_sent4_valence', 'char1_sent4_arousal',
'char1_sent5_valence', 'char1_sent5_arousal']
cols_2 = ['char2_sent1_valence', 'char2_sent1_arousal',
'char2_sent2_valence', 'char2_sent2_arousal',
'char2_sent3_valence', 'char2_sent3_arousal',
'char2_sent4_valence', 'char2_sent4_arousal',
'char2_sent5_valence', 'char2_sent5_arousal']
cols_r = ['reader_sent1_valence', 'reader_sent1_arousal',
'reader_sent2_valence', 'reader_sent2_arousal',
'reader_sent3_valence', 'reader_sent3_arousal',
'reader_sent4_valence', 'reader_sent4_arousal',
'reader_sent5_valence', 'reader_sent5_arousal']
char1_array = result.loc[:, cols_1].values.reshape(5,2)
char2_array = result.loc[:, cols_2].values.reshape(5,2)
reader_array = result.loc[:, cols_r].values.reshape(5,2)
def plot_array(result_array, ax, title=None):
for i in range(5):
if i == 0:
plt.scatter(result_array[i][0], result_array[i][1], s=30, c="r", marker='s')
elif i != 4:
plt.scatter(result_array[i][0], result_array[i][1], s=30, c="b", marker='+')
arrow = patches.FancyArrowPatch(result_array[i-1], result_array[i],
arrowstyle='->', linestyle='--',
mutation_scale=20)
ax.add_patch(arrow)
else:
plt.scatter(result_array[i][0], result_array[i][1], s=30, c="g", marker="o")
arrow = patches.FancyArrowPatch(result_array[i-1], result_array[i],
arrowstyle='->', linestyle='--',
mutation_scale=20)
ax.add_patch(arrow)
plt.xlim(-4.5, 4.5)
plt.ylim(-4.5, 4.5)
plt.xlabel("Valence", fontsize='12')
plt.ylabel("Arousal", fontsize='12')
if title != None:
plt.title(title, fontsize='15')
ax1 = fig.add_subplot(N, 3, 1, aspect='equal')
plot_array(char1_array, ax1, "Character 1")
ax1.grid()
ax2 = fig.add_subplot(N, 3, 2, aspect='equal')
plot_array(char2_array, ax2, "Character 2")
ax2.grid()
ax3 = fig.add_subplot(N, 3, 3, aspect='equal')
plot_array(reader_array, ax3, "Reader")
ax3.grid()
return fig
def print_info(result):
print("Story ID:", result.loc[:, "story_id"].values[0])
print("Type:", result.loc[:, "type"].values[0])
print("Rating:", result.loc[:, "rating"].values[0])
print("Review:", result.loc[:, "Review"].values[0])
| 40.526316
| 92
| 0.566234
|
4a0a6904112d5365dbcaccb6b670d8ca83ecc412
| 409
|
py
|
Python
|
django/personal_library/personal_library/wsgi.py
|
mstuttgart/estudos
|
94310b8b3f97a702ffbb710029bffe4becc5a651
|
[
"MIT"
] | 9
|
2019-04-29T21:21:39.000Z
|
2021-05-08T08:04:14.000Z
|
python/django/personal_library/personal_library/wsgi.py
|
midoriobana/estudos
|
a5d2cbb0944b20f650161ab1d251d2440c56bca1
|
[
"MIT"
] | 157
|
2018-05-30T01:53:11.000Z
|
2019-04-22T13:09:05.000Z
|
django/personal_library/personal_library/wsgi.py
|
mstuttgart/my-study-workflow
|
94310b8b3f97a702ffbb710029bffe4becc5a651
|
[
"MIT"
] | 13
|
2019-12-30T11:15:16.000Z
|
2021-10-07T00:54:10.000Z
|
"""
WSGI config for personal_library project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "personal_library.settings")
application = get_wsgi_application()
| 24.058824
| 78
| 0.794621
|
4a0a69b79e7a7fd81697678b72d29add834126d2
| 1,703
|
py
|
Python
|
bigimg/preprocess.py
|
thomasnilsson/big-imaging-project
|
97bdfffc29bcab74abaf2722f8528e815098077c
|
[
"MIT"
] | null | null | null |
bigimg/preprocess.py
|
thomasnilsson/big-imaging-project
|
97bdfffc29bcab74abaf2722f8528e815098077c
|
[
"MIT"
] | null | null | null |
bigimg/preprocess.py
|
thomasnilsson/big-imaging-project
|
97bdfffc29bcab74abaf2722f8528e815098077c
|
[
"MIT"
] | null | null | null |
import numpy as np
import cv2
def rescale_patient_4d_imgs(patient):
img_4d = patient.images
if len(img_4d.shape) < 4: raise Exception("Patient images are not 4D!")
num_slices, time, height, width = img_4d.shape
col, row = patient.col_scaling, patient.row_scaling
scaled_height = int(height * row)
scaled_width = int(width * col)
scaled_imgs = np.zeros((num_slices, time, scaled_height, scaled_width))
for i in range(num_slices):
for j in range(time):
scaled_imgs[i,j] = cv2.resize(src=img_4d[i,j], dsize=None, fx=col, fy=row)
return scaled_imgs
def crop_roi(img, dim_y, dim_x, cy, cx):
"""
Crops an image from the given coords (cy, cx), such that the resulting img is of
dimensions [dim_y, dim_x], i.e. height and width.
Resulting image is filled out from top-left corner, and remaining pixels are left black.
"""
cy, cx = int(round(cy)), int(round(cx))
h, w = img.shape
if dim_x > w or dim_y > h: raise ValueError('Crop dimensions larger than image dimension!')
new_img = np.zeros((dim_y, dim_x))
dx, dy = int(dim_x / 2), int(dim_y / 2)
dx_odd, dy_odd = int(dim_x % 2 == 1), int(dim_y % 2 == 1)
# Find boundaries for cropping [original img]
dx_left = max(0, cx - dx)
dx_right = min(w, cx + dx + dx_odd)
dy_up = max(0, cy - dy)
dy_down = min(h, cy + dy + dy_odd)
# Find how many pixels to fill out in new image
range_x = dx_right - dx_left
range_y = dy_down - dy_up
# Fill out new image from top left corner
# Leave pixels outside range as 0's (black)
new_img[0:range_y, 0:range_x] = img[dy_up:dy_down, dx_left:dx_right]
return new_img
| 37.021739
| 95
| 0.650617
|
4a0a69c7df771d3bf8795c75604baa6f33cb668d
| 3,086
|
py
|
Python
|
src/gui/command.py
|
iosetek/CommandRecognition
|
56a58b44bdc4d54feafc955c17dd0ff236486cae
|
[
"MIT"
] | null | null | null |
src/gui/command.py
|
iosetek/CommandRecognition
|
56a58b44bdc4d54feafc955c17dd0ff236486cae
|
[
"MIT"
] | null | null | null |
src/gui/command.py
|
iosetek/CommandRecognition
|
56a58b44bdc4d54feafc955c17dd0ff236486cae
|
[
"MIT"
] | null | null | null |
from src.api import Api
from src.gui.appJar.appjar import gui
class CommandUI:
def __init__(self, app):
self.__app = app
def append_its_content(self):
"""
Creates view designed for registering new commands or editing
already existing commands. It allows user to load records from
disk or recording it directly to programm. Each command is
translated to set of phonem classes described by already
registered model.
"""
self.__app.addLabel("COMMANDS_COMMANDS_NAMES_LABEL", "COMMANDS",
row=1, column=1, rowspan=2, colspan=5)
self.__app.addListBox("COMMANDS_COMMANDS_LISTBOX",
row=3, column=1, rowspan=7, colspan=5)
self.__app.addNamedButton("ADD NEW", "COMMANDS_NEW_COMMAND_BUTTON", print("TODO"),
row=10, column=1, rowspan=2, colspan=5)
self.__app.addNamedButton("EDIT", "COMMANDS_EDIT_COMMAND_BUTTON", print("TODO"),
row=13, column=1, rowspan=2, colspan=5)
self.__app.addNamedButton("DELETE", "COMMANDS_DELETE_COMMAND_BUTTON", print("TODO"),
row=15, column=1, rowspan=2, colspan=5)
self.__app.addLabel("COMMANDS_COMMAND_NAME_LABEL", "NAME",
row=1, column=6, rowspan=1, colspan=6)
self.__app.addEntry("COMMANDS_COMMAND_NAME_ENTRY",
row=2, column=6, rowspan=1, colspan=2)
self.__app.addNamedButton("ACTIVATE", "COMMANDS_ACTIVATE_BUTTON", print("TODO"),
row=3, column=6, rowspan=1, colspan=6)
self.__app.addNamedButton("DEACTIVATE", "COMMANDS_DEACTIVATE_BUTTON", print("TODO"),
row=4, column=6, rowspan=1, colspan=6)
self.__app.addNamedButton("CALCULATE", "COMMANDS_CALCULATE_BUTTON", print("TODO"),
row=5, column=6, rowspan=1, colspan=6)
self.__app.addLabel("COMMANDS_LOG_LABEL", "",
row=6, column=6, rowspan=1, colspan=14)
self.__app.addLabel("COMMANDS_RECORDS_NAMES_LABEL", "RECORDS",
row=1, column=12, rowspan=2, colspan=7)
self.__app.addListBox("COMMANDS_RECORD_LISTBOX",
row=3, column=12, rowspan=5, colspan=7)
self.__app.addNamedButton("PLAY", "COMMANDS_PLAY_RECORD_BUTTON", print("TODO"),
row=9, column=12, rowspan=2, colspan=3)
self.__app.addNamedButton("DELETE", "COMMANDS_DELETE_RECORD_BUTTON", print("TODO"),
row=9, column=15, rowspan=2, colspan=4)
self.__app.addNamedButton("RECORD NEW", "COMMANDS_RECORD_RECORD_BUTTON", print("TODO"),
row=11, column=12, rowspan=2, colspan=7)
self.__app.addNamedButton("LOAD", "COMMANDS_LOAD_RECORD_BUTTON", print("TODO"),
row=13, column=12, rowspan=2, colspan=7)
print("TODO")
| 57.148148
| 95
| 0.580687
|
4a0a69d66298f5f6ab4d503b9b8206da9a234504
| 17,307
|
py
|
Python
|
snakemake/deployment/conda.py
|
Lodewic/snakemake
|
f00cd3b26250db5b9330acd1981b1e24614fc8b8
|
[
"MIT"
] | null | null | null |
snakemake/deployment/conda.py
|
Lodewic/snakemake
|
f00cd3b26250db5b9330acd1981b1e24614fc8b8
|
[
"MIT"
] | null | null | null |
snakemake/deployment/conda.py
|
Lodewic/snakemake
|
f00cd3b26250db5b9330acd1981b1e24614fc8b8
|
[
"MIT"
] | null | null | null |
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2015-2019, Johannes Köster"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
import os
import re
import subprocess
import tempfile
from urllib.request import urlopen
from urllib.parse import urlparse
from urllib.error import URLError
import hashlib
import shutil
from distutils.version import StrictVersion
import json
from glob import glob
import tarfile
import zipfile
import uuid
from enum import Enum
from snakemake.exceptions import CreateCondaEnvironmentException, WorkflowError
from snakemake.logging import logger
from snakemake.common import strip_prefix, ON_WINDOWS
from snakemake import utils
from snakemake.deployment import singularity
from snakemake.io import git_content
class CondaCleanupMode(Enum):
tarballs = "tarballs"
cache = "cache"
def __str__(self):
return self.value
def content(env_file):
if env_file.startswith("git+file:"):
return git_content(env_file).encode("utf-8")
elif urlparse(env_file).netloc:
try:
return urlopen(env_file).read()
except URLError as e:
raise WorkflowError(
"Failed to open environment file {}:".format(env_file), e
)
else:
if not os.path.exists(env_file):
raise WorkflowError("Conda env file does not " "exist: {}".format(env_file))
with open(env_file, "rb") as f:
return f.read()
class Env:
"""Conda environment from a given specification file."""
def __init__(self, env_file, dag, container_img=None, cleanup=None):
self.file = env_file
self.frontend = dag.workflow.conda_frontend
self._env_dir = dag.workflow.persistence.conda_env_path
self._env_archive_dir = dag.workflow.persistence.conda_env_archive_path
self._hash = None
self._content_hash = None
self._content = None
self._path = None
self._archive_file = None
self._container_img = container_img
self._cleanup = cleanup
@property
def container_img_url(self):
return self._container_img.url if self._container_img else None
@property
def content(self):
if self._content is None:
self._content = content(self.file)
return self._content
@property
def hash(self):
if self._hash is None:
md5hash = hashlib.md5()
# Include the absolute path of the target env dir into the hash.
# By this, moving the working directory around automatically
# invalidates all environments. This is necessary, because binaries
# in conda environments can contain hardcoded absolute RPATHs.
env_dir = os.path.realpath(self._env_dir)
md5hash.update(env_dir.encode())
if self._container_img:
md5hash.update(self._container_img.url.encode())
md5hash.update(self.content)
self._hash = md5hash.hexdigest()
return self._hash
@property
def content_hash(self):
if self._content_hash is None:
md5hash = hashlib.md5()
md5hash.update(self.content)
self._content_hash = md5hash.hexdigest()
return self._content_hash
@property
def path(self):
"""Path to directory of the conda environment.
First tries full hash, if it does not exist, (8-prefix) is used
as default.
"""
hash = self.hash
env_dir = self._env_dir
for h in [hash, hash[:8]]:
path = os.path.join(env_dir, h)
if os.path.exists(path):
return path
return path
@property
def archive_file(self):
"""Path to archive of the conda environment, which may or may not exist."""
if self._archive_file is None:
self._archive_file = os.path.join(self._env_archive_dir, self.content_hash)
return self._archive_file
def create_archive(self):
"""Create self-contained archive of environment."""
from snakemake.shell import shell
try:
import yaml
except ImportError:
raise WorkflowError(
"Error importing PyYAML. " "Please install PyYAML to archive workflows."
)
# importing requests locally because it interferes with instantiating conda environments
import requests
env_archive = self.archive_file
if os.path.exists(env_archive):
return env_archive
try:
# Download
logger.info(
"Downloading packages for conda environment {}...".format(self.file)
)
os.makedirs(env_archive, exist_ok=True)
try:
out = shell.check_output(
"conda list --explicit --prefix '{}'".format(self.path),
stderr=subprocess.STDOUT,
universal_newlines=True,
)
logger.debug(out)
except subprocess.CalledProcessError as e:
raise WorkflowError("Error exporting conda packages:\n" + e.output)
with open(os.path.join(env_archive, "packages.txt"), "w") as pkg_list:
for l in out.split("\n"):
if l and not l.startswith("#") and not l.startswith("@"):
pkg_url = l
logger.info(pkg_url)
parsed = urlparse(pkg_url)
pkg_name = os.path.basename(parsed.path)
# write package name to list
print(pkg_name, file=pkg_list)
# download package
pkg_path = os.path.join(env_archive, pkg_name)
with open(pkg_path, "wb") as copy:
r = requests.get(pkg_url)
r.raise_for_status()
copy.write(r.content)
try:
if pkg_path.endswith(".conda"):
assert zipfile.ZipFile(pkg_path).testzip() is None
else:
tarfile.open(pkg_path)
except:
raise WorkflowError(
"Package is invalid tar/zip archive: {}".format(pkg_url)
)
except (
requests.exceptions.ChunkedEncodingError,
requests.exceptions.HTTPError,
) as e:
shutil.rmtree(env_archive)
raise WorkflowError("Error downloading conda package {}.".format(pkg_url))
except (Exception, BaseException) as e:
shutil.rmtree(env_archive)
raise e
return env_archive
def create(self, dryrun=False):
""" Create the conda enviroment."""
from snakemake.shell import shell
# Read env file and create hash.
env_file = self.file
tmp_file = None
url_scheme, *_ = urlparse(env_file)
if (url_scheme and not url_scheme == "file") or (
not url_scheme and env_file.startswith("git+file:/")
):
with tempfile.NamedTemporaryFile(delete=False, suffix=".yaml") as tmp:
tmp.write(self.content)
env_file = tmp.name
tmp_file = tmp.name
env_hash = self.hash
env_path = self.path
# Check for broken environment
if os.path.exists(
os.path.join(env_path, "env_setup_start")
) and not os.path.exists(os.path.join(env_path, "env_setup_done")):
if dryrun:
logger.info(
"Incomplete Conda environment {} will be recreated.".format(
utils.simplify_path(self.file)
)
)
else:
logger.info(
"Removing incomplete Conda environment {}...".format(
utils.simplify_path(self.file)
)
)
shutil.rmtree(env_path, ignore_errors=True)
# Create environment if not already present.
if not os.path.exists(env_path):
if dryrun:
logger.info(
"Conda environment {} will be created.".format(
utils.simplify_path(self.file)
)
)
return env_path
conda = Conda(self._container_img)
logger.info(
"Creating conda environment {}...".format(
utils.simplify_path(self.file)
)
)
# Check if env archive exists. Use that if present.
env_archive = self.archive_file
try:
# Touch "start" flag file
os.makedirs(env_path, exist_ok=True)
with open(os.path.join(env_path, "env_setup_start"), "a") as f:
pass
if os.path.exists(env_archive):
logger.info("Installing archived conda packages.")
pkg_list = os.path.join(env_archive, "packages.txt")
if os.path.exists(pkg_list):
# read pacakges in correct order
# this is for newer env archives where the package list
# was stored
packages = [
os.path.join(env_archive, pkg.rstrip())
for pkg in open(pkg_list)
]
else:
# guess order
packages = glob(os.path.join(env_archive, "*.tar.bz2"))
# install packages manually from env archive
cmd = " ".join(
["conda", "create", "--copy", "--prefix '{}'".format(env_path)]
+ packages
)
if self._container_img:
cmd = singularity.shellcmd(
self._container_img.path,
cmd,
envvars=self.get_singularity_envvars(),
)
out = shell.check_output(
cmd, stderr=subprocess.STDOUT, universal_newlines=True
)
else:
# Copy env file to env_path (because they can be on
# different volumes and singularity should only mount one).
# In addition, this allows to immediately see what an
# environment in .snakemake/conda contains.
target_env_file = env_path + ".yaml"
shutil.copy(env_file, target_env_file)
logger.info("Downloading and installing remote packages.")
cmd = " ".join(
[
self.frontend,
"env",
"create",
"--file '{}'".format(target_env_file),
"--prefix '{}'".format(env_path),
]
)
if self._container_img:
cmd = singularity.shellcmd(
self._container_img.path,
cmd,
envvars=self.get_singularity_envvars(),
)
out = shell.check_output(
cmd, stderr=subprocess.STDOUT, universal_newlines=True
)
# cleanup if requested
if self._cleanup is CondaCleanupMode.tarballs:
logger.info("Cleaning up conda package tarballs.")
shell.check_output("conda clean -y --tarballs")
elif self._cleanup is CondaCleanupMode.cache:
logger.info(
"Cleaning up conda package tarballs and package cache."
)
shell.check_output("conda clean -y --tarballs --packages")
# Touch "done" flag file
with open(os.path.join(env_path, "env_setup_done"), "a") as f:
pass
logger.debug(out)
logger.info(
"Environment for {} created (location: {})".format(
os.path.relpath(env_file), os.path.relpath(env_path)
)
)
except subprocess.CalledProcessError as e:
# remove potential partially installed environment
shutil.rmtree(env_path, ignore_errors=True)
raise CreateCondaEnvironmentException(
"Could not create conda environment from {}:\n".format(env_file)
+ e.output
)
if tmp_file:
# temporary file was created
os.remove(tmp_file)
return env_path
@classmethod
def get_singularity_envvars(self):
return {"CONDA_PKGS_DIRS": "/tmp/conda/{}".format(uuid.uuid4())}
def __hash__(self):
# this hash is only for object comparison, not for env paths
return hash(self.file)
def __eq__(self, other):
if isinstance(other, Env):
return self.file == other.file
return False
class Conda:
instances = dict()
def __new__(cls, container_img=None):
if container_img not in cls.instances:
inst = super().__new__(cls)
inst.__init__(container_img=container_img)
cls.instances[container_img] = inst
return inst
else:
return cls.instances[container_img]
def __init__(self, container_img=None):
from snakemake.shell import shell
from snakemake.deployment import singularity
if isinstance(container_img, singularity.Image):
container_img = container_img.path
self.container_img = container_img
self._check()
self.info = json.loads(shell.check_output(self._get_cmd("conda info --json")))
def _get_cmd(self, cmd):
if self.container_img:
return singularity.shellcmd(self.container_img, cmd)
return cmd
def _check(self):
from snakemake.shell import shell
# Use type here since conda now is a function.
# type allows to check for both functions and regular commands.
if not ON_WINDOWS or shell.get_executable():
locate_cmd = "type conda"
else:
locate_cmd = "where conda"
try:
shell.check_output(self._get_cmd(locate_cmd), stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
if self.container_img:
raise CreateCondaEnvironmentException(
"The 'conda' command is not "
"available inside "
"your singularity container "
"image. Snakemake mounts "
"your conda installation "
"into singularity. "
"Sometimes, this can fail "
"because of shell restrictions. "
"It has been tested to work "
"with docker://ubuntu, but "
"it e.g. fails with "
"docker://bash "
)
else:
raise CreateCondaEnvironmentException(
"The 'conda' command is not "
"available in the "
"shell {} that will be "
"used by Snakemake. You have "
"to ensure that it is in your "
"PATH, e.g., first activating "
"the conda base environment "
"with `conda activate base`.".format(shell.get_executable())
)
try:
version = shell.check_output(
self._get_cmd("conda --version"),
stderr=subprocess.STDOUT,
universal_newlines=True,
)
version = version.split()[1]
if StrictVersion(version) < StrictVersion("4.2"):
raise CreateCondaEnvironmentException(
"Conda must be version 4.2 or later, found version {}.".format(
version
)
)
except subprocess.CalledProcessError as e:
raise CreateCondaEnvironmentException(
"Unable to check conda version:\n" + e.output.decode()
)
def prefix_path(self):
return self.info["conda_prefix"]
def bin_path(self):
return os.path.join(self.prefix_path(), "bin")
def shellcmd(self, env_path, cmd):
from snakemake.shell import shell
# get path to activate script
activate = os.path.join(self.bin_path(), "activate")
return "source {} '{}'; {}".format(activate, env_path, cmd)
| 37.542299
| 96
| 0.530479
|
4a0a6a939103dacabcbcd1f1f2d210e42848ddec
| 74
|
py
|
Python
|
fonts/internal.py
|
theblacklion/diamond-framework
|
0996a517a6821d8903f5c378a85e9b1f3998109f
|
[
"MIT"
] | null | null | null |
fonts/internal.py
|
theblacklion/diamond-framework
|
0996a517a6821d8903f5c378a85e9b1f3998109f
|
[
"MIT"
] | null | null | null |
fonts/internal.py
|
theblacklion/diamond-framework
|
0996a517a6821d8903f5c378a85e9b1f3998109f
|
[
"MIT"
] | null | null | null |
# default font
type = 'ttf'
name = None
size = 14
color = (255, 255, 255)
| 12.333333
| 23
| 0.621622
|
4a0a6ad3b59432206f63b88160c6704e34092997
| 92
|
py
|
Python
|
letra/label.py
|
swellaby/letra
|
1a232a454fce0a01a8b3021ab9d0da976eaa041e
|
[
"MIT"
] | null | null | null |
letra/label.py
|
swellaby/letra
|
1a232a454fce0a01a8b3021ab9d0da976eaa041e
|
[
"MIT"
] | 178
|
2019-06-13T22:21:03.000Z
|
2022-03-29T11:22:14.000Z
|
letra/label.py
|
swellaby/letra
|
1a232a454fce0a01a8b3021ab9d0da976eaa041e
|
[
"MIT"
] | null | null | null |
from collections import namedtuple
Label = namedtuple("Label", "name, description, color")
| 23
| 55
| 0.771739
|
4a0a6c047bdb10c4737a361aaa60d9180cae6c70
| 6,642
|
py
|
Python
|
salt/proxy/dummy.py
|
Bacon-Unlimited/salt
|
9b1b791d212a6810c430dd15c63fbce3a4f7e1d6
|
[
"Apache-2.0"
] | 9,425
|
2015-01-01T05:59:24.000Z
|
2022-03-31T20:44:05.000Z
|
salt/proxy/dummy.py
|
Bacon-Unlimited/salt
|
9b1b791d212a6810c430dd15c63fbce3a4f7e1d6
|
[
"Apache-2.0"
] | 33,507
|
2015-01-01T00:19:56.000Z
|
2022-03-31T23:48:20.000Z
|
salt/proxy/dummy.py
|
Bacon-Unlimited/salt
|
9b1b791d212a6810c430dd15c63fbce3a4f7e1d6
|
[
"Apache-2.0"
] | 5,810
|
2015-01-01T19:11:45.000Z
|
2022-03-31T02:37:20.000Z
|
"""
This is the a dummy proxy-minion designed for testing the proxy minion subsystem.
"""
import copy
import logging
import os
import pprint
from contextlib import contextmanager
import salt.utils.files
import salt.utils.msgpack
# This must be present or the Salt loader won't load this module
__proxyenabled__ = ["dummy"]
log = logging.getLogger(__file__)
# This does nothing, it's here just as an example and to provide a log
# entry when the module is loaded.
def __virtual__():
"""
Only return if all the modules are available
"""
log.debug("dummy proxy __virtual__() called...")
return True
def _save_state(opts, details):
_id = __context__["dummy_proxy"]["id"]
cachefile = os.path.join(opts["cachedir"], "dummy-proxy-{}.cache".format(_id))
with salt.utils.files.fopen(cachefile, "wb") as pck:
pck.write(salt.utils.msgpack.packb(details, use_bin_type=True))
log.warning("Dummy Proxy Saved State(%s):\n%s", cachefile, pprint.pformat(details))
def _load_state(opts):
_id = __context__["dummy_proxy"]["id"]
cachefile = os.path.join(opts["cachedir"], "dummy-proxy-{}.cache".format(_id))
try:
with salt.utils.files.fopen(cachefile, "rb") as pck:
state = salt.utils.msgpack.unpackb(pck.read(), raw=False)
except FileNotFoundError:
state = _initial_state()
_save_state(opts, state)
except Exception as exc: # pylint: disable=broad-except
log.exception("Failed to load state: %s", exc, exc_info=True)
state = _initial_state()
_save_state(opts, state)
log.warning("Dummy Proxy Loaded State(%s):\n%s", cachefile, pprint.pformat(state))
return state
@contextmanager
def _loaded_state(opts):
state = _load_state(opts)
original = copy.deepcopy(state)
try:
yield state
finally:
if state != original:
_save_state(opts, state)
def _initial_state():
return {
"services": {"apache": "running", "ntp": "running", "samba": "stopped"},
"packages": {
"coreutils": "1.0",
"apache": "2.4",
"tinc": "1.4",
"redbull": "999.99",
},
}
# Every proxy module needs an 'init', though you can
# just put DETAILS['initialized'] = True here if nothing
# else needs to be done.
def init(opts):
"""
Required.
Can be used to initialize the server connection.
"""
__context__["dummy_proxy"] = {"id": opts["id"]}
log.debug("dummy proxy init() called...")
with _loaded_state(opts) as state:
state["initialized"] = True
def initialized():
"""
Since grains are loaded in many different places and some of those
places occur before the proxy can be initialized, return whether
our init() function has been called
"""
with _loaded_state(__opts__) as state:
return state.get("initialized", False)
def grains():
"""
Make up some grains
"""
with _loaded_state(__opts__) as state:
if "grains_cache" not in state:
state["grains_cache"] = {
"dummy_grain_1": "one",
"dummy_grain_2": "two",
"dummy_grain_3": "three",
}
return state["grains_cache"]
def grains_refresh():
"""
Refresh the grains
"""
with _loaded_state(__opts__) as state:
if "grains_cache" in state:
state.pop("grains_cache")
return grains()
def fns():
"""
Method called by grains module.
"""
return {
"details": (
"This key is here because a function in "
"grains/rest_sample.py called fns() here in the proxymodule."
)
}
def service_start(name):
"""
Start a "service" on the dummy server
"""
with _loaded_state(__opts__) as state:
state["services"][name] = "running"
return "running"
def service_stop(name):
"""
Stop a "service" on the dummy server
"""
with _loaded_state(__opts__) as state:
state["services"][name] = "stopped"
return "stopped"
def service_restart(name):
"""
Restart a "service" on the REST server
"""
return True
def service_list():
"""
List "services" on the REST server
"""
with _loaded_state(__opts__) as state:
return list(state["services"])
def service_status(name):
"""
Check if a service is running on the REST server
"""
with _loaded_state(__opts__) as state:
if state["services"][name] == "running":
return {"comment": "running"}
else:
return {"comment": "stopped"}
def package_list():
"""
List "packages" installed on the REST server
"""
with _loaded_state(__opts__) as state:
return state["packages"]
def package_install(name, **kwargs):
"""
Install a "package" on the REST server
"""
if kwargs.get("version", False):
version = kwargs["version"]
else:
version = "1.0"
with _loaded_state(__opts__) as state:
state["packages"][name] = version
return {name: version}
def upgrade():
"""
"Upgrade" packages
"""
with _loaded_state(__opts__) as state:
for p in state["packages"]:
version_float = float(state["packages"][p])
version_float = version_float + 1.0
state["packages"][p] = str(version_float)
return state["packages"]
def uptodate():
"""
Call the REST endpoint to see if the packages on the "server" are up to date.
"""
with _loaded_state(__opts__) as state:
return state["packages"]
def package_remove(name):
"""
Remove a "package" on the REST server
"""
__context__["dummy_proxy"]["foo"] = "bar"
with _loaded_state(__opts__) as state:
state["packages"].pop(name)
return state["packages"]
def package_status(name):
"""
Check the installation status of a package on the REST server
"""
with _loaded_state(__opts__) as state:
if name in state["packages"]:
return {name: state["packages"][name]}
def ping():
"""
Degenerate ping
"""
log.debug("dummy proxy returning ping")
return True
def shutdown(opts):
"""
For this proxy shutdown is a no-op
"""
log.debug("dummy proxy shutdown() called...")
with _loaded_state(__opts__) as state:
if "filename" in state:
os.unlink(state["filename"])
def test_from_state():
"""
Test function so we have something to call from a state
:return:
"""
log.debug("test_from_state called")
return "testvalue"
| 24.69145
| 87
| 0.612767
|
4a0a6c106d0a4bb14125e998e18d3b5d229dc102
| 495
|
py
|
Python
|
backend/orders/migrations/0008_auto_20220417_1104.py
|
crowdbotics-apps/royal-cloud-33498
|
4ac1701e6af7db4b3b7393b73fc0af80fc313b3b
|
[
"FTL",
"AML",
"RSA-MD"
] | null | null | null |
backend/orders/migrations/0008_auto_20220417_1104.py
|
crowdbotics-apps/royal-cloud-33498
|
4ac1701e6af7db4b3b7393b73fc0af80fc313b3b
|
[
"FTL",
"AML",
"RSA-MD"
] | null | null | null |
backend/orders/migrations/0008_auto_20220417_1104.py
|
crowdbotics-apps/royal-cloud-33498
|
4ac1701e6af7db4b3b7393b73fc0af80fc313b3b
|
[
"FTL",
"AML",
"RSA-MD"
] | null | null | null |
# Generated by Django 2.2.27 on 2022-04-17 11:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0007_suborder_style'),
]
operations = [
migrations.RemoveField(
model_name='suborder',
name='style',
),
migrations.AddField(
model_name='order',
name='style',
field=models.CharField(blank=True, max_length=150),
),
]
| 21.521739
| 63
| 0.567677
|
4a0a6c6cc0684ee6246bec0e5afd00cf22dec20d
| 1,988
|
py
|
Python
|
tempofy_bot.py
|
hardkoro/tempofy_bot
|
a3adee36ce36a43c867c1dc5d750f2bf9126f095
|
[
"MIT"
] | null | null | null |
tempofy_bot.py
|
hardkoro/tempofy_bot
|
a3adee36ce36a43c867c1dc5d750f2bf9126f095
|
[
"MIT"
] | null | null | null |
tempofy_bot.py
|
hardkoro/tempofy_bot
|
a3adee36ce36a43c867c1dc5d750f2bf9126f095
|
[
"MIT"
] | null | null | null |
from os import getenv
from dotenv import find_dotenv, load_dotenv
from telegram import ParseMode
from telegram.ext import (CommandHandler, Defaults, Filters, MessageHandler,
Updater)
from help import FEATURE_HELP, START_MESSAGE
from get_song_features import get_song_data
load_dotenv(find_dotenv())
TOKEN = getenv('TOKEN')
DEBUG_MODE = False
TEST_URI = 'https://open.spotify.com/track/40riOy7x9W7GXjyGp4pjAv?si=ba7f5849faa64fbe'
class TempofyBot():
def __init__(self):
if DEBUG_MODE:
print(get_song_data(TEST_URI))
else:
self.updater = Updater(
TOKEN,
defaults=Defaults(disable_web_page_preview=True)
)
self.dispatcher = self.updater.dispatcher
self.dispatcher.add_handler(
CommandHandler('start', self.start)
)
self.dispatcher.add_handler(
CommandHandler('help', self.help)
)
self.dispatcher.add_handler(
MessageHandler(
Filters.text & ~Filters.command, self.tempofy_song
)
)
self.updater.start_polling()
self.updater.idle()
def start(self, update, context):
user = update.effective_user
update.message.reply_markdown_v2(
START_MESSAGE.format(username=user.mention_markdown_v2())
)
def help(self, update, context):
update.message.reply_text(FEATURE_HELP, parse_mode=ParseMode.MARKDOWN)
def tempofy_song(self, update, context):
try:
update.message.reply_text(
get_song_data(update.message.text),
parse_mode=ParseMode.MARKDOWN
)
except Exception:
update.message.reply_text(
'Sorry! But I can\'t find song with this URI at Spotify 💁'
)
def main():
TempofyBot()
if __name__ == '__main__':
main()
| 28.811594
| 86
| 0.605131
|
4a0a6c7d2c4f35fa6c8a3bc51e07577f49dc7b75
| 617
|
py
|
Python
|
django_exemple/migrations/0003_alter_todolist_user.py
|
mifa43/django-start
|
56e509af4ee61651d0b15a0858e82330b702c7a7
|
[
"Apache-2.0"
] | null | null | null |
django_exemple/migrations/0003_alter_todolist_user.py
|
mifa43/django-start
|
56e509af4ee61651d0b15a0858e82330b702c7a7
|
[
"Apache-2.0"
] | 4
|
2021-08-06T08:29:46.000Z
|
2021-08-25T07:55:36.000Z
|
django_exemple/migrations/0003_alter_todolist_user.py
|
mifa43/django-start
|
56e509af4ee61651d0b15a0858e82330b702c7a7
|
[
"Apache-2.0"
] | null | null | null |
# Generated by Django 3.2.6 on 2021-08-09 13:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('django_exemple', '0002_todolist_user'),
]
operations = [
migrations.AlterField(
model_name='todolist',
name='user',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='TodoList', to=settings.AUTH_USER_MODEL),
),
]
| 28.045455
| 146
| 0.683955
|
4a0a6cba4fa2117e4158d2ec83fd8a9488e2ee58
| 3,401
|
py
|
Python
|
CoderWorld/settings.py
|
Rasesh2005/CoderWorld
|
c9b973da6a5be80db2d167bf0bebca83e845b4e2
|
[
"MIT"
] | 1
|
2020-12-21T09:53:01.000Z
|
2020-12-21T09:53:01.000Z
|
CoderWorld/settings.py
|
Rasesh2005/CoderWorld
|
c9b973da6a5be80db2d167bf0bebca83e845b4e2
|
[
"MIT"
] | null | null | null |
CoderWorld/settings.py
|
Rasesh2005/CoderWorld
|
c9b973da6a5be80db2d167bf0bebca83e845b4e2
|
[
"MIT"
] | 2
|
2020-10-11T07:32:54.000Z
|
2020-10-11T08:18:31.000Z
|
"""
Django settings for CoderWorld project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
from django.contrib.messages import constants as messages
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'k&@c+j#r849ojuj=sp=6-u(aol@guc*oc82hd^&(&23yfcz9xl'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'home',
'blog',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'CoderWorld.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
TEMPLATE_DIR,
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'CoderWorld.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=[STATIC_DIR]
MESSAGE_TAGS = {
messages.ERROR: 'danger',
}
| 25.571429
| 91
| 0.697148
|
4a0a6e9e1868ded041452dbcbf4b2356057a27e7
| 1,467
|
py
|
Python
|
flatblocks/models.py
|
whyflyru/django-flatblocks
|
8e205e051805972f8f4017542b4d7e4748c18496
|
[
"BSD-3-Clause"
] | null | null | null |
flatblocks/models.py
|
whyflyru/django-flatblocks
|
8e205e051805972f8f4017542b4d7e4748c18496
|
[
"BSD-3-Clause"
] | null | null | null |
flatblocks/models.py
|
whyflyru/django-flatblocks
|
8e205e051805972f8f4017542b4d7e4748c18496
|
[
"BSD-3-Clause"
] | 1
|
2020-02-06T16:14:25.000Z
|
2020-02-06T16:14:25.000Z
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
class FlatBlock(models.Model):
"""
Think of a flatblock as a flatpage but for just part of a site. It's
basically a piece of content with a given name (slug) and an optional
title (header) which you can, for example, use in a sidebar of a website.
"""
slug = models.CharField(_('Slug'), max_length=255,
help_text=_("A unique name used for reference in the templates"))
header = models.CharField(_('Header'), blank=True, max_length=255,
help_text=_("An optional header for this content"))
content = models.TextField(verbose_name=_('Content'), blank=True)
subdomain = models.CharField(_('Subdomain'), blank=True, null=True, max_length=255,
help_text=_('A subdomain under which the content will be displayed'))
all_subdomains = models.BooleanField(verbose_name=_('All subdomains'), default=False,
help_text=_('Show on all subdomains'))
# Helper attributes used if content should be evaluated in order to
# represent the original content.
raw_content = None
raw_header = None
def __str__(self):
return self.slug
class Meta:
verbose_name = _('Flat block')
verbose_name_plural = _('Flat blocks')
unique_together = ('slug', 'subdomain', 'all_subdomains')
| 43.147059
| 102
| 0.646217
|
4a0a6eb21d08a1b1a5adc42035c7eb27c4be96b5
| 2,705
|
py
|
Python
|
app/recipe/tests/test_ingredients_api.py
|
StephPoleo/recipe-app-api
|
63269eb720023f15b16c009b46a161ba7621496f
|
[
"MIT"
] | null | null | null |
app/recipe/tests/test_ingredients_api.py
|
StephPoleo/recipe-app-api
|
63269eb720023f15b16c009b46a161ba7621496f
|
[
"MIT"
] | null | null | null |
app/recipe/tests/test_ingredients_api.py
|
StephPoleo/recipe-app-api
|
63269eb720023f15b16c009b46a161ba7621496f
|
[
"MIT"
] | null | null | null |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredients
from recipe.serializer import IngredientsSerializer
INGREDIENTS_URL = reverse("recipe:ingredients-list")
class PublicIngredientsApiTest(TestCase):
"""Test the publicly available ingredients API"""
def setUp(self):
self.client = APIClient()
def test_login_required(self):
"""Test that login is required to access the endpoint"""
res = self.client.get(INGREDIENTS_URL)
self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)
class PrivateIngredientsApiTest(TestCase):
"""Test ingredients can be retived by authorized user"""
def setUp(self):
self.user = get_user_model().objects.create_user("prueba@test.com", "testpass")
self.client = APIClient()
self.client.force_authenticate(self.user)
def test_retrieve_ingredients_list(self):
"""Test retrieving a list of ingredients"""
Ingredients.objects.create(user=self.user, name="Kale")
Ingredients.objects.create(user=self.user, name="Salt")
res = self.client.get(INGREDIENTS_URL)
ingredients = Ingredients.objects.all().order_by("-name")
serializer = IngredientsSerializer(ingredients, many=True)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(res.data, serializer.data)
def test_ingredients_limited_to_user(self):
"""Test that ingredients form the authenticated user are returned"""
user2 = get_user_model().objects.create_user("prueba2@test.com", "testpass")
Ingredients.objects.create(user=user2, name="Vinegar")
ingredient = Ingredients.objects.create(user=self.user, name="Tumeric")
res = self.client.get(INGREDIENTS_URL)
self.assertEqual(res.status_code, status.HTTP_200_OK)
self.assertEqual(len(res.data), 1)
self.assertEqual(res.data[0]["name"], ingredient.name)
def test_create_ingredient_successful(self):
"""Test create a new ingredient"""
payload = {"name": "Cabbage"}
self.client.post(INGREDIENTS_URL, payload)
exists = Ingredients.objects.filter(
user=self.user,
name=payload["name"],
).exists()
self.assertTrue(exists)
def test_create_ingredient_invalid(self):
"""Test creating invalid ingredient fails"""
payload = {"name": ""}
res = self.client.post(INGREDIENTS_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
| 34.240506
| 87
| 0.699445
|
4a0a6ec3cdbba18e6e82139d3f5a2e02cddf188c
| 1,035
|
py
|
Python
|
settings.py
|
Llona/AJ-cat_plugin
|
9d4a826bf74d46c395c90e05c460ab87b063b002
|
[
"Apache-2.0"
] | null | null | null |
settings.py
|
Llona/AJ-cat_plugin
|
9d4a826bf74d46c395c90e05c460ab87b063b002
|
[
"Apache-2.0"
] | null | null | null |
settings.py
|
Llona/AJ-cat_plugin
|
9d4a826bf74d46c395c90e05c460ab87b063b002
|
[
"Apache-2.0"
] | null | null | null |
import sys
from os import path
import enum
import platform
DEVICE_ID = 'RF8N32YBMGG'
# FIGHTING_COLOR = "528cca"
FIGHTING_COLOR = "5995d2"
# DEVICE_ID = '2785a241e41c7ece'
# FIGHTING_COLOR = "3c5e85"
COPY_FIGHT_TOTAL_COUNT = 5
if platform.system() == 'Windows':
VIRTUAL_DISK = 'R:'
VIRTUAL_CREATE_CMD = 'imdisk -a -s 64M -m '+VIRTUAL_DISK+' -o rem -p "/fs:ntfs /v:RamDisk /q /y" > nul'
VIRTUAL_DELETE_CMD = 'imdisk -D -m '+VIRTUAL_DISK
NULL_DEV = 'nul'
else:
VIRTUAL_DISK = '/tmp/ramdisk/'
VIRTUAL_MOUNT_CMD = 'echo Aa112233 | sudo -S mount -t tmpfs -o size=64M tmpfs ' + VIRTUAL_DISK
VIRTUAL_UMOUNT_CMD = 'echo Aa112233 | sudo -S umount ' + VIRTUAL_DISK
NULL_DEV = '/dev/null'
NO_VD_SCREEN_DUMP_PATH = path.join(sys.path[0], 'screen.dump')
SCREEN_DUMP_PATH = path.join(VIRTUAL_DISK, 'screen.dump')
class RoleEnum(enum.Enum):
AMI = 'ami'
LIKA = 'lika'
ALDER = 'alder'
LSebas_A4 = 'lsa4'
Benandark = 'benandark'
class TicketEnum(enum.Enum):
GREEN = 'green'
RED = 'red'
| 26.538462
| 107
| 0.677295
|
4a0a6f59c2e65ce084a10ae6de819c47203d461a
| 2,289
|
py
|
Python
|
petra/call.py
|
StanfordLegion/petra
|
5e2c41ccc78afb0ecec62c54846739ea923e3e40
|
[
"Apache-2.0"
] | null | null | null |
petra/call.py
|
StanfordLegion/petra
|
5e2c41ccc78afb0ecec62c54846739ea923e3e40
|
[
"Apache-2.0"
] | null | null | null |
petra/call.py
|
StanfordLegion/petra
|
5e2c41ccc78afb0ecec62c54846739ea923e3e40
|
[
"Apache-2.0"
] | 1
|
2020-04-13T20:12:26.000Z
|
2020-04-13T20:12:26.000Z
|
"""
This file defines Petra function call expressions and statements.
"""
import re
from llvmlite import ir
from typing import List, Optional, Tuple, Union
from .codegen import CodegenContext
from .expr import Expr
from .statement import Statement
from .validate import ValidateError
from .type import Type
from .typecheck import TypeContext, TypeCheckError
class Call(Expr):
"""
A function call expression.
"""
def __init__(self, name: str, args: List[Expr]):
self.name = name
self.args = args
self.t: Union[Tuple[()], Optional[Type]] = None
self.validate()
def get_type(self) -> Type:
if isinstance(self.t, Type):
return self.t
if self.t == ():
raise TypeCheckError("Attempted to use Call statement as expression")
raise Exception("Expected type to exist - was typecheck called?")
def validate(self) -> None:
if not re.match(r"^[a-z][a-zA-Z0-9_]*$", self.name):
raise ValidateError(
"Function call to '%s' does not match regex "
"^[a-z][a-zA-Z0-9_]*$" % self.name
)
def typecheck(self, ctx: TypeContext) -> None:
# check existence of name
if self.name not in ctx.functypes:
raise TypeCheckError("Undeclared function '%s'" % self.name)
(t_in, t_out) = ctx.functypes[self.name]
# check argument types
if len(self.args) != len(t_in):
raise TypeCheckError(
"Function call to '%s' expects %s arguments, not %s"
% (self.name, len(t_in), len(self.args))
)
for i, arg in enumerate(self.args):
arg.typecheck(ctx)
if arg.get_type() != t_in[i]:
raise TypeCheckError(
"Argument %s of call to '%s' should be of type"
"%s, not %s" % (i, self.name, str(t_in[i]), str(arg.get_type()))
)
self.t = t_out
def codegen(self, builder: ir.IRBuilder, ctx: CodegenContext) -> ir.Value:
def codegen_arg(arg: Expr) -> ir.Value:
return arg.codegen(builder, ctx)
args = tuple(map(codegen_arg, self.args))
func = ctx.funcs[self.name]
return builder.call(func, args)
| 32.7
| 84
| 0.580603
|
4a0a6f96d6061042e04dbcfa58760cb0ef283cd6
| 1,350
|
py
|
Python
|
var/spack/repos/builtin/packages/r-geometry/package.py
|
renjithravindrankannath/spack
|
043b2cbb7c99d69a373f3ecbf35bc3b4638bcf85
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null |
var/spack/repos/builtin/packages/r-geometry/package.py
|
renjithravindrankannath/spack
|
043b2cbb7c99d69a373f3ecbf35bc3b4638bcf85
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null |
var/spack/repos/builtin/packages/r-geometry/package.py
|
renjithravindrankannath/spack
|
043b2cbb7c99d69a373f3ecbf35bc3b4638bcf85
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 2
|
2019-02-08T20:37:20.000Z
|
2019-03-31T15:19:26.000Z
|
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class RGeometry(RPackage):
"""Mesh Generation and Surface Tessellation.
Makes the 'Qhull' library <http://www.qhull.org> available in R, in a
similar manner as in Octave and MATLAB. Qhull computes convex hulls,
Delaunay triangulations, halfspace intersections about a point, Voronoi
diagrams, furthest-site Delaunay triangulations, and furthest-site Voronoi
diagrams. It runs in 2D, 3D, 4D, and higher dimensions. It implements the
Quickhull algorithm for computing the convex hull. Qhull does not support
constrained Delaunay triangulations, or mesh generation of non-convex
objects, but the package does include some R functions that allow for
this."""
cran = "geometry"
version('0.4.6', sha256='910465a8c8043faca73bcc7c81c9249b9938677ee6649468003b438a6503f5d8')
depends_on('r@3.0.0:', type=('build', 'run'))
depends_on('r-magic', type=('build', 'run'))
depends_on('r-rcpp', type=('build', 'run'))
depends_on('r-lpsolve', type=('build', 'run'))
depends_on('r-linprog', type=('build', 'run'))
depends_on('r-rcppprogress', type=('build', 'run'))
| 42.1875
| 95
| 0.720741
|
4a0a70257d3ae187247a0b8eb3383afd8b0eb4ef
| 7,852
|
py
|
Python
|
flexassist/integrations/tensorflow/trainer.py
|
akamlani/flexassist-core
|
662f2c8c24a625e094362a43a74e8e2d37719b98
|
[
"MIT"
] | null | null | null |
flexassist/integrations/tensorflow/trainer.py
|
akamlani/flexassist-core
|
662f2c8c24a625e094362a43a74e8e2d37719b98
|
[
"MIT"
] | null | null | null |
flexassist/integrations/tensorflow/trainer.py
|
akamlani/flexassist-core
|
662f2c8c24a625e094362a43a74e8e2d37719b98
|
[
"MIT"
] | null | null | null |
import numpy as np
import pandas as pd
import datetime
from typing import List
from pathlib import Path
from dataclasses import dataclass, asdict, is_dataclass
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras.layers as layers
import tensorflow.keras.models as models
import tensorflow.keras.optimizers as opt
import tensorflow.keras.losses as losses
import tensorflow.keras.metrics as metrics # Metrics
import tensorflow.keras.callbacks as callbacks # LambdaCallback
import wandb
from wandb.keras import WandbCallback
@dataclass
class TrainingConfig:
"training parameters"
loss:str
metrics:List[str]
num_epochs:int = 10
batch_size:int = 32
learning_rate:float = 5e-4
patience:int = 3 # number of epochs of which no improve in training for ES to be stopped
validation_split:int = 0.2
momentum:float = 0.99
verbosity:int = 0
@dataclass
class ExperimentConfig:
"configuration paths for model training"
tensorboard_dir:str
model_dir:str
checkpoint_dir:str
figures_dir:str
class LogCallback(callbacks.Callback):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def on_epoch_end(self, epoch:int, logs:dict=None):
from sklearn.metrics import r2_score
keys = list(logs.keys())
metrics_dict = dict(
epoch = epoch
)
print("End epoch {} of training; got log keys: {}".format(epoch, keys))
#wandb.log({'r2_score': r2_score})
class Trainer(object):
def __init__(self, training_config:dict, cxt=None):
def populate(data:dict, subset:dict) -> dict:
"""used to filter and populate information to a dataclass
Examples:
data_dict = populate(training_config['paths'], PathConfig.__annotations__)
PathConfig(**data_dict)
"""
return {k:v for k, v in data.items() if k in subset}
# populate internal data structure
self.training_params = TrainingConfig(**populate(training_config['training_parameters'], TrainingConfig.__annotations__ ))
self.experiment_params = ExperimentConfig(**populate(training_config['experiment_parameters'], ExperimentConfig.__annotations__ ))
# context runner for wandb
self.cxt = None
def train(self, model_name:str, model, train, validation, **kwargs) -> tuple:
"encapsulation function to train and save the model"
model = self.compile(model)
model, df_history = self.fit(model_name, model, train, validation, **kwargs)
# save the model to directory
model_path = str(Path(self.experiment_params.model_dir)/model_name)
self.save(model, model_path, format='tf')
# save the model figure architecture
fig_filename = model_name + '.png'
fig_path = str(Path(self.experiment_params.figures_dir)/fig_filename)
self.save_architecture(model, filename=fig_path)
return model, df_history
def compile(self, model):
"compile the architecture with the ability to extract model.suammary"
model.compile(
optimizer = opt.Adam(float(self.training_params.learning_rate)),
# extend to a dict of losses for multi-output
loss = self.training_params.loss,
metrics = self.training_params.metrics
)
return model
def fit(self, model_name:str, model, train, validation, **kwargs):
"""fit and train the model with training data"""
# instantiate callbacks
tb_log_dir = self.experiment_params.tensorboard_dir
tb_log_dir = str(Path(tb_log_dir)/datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
writer = tf.summary.create_file_writer(tb_log_dir)
model_filename = '-'.join([f'model.{model_name}', '{epoch:02d}-{val_loss:.2f}.h5'])
model_path = str(Path(self.experiment_params.checkpoint_dir)/model_filename)
callbacks_lst = [
#tolerance for convergence training over epochs
callbacks.EarlyStopping(monitor = 'val_loss',
mode = 'min',
patience = self.training_params.patience,
min_delta = 1e-3),
# tensorboard
callbacks.TensorBoard(log_dir=tb_log_dir),
]
if kwargs.get('cb_ckpt', False):
# only saving the best checkpoints
callbacks_lst.append( callbacks.ModelCheckpoint(model_path, save_freq ='epoch', save_best_only=False) )
if kwargs.get('cb_wandb', False):
callbacks_lst.append(
WandbCallback(
monitor = 'val_loss',
training_data = validation,
# when training and validation are tf.data.Dataset, can just use the length
validation_steps = len(validation),
log_weights=True,
log_evaluation=True,
#log_gradients=True,
)
)
if kwargs.get('cb_logger', True):
callbacks_lst.append(LogCallback())
# assumes inputs are datasets, equivalent to the following:
# steps_per_epoch = TotalTrainingSamples / TrainingBatchSize
# validation_steps = TotalvalidationSamples / ValidationBatchSize
history = model.fit(train,
validation_data = validation,
# when training and validation are tf.data.Dataset, can just use the length
steps_per_epoch = len(train),
validation_steps = len(validation),
epochs = self.training_params.num_epochs,
batch_size = self.training_params.batch_size,
callbacks = callbacks_lst,
use_multiprocessing = True)
df_history = pd.DataFrame(history.history)
return model, df_history
def load(self, export_path:str):
"""load an existing serialized model
Examples:
>>> .load(self.training_config.model_export_path)
"""
model = models.load_model(export_path)
return model
def save(self, model, export_path:str, format:str='tf'):
"""serialize a model to a given path
._save(model, export_path)
"""
model.save(export_path, save_format=format)
def save_architecture(self, model, filename:str, **kwargs):
"""save model architecture diagram to a file
Examples
>>> model.summary()
>>> .save_architecture(model, filename='./exports/models/model_arch.png')
"""
Path(filename).parent.mkdir(parents=True, exist_ok=True)
params = dict(show_layer_names=True, show_shapes=True, show_dtype=True, rankdir="TB")
# for subclassing: using model.build_graph() to return new model
return keras.utils.plot_model(model.build_graph(), to_file=filename, **params)
def _evaluate(self, model, X, y, batch_size:int):
yhat = model.predict(X)
loss, accuracy = model.evaluate(X, y, batch_size=batch_size, verbose=2)
error_rate = round((1 - accuracy) * 100, 2)
# (1) Global Partition Metrics (2) Per Class Distribution Metrics
metrics = {'accuracy': accuracy, 'loss': loss, 'error_rate': error_rate}
# separate into delayed commits
wandb.log(metrics, commit=False)
wandb.log()
# run.join()
| 41.765957
| 138
| 0.608507
|
4a0a7076dd42cdc64a23b514d06ad07dbb42bfd5
| 19,671
|
py
|
Python
|
application/views/ride_views.py
|
meshack-mbuvi/ride-my-way-api
|
2e091f020e774cad4891427a2de91a7a2c29def1
|
[
"MIT"
] | null | null | null |
application/views/ride_views.py
|
meshack-mbuvi/ride-my-way-api
|
2e091f020e774cad4891427a2de91a7a2c29def1
|
[
"MIT"
] | 19
|
2018-06-23T17:08:37.000Z
|
2018-07-23T17:37:55.000Z
|
application/views/ride_views.py
|
meshack-mbuvi/ride-my-way-api
|
2e091f020e774cad4891427a2de91a7a2c29def1
|
[
"MIT"
] | null | null | null |
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_restplus import Resource, Namespace, fields
from flask import request, jsonify
from datetime import datetime
from application.models.ride_models import RideOffer
from application import db
api = Namespace('Ride offers', Description='Operations on Rides')
ride = api.model('Ride offer', {
'start point': fields.String(description='location of the driver'),
'destination': fields.String(description='end-point of the journey'),
'route': fields.String(description='ordered roads driver is going \
to use'),
'start time': fields.DateTime(dt_format='iso8601',
description='Format:(Year Month Day Hr:MinAM/PM). time \
driver starts the ride.'),
'available space': fields.Integer(
description='available space for passengers')
})
def past_date(date_string):
"""checks whether date given is a past date
:returns True for past date, False otherwise."""
try:
str_to_date = datetime.strptime(date_string, "%Y-%m-%d %H:%M").date()
if str_to_date > datetime.now().date():
return False
return True
except Exception as e:
# catch invalid date format
print(e)
return {'message':
'use correct format for date and time.'}, 400
def convert_date(date_string):
""":Returns
: start_time(str) a string representation for time is successful"""
try:
date = datetime.strptime(date_string, '%Y-%m-%d %H:%M')
startTime = datetime.strftime(date, '%Y-%m-%d %H:%M')
return startTime
except Exception as e:
print(e)
return {'message':
'use correct format for date and time.'}, 400
class Rides(Resource):
@api.doc(responses={'message': 'ride offer added successfully.',
201: 'Created', 400: 'BAD FORMAT',
401: 'UNAUTHORIZED'})
@api.expect(ride)
@jwt_required
def post(self):
"""Creates a new ride offer"""
data = request.get_json()
current_user_email = get_jwt_identity()
# Check whether there is data
if any(data):
# save ride to data structure
if not isinstance(data['available space'], int):
return {'message': 'available space can only be numbers.'}, 400
if past_date(data['start time']) == True:
return {'message': 'Cannot create an expired ride'}, 400
query = "SELECT user_type from users where email='{}'"\
.format(current_user_email)
result = db.execute(query)
row = result.fetchone()
if row[0] == 'passenger':
return "Please upgrade your account to be a driver to access this service", 401
try:
start_time = convert_date(data['start time'])
if type(start_time) == type(str("")):
query = "SELECT * from rides where start_point='{}'\
and destination = '{}' and start_time='{}' \
and owner_id=(SELECT user_id from users \
where email='{}')" . format(data['start point'],
data['destination'],
start_time, current_user_email)
result = db.execute(query)
row = result.fetchone()
if row is None:
data['start time'] = start_time
ride_offer = RideOffer(data)
# save data here
ride_offer.save(current_user_email)
return {'message':
'ride offer added successfully.'}, 201
return {'message': 'offer exists.'}, 409
# return the error caught on datetime conversion since it is saved on variable start_time
return start_time
except Exception as e:
print(e)
return {'message': 'Request not successful'}, 500
else:
return {'message':
'make sure you provide all required fields.'}, 400
@jwt_required
def get(self):
query = "SELECT user_id from users where email='{}'".format(get_jwt_identity())
result = db.execute(query)
user = result.fetchone()
query = "SELECT *, (select count(req_id) from requests where requests.ride_id=rides.ride_id)\
from rides where rides.owner_id='{}'".format(user[0])
result = db.execute(query)
rides = result.fetchall()
if (len(rides) == 0):
return {'message': 'You do not have ride offers'}, 404
else:
return jsonify([
{'id': row[0], 'start point': row[2],
'destination': row[3], 'start_time': row[4],
'route': row[5],
'Available space': row[6],
'successful': row[7],
'request count': row[8]}
for row in rides])
@jwt_required
def put(self,ride_id):
query = "select * from rides where ride_id='{}'".format(ride_id)
result = db.execute(query)
ride = result.fetchone()
if ride is None:
return {'message': 'Offer with given id does not exist'}, 404
current_user_email = get_jwt_identity()
query = "select user_id from users where email='{}'"\
. format(current_user_email)
result = db.execute(query)
user_id = result.fetchone()
args = request.args
if len(args) > 0:
if args['action'] == 'true':
query = "update rides set successful='{}' where ride_id='{}'"\
. format(True,int(ride_id))
db.execute(query)
return {'message':'Ride marked as successful'}
else:
query = "update rides set successful='{}' where ride_id='{}'"\
. format(False,int(ride_id))
db.execute(query)
return {'message':'Ride marked as unsuccessful'}
if not ride[1] == user_id[0]:
return {'message': 'You cannot change \
details of ride offer you do not own'}, 401
data = request.get_json()
if not isinstance(data['available space'], int):
return {'message': 'available space can only be numbers.'}, 400
start_time=convert_date(data['start time'])
if type(start_time) != type(str("")):
"""time is not in the correct format"""
return start_time
if past_date(start_time) == True:
return {'message': 'Cannot create an expired ride'}, 400
query = "update rides set start_point='{}',destination='{}', start_time='{}',\
route='{}', available_space='{}' where ride_id='{}'"\
. format(data['start point'], data['destination'], data['start time'],\
data['route'], data['available space'] ,int(ride_id))
db.execute(query)
query = "select * from rides where ride_id='{}'".format(ride_id)
result = db.execute(query)
ride = result.fetchone()
return jsonify({'id': ride[0],'start point': ride[2], 'destination': ride[3],\
'start time': ride[4], 'route': ride[5], 'available seats': ride[6]})
@jwt_required
def delete(self,ride_id):
query = "select user_id from users where email='{}'".format(get_jwt_identity())
result = db.execute(query)
user_id = result.fetchone()
query = "select * from rides where ride_id='{}' and owner_id='{}'"\
.format(ride_id, user_id[0])
result = db.execute(query)
if len(result.fetchall()) > 0:
query = "delete from rides where ride_id='{}' and owner_id='{}'"\
.format(ride_id, user_id[0])
result = db.execute(query)
return {'message': 'Ride offer deleted successfully'}
else:
return {'message': 'Ride offer not found.'}, 404
class AllRides(Resource):
@api.doc('Get Available rides',
params={'ride_id': 'Id for a single ride offer'},
responses={200: 'OK', 404: 'NOT FOUND'})
@jwt_required
def get(self, ride_id=None):
query = ''
if ride_id is None:
query = "SELECT * from rides"
else:
query = "SELECT * from rides where ride_id = {}"\
. format(ride_id)
offer_filter = request.args
if len(offer_filter) > 0:
search_key = offer_filter['key']
search_value = offer_filter['{}'.format(search_key)]
query = "SELECT * from rides where {}='{}'".format(search_key, search_value)
try:
result = db.execute(query)
rows = result.fetchall()
if (len(rows) == 0) and (ride_id is not None):
# This works when user retrieves a single ride offer
return {'message': 'Offer not found'}, 404
return jsonify([
{'id': row[0], 'start point': row[2],
'destination': row[3], 'start_time': row[4],
'route': row[5],
'available space': row[6]}
for row in rows])
except Exception as e:
return {'message': 'Request not successful'}, 500
class JoinRide(Resource):
@api.doc('Request to join a ride offer',
params={'ride_id': 'Id for offer to join'},
responses={201: 'Created', 404: 'NOT FOUND', 403: 'EXPIRED'})
@jwt_required
def post(self, ride_id):
"""Sends user request to join a ride offer"""
try:
# sample user
current_user_email = get_jwt_identity()
# Get user ID
query = "SELECT users.user_id \
from users where email='{}'"\
. format(current_user_email)
result = db.execute(query)
user_row = result.fetchone()
if user_row is None:
return {'message': 'User not found'}, 404
user_id = user_row[0]
# Find the particular ride offer to check its availability
query = "SELECT * from rides where ride_id = '{}'" . format(
ride_id)
result = db.execute(query)
row = result.fetchone()
if row is None:
return {'message': 'That ride does not exist'}, 404
# check whether this ride offer belongs to the user
if user_id == row[1]:
return {'message':
'You cannot request to join your own offer'}, 403
request_data = request.get_json()
if 'pick-up point' not in request_data or 'drop-off point' not in request_data or\
'seats_booked' not in request_data:
return {'message': 'provide pick-up and drop-off points, and number of seats you want to book. '}, 400
pick_up = request_data['pick-up point']
drop_off = request_data['drop-off point']
seats_booked = request_data['seats_booked']
status = 'pending'
# # check whether ride offer has any remaining space
if row[6] < seats_booked:
return {'message': 'No available space for you.'}, 403
# check whether ride offer is expired
time = (row[4])
if time > datetime.now():
# check whether users has alread requested given ride offer
query = "SELECT * from requests where user_id = (SELECT users.user_id \
from users where email='{}') and ride_id = {}"\
. format(current_user_email, ride_id)
result = db.execute(query)
result = result.fetchone()
if result is None:
# save user requests now
query = "INSERT INTO requests (date_created, ride_id, user_id, pick_up_point,\
drop_off_point, seats_booked, status)\
values('{}', '{}', '{}', '{}', '{}', '{}', '{}')"\
. format(datetime.now(), ride_id, user_id, pick_up, drop_off, \
seats_booked, status)
db.execute(query)
return {'message': 'Your request has been recorded.'}, 201
# user has already requested to join this ride offer
return{'message': 'You already requested this ride.'}, 403
else:
return {'message':
'The ride requested has already expired'}, 403
except Exception as e:
print(e)
return {'message': 'Request not successful.'}, 500
class Requests(Resource):
@api.doc('view user requests to a given ride offer',
responses={200: 'OK', 404: 'NOT FOUND', 401: 'UNAUTHORIZED'},
params={'ride_id': 'Id for ride user wants to view'})
@jwt_required
def get(self, ride_id=""):
"""Retrieves all requests to a given ride"""
try:
# get owner id
query = "SELECT user_id from users where email='{}'"\
.format(get_jwt_identity()
)
result = db.execute(query)
row = result.fetchone()
owner_id = row[0]
if ride_id =="":
# Retrieve user request history
query = "SELECT * from requests where user_id='{}'".format(owner_id)
result = db.execute(query)
rows = result.fetchall()
if len(rows) > 0:
return jsonify([{'Request Id':row[0],'Date Requested': row[1],
'pick up point': row[4],
'drop-off point': row[5],
'seats booked': row[6],
'status': row[7]} for row in rows])
return {'message': "There is no request to your ride offer."}, 404
else:
query = "SELECT firstname,phone,pick_up_point,drop_off_point, seats_booked, \
start_time,status, req_id from users INNER JOIN requests \
ON requests.user_id = users.user_id INNER JOIN \
rides on rides.ride_id = '{}' where requests.ride_id = '{}'" \
. format(ride_id, ride_id)
result = db.execute(query)
rows = result.fetchall()
if len(rows) > 0:
return jsonify([{'Request Id':row[7],'name of user': row[0], 'user phone contact': row[1],
'pick up point': row[2],
'drop-off point': row[3],
'seats booked': row[4],
'start time': row[5],
'status': row[6]} for row in rows])
return {'message': "There is no request to your ride offer."}, 404
except Exception as e: return e, 500
@jwt_required
def put(self, request_id):
"""Driver can accept or reject the ride offer.And users can take an accepted request"""
try:
action = request.args['action']
response = ''
# check whether driver already accepted the offer.
query = "select status,seats_booked,ride_id from requests where\
req_id='{}'".format(request_id)
result = db.execute(query)
result_rows = result.fetchone()
query = "select available_space from rides where ride_id='{}'"\
.format((result_rows[2]))
result = db.execute(query)
seats = result.fetchone()
available_seats = seats[0]
print(action)
if action.lower() == 'taken':
query = "update requests set status='{}' where requests.req_id='{}'"\
. format('taken', int(request_id))
db.execute(query)
return {'message': 'Your request has been updated.'}
elif action.lower() == 'abandoned':
query = "update requests set status='{}' where requests.req_id='{}'"\
. format('abadoned', int(request_id))
db.execute(query)
return {'message': 'Your request has been updated.'}
# check for action to take
elif action.lower() == 'accept':
if result_rows[0] == 'accepted':
return {'message': 'You already accepted this user request'},403
action = 'accepted'
# Decrement the available seats by one
available_seats -= result_rows[1]
# set message to be returned to user after request update cycle
response = {'message': 'Request accepted'}
else:
# Reject an already accepted request; this means available seats should be incremented
if result_rows[0] == 'accepted' :
available_seats += result_rows[1]
response = {'message': 'Request canceled'}
action = 'canceled'
elif result_rows[0] == 'rejected':
return {'message': 'Request already rejected'}
elif result_rows[0] == 'taken':
return {'message': 'Reuest which is already taken cannot be modified.'}
else:
action = 'rejected'
response = {'message': 'Request rejected'}
query = "update requests set status='{}' where requests.req_id='{}'" \
. format(action, int(request_id))
db.execute(query)
query = "update rides set available_space='{}' where ride_id='{}'"\
.format(int(available_seats), result_rows[2])
db.execute(query)
return response
except Exception as e: return e, 500
@jwt_required
def delete(self, request_id):
query = "select user_id from users where email='{}'".format(get_jwt_identity())
result = db.execute(query)
user_id = result.fetchone()
query = "select * from requests where req_id='{}' and user_id='{}'"\
.format(request_id, user_id[0])
result = db.execute(query)
if len(result.fetchall()) > 0:
query = "delete from requests where req_id='{}' and user_id='{}'"\
.format(request_id, user_id[0])
result = db.execute(query)
return {'message': 'Your request has been deleted.'}
else:
return {'message': 'Request not found.'}, 404
api.add_resource(Rides, '/users/rides', '/users/rides/<ride_id>')
api.add_resource(AllRides, '/rides', '/rides/<string:ride_id>')
api.add_resource(JoinRide, '/rides/<ride_id>/requests')
api.add_resource(Requests, '/users/rides/requests', '/users/rides/<ride_id>/requests', '/users/rides/requests/<request_id>')
| 44.006711
| 124
| 0.522444
|
4a0a7095f55bf6f8fe165c7a4b59e9e543d4e6d4
| 6,208
|
py
|
Python
|
external/devlib/devlib/instrument/acmecape.py
|
qais-yousef/lisa
|
8343e26bf0565589928a69ccbe67b1be03403db7
|
[
"Apache-2.0"
] | 159
|
2016-01-25T11:08:39.000Z
|
2022-03-28T05:20:41.000Z
|
external/devlib/devlib/instrument/acmecape.py
|
qais-yousef/lisa
|
8343e26bf0565589928a69ccbe67b1be03403db7
|
[
"Apache-2.0"
] | 656
|
2016-01-25T11:16:56.000Z
|
2022-03-23T16:03:28.000Z
|
external/devlib/devlib/instrument/acmecape.py
|
qais-yousef/lisa
|
8343e26bf0565589928a69ccbe67b1be03403db7
|
[
"Apache-2.0"
] | 116
|
2016-01-25T12:06:31.000Z
|
2022-03-28T08:43:28.000Z
|
# Copyright 2018 ARM Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
#
#pylint: disable=attribute-defined-outside-init
from __future__ import division
import os
import sys
import time
import tempfile
import shlex
from fcntl import fcntl, F_GETFL, F_SETFL
from string import Template
from subprocess import Popen, PIPE, STDOUT
from pipes import quote
from devlib import Instrument, CONTINUOUS, MeasurementsCsv
from devlib.exception import HostError
from devlib.utils.csvutil import csvreader, csvwriter
from devlib.utils.misc import which
OUTPUT_CAPTURE_FILE = 'acme-cape.csv'
IIOCAP_CMD_TEMPLATE = Template("""
${iio_capture} -n ${host} -b ${buffer_size} -c -f ${outfile} ${iio_device}
""")
def _read_nonblock(pipe, size=1024):
fd = pipe.fileno()
flags = fcntl(fd, F_GETFL)
flags |= os.O_NONBLOCK
fcntl(fd, F_SETFL, flags)
output = ''
try:
while True:
output += pipe.read(size)
except IOError:
pass
return output
class AcmeCapeInstrument(Instrument):
mode = CONTINUOUS
def __init__(self, target,
iio_capture=which('iio-capture'),
host='baylibre-acme.local',
iio_device='iio:device0',
buffer_size=256,
keep_raw=False):
super(AcmeCapeInstrument, self).__init__(target)
self.iio_capture = iio_capture
self.host = host
self.iio_device = iio_device
self.buffer_size = buffer_size
self.keep_raw = keep_raw
self.sample_rate_hz = 100
if self.iio_capture is None:
raise HostError('Missing iio-capture binary')
self.command = None
self.process = None
self.add_channel('shunt', 'voltage')
self.add_channel('bus', 'voltage')
self.add_channel('device', 'power')
self.add_channel('device', 'current')
self.add_channel('timestamp', 'time_ms')
def __del__(self):
if self.process and self.process.pid:
self.logger.warning('killing iio-capture process [{}]...'.format(self.process.pid))
self.process.kill()
def reset(self, sites=None, kinds=None, channels=None):
super(AcmeCapeInstrument, self).reset(sites, kinds, channels)
self.raw_data_file = tempfile.mkstemp('.csv')[1]
params = dict(
iio_capture=self.iio_capture,
host=self.host,
# This must be a string for quote()
buffer_size=str(self.buffer_size),
iio_device=self.iio_device,
outfile=self.raw_data_file
)
params = {k: quote(v) for k, v in params.items()}
self.command = IIOCAP_CMD_TEMPLATE.substitute(**params)
self.logger.debug('ACME cape command: {}'.format(self.command))
def start(self):
self.process = Popen(shlex.split(self.command), stdout=PIPE, stderr=STDOUT)
def stop(self):
self.process.terminate()
timeout_secs = 10
output = ''
for _ in range(timeout_secs):
if self.process.poll() is not None:
break
time.sleep(1)
else:
output += _read_nonblock(self.process.stdout)
self.process.kill()
self.logger.error('iio-capture did not terminate gracefully')
if self.process.poll() is None:
msg = 'Could not terminate iio-capture:\n{}'
raise HostError(msg.format(output))
if self.process.returncode != 15: # iio-capture exits with 15 when killed
if sys.version_info[0] == 3:
output += self.process.stdout.read().decode(sys.stdout.encoding or 'utf-8', 'replace')
else:
output += self.process.stdout.read()
self.logger.info('ACME instrument encountered an error, '
'you may want to try rebooting the ACME device:\n'
' ssh root@{} reboot'.format(self.host))
raise HostError('iio-capture exited with an error ({}), output:\n{}'
.format(self.process.returncode, output))
if not os.path.isfile(self.raw_data_file):
raise HostError('Output CSV not generated.')
self.process = None
def get_data(self, outfile):
if os.stat(self.raw_data_file).st_size == 0:
self.logger.warning('"{}" appears to be empty'.format(self.raw_data_file))
return
all_channels = [c.label for c in self.list_channels()]
active_channels = [c.label for c in self.active_channels]
active_indexes = [all_channels.index(ac) for ac in active_channels]
with csvreader(self.raw_data_file, skipinitialspace=True) as reader:
with csvwriter(outfile) as writer:
writer.writerow(active_channels)
header = next(reader)
ts_index = header.index('timestamp ms')
for row in reader:
output_row = []
for i in active_indexes:
if i == ts_index:
# Leave time in ms
output_row.append(float(row[i]))
else:
# Convert rest into standard units.
output_row.append(float(row[i])/1000)
writer.writerow(output_row)
return MeasurementsCsv(outfile, self.active_channels, self.sample_rate_hz)
def get_raw(self):
return [self.raw_data_file]
def teardown(self):
if not self.keep_raw:
if os.path.isfile(self.raw_data_file):
os.remove(self.raw_data_file)
| 36.733728
| 102
| 0.610019
|
4a0a7193506a334a76d23b92f1e5c986e4708076
| 1,146
|
py
|
Python
|
Django-E-Commerce/product/views.py
|
muhammadkashifdotcom/easywear
|
370981e77129bb027b6dc9607a93fbb78957253c
|
[
"bzip2-1.0.6"
] | null | null | null |
Django-E-Commerce/product/views.py
|
muhammadkashifdotcom/easywear
|
370981e77129bb027b6dc9607a93fbb78957253c
|
[
"bzip2-1.0.6"
] | 7
|
2021-03-30T13:52:56.000Z
|
2022-03-12T00:38:56.000Z
|
Django-E-Commerce/product/views.py
|
muhammadkashifdotcom/easywear
|
370981e77129bb027b6dc9607a93fbb78957253c
|
[
"bzip2-1.0.6"
] | null | null | null |
from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
# Create your views here.
from product.models import CommentForm, Comment
def index(request):
return HttpResponse("My Product Page")
def addcomment(request,id):
url = request.META.get('HTTP_REFERER') # get last url
#return HttpResponse(url)
if request.method == 'POST': # check post
form = CommentForm(request.POST)
if form.is_valid():
data = Comment() # create relation with model
data.subject = form.cleaned_data['subject']
data.comment = form.cleaned_data['comment']
data.rate = form.cleaned_data['rate']
data.ip = request.META.get('REMOTE_ADDR')
data.product_id=id
current_user= request.user
data.user_id=current_user.id
data.save() # save data to table
messages.success(request, "Your review has ben sent. Thank you for your interest.")
return HttpResponseRedirect(url)
return HttpResponseRedirect(url)
def colors(request):
return render(request,'product_color.html')
| 32.742857
| 92
| 0.691972
|
4a0a7217f0fc1af9c525db5517d74bfe6def58eb
| 208
|
py
|
Python
|
476_numberComplement.py
|
stuti-rastogi/leetcode-python-solutions
|
73593fe642a06a83cde974ba5e6de3a7b396ec84
|
[
"MIT"
] | 4
|
2018-07-24T08:36:42.000Z
|
2019-08-25T17:48:47.000Z
|
476_numberComplement.py
|
stuti-rastogi/leetcodesolutions
|
73593fe642a06a83cde974ba5e6de3a7b396ec84
|
[
"MIT"
] | null | null | null |
476_numberComplement.py
|
stuti-rastogi/leetcodesolutions
|
73593fe642a06a83cde974ba5e6de3a7b396ec84
|
[
"MIT"
] | null | null | null |
class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i = 1
while i <= num:
i = i << 1
return (i - 1) ^ num
| 20.8
| 34
| 0.384615
|
4a0a72f059c8f0ace355277c3a88dafe8ff1f000
| 443
|
py
|
Python
|
ABC/199/c.py
|
buchi1002/AtCoder
|
e678a8a1f0edb3eab922ee5f65f6742791c231b3
|
[
"MIT"
] | null | null | null |
ABC/199/c.py
|
buchi1002/AtCoder
|
e678a8a1f0edb3eab922ee5f65f6742791c231b3
|
[
"MIT"
] | null | null | null |
ABC/199/c.py
|
buchi1002/AtCoder
|
e678a8a1f0edb3eab922ee5f65f6742791c231b3
|
[
"MIT"
] | null | null | null |
def main():
# input
N = int(input())
S = str(input())
Q = int(input())
# compute
Ts = [i for i in range(2*N)]
for i in range(Q):
T, A, B = map(int, input().split())
if T == 1:
Ts[A-1], Ts[B-1] = Ts[B-1], Ts[A-1]
else:
Ts = Ts[N:] + Ts[:N]
# output
for i in range(2*N):
print(S[Ts[i]], end = "")
if __name__ == '__main__':
main()
| 23.315789
| 48
| 0.401806
|
4a0a7548c84ed07d820a1febf2dc65642268485f
| 1,537
|
py
|
Python
|
render_functions.py
|
BarbaAlGhul/advanced-calaboucos-e-cachorros
|
66dbc7c903d130b533680eb2afea876af83db29e
|
[
"MIT"
] | null | null | null |
render_functions.py
|
BarbaAlGhul/advanced-calaboucos-e-cachorros
|
66dbc7c903d130b533680eb2afea876af83db29e
|
[
"MIT"
] | null | null | null |
render_functions.py
|
BarbaAlGhul/advanced-calaboucos-e-cachorros
|
66dbc7c903d130b533680eb2afea876af83db29e
|
[
"MIT"
] | null | null | null |
from __future__ import annotations
from typing import Tuple, TYPE_CHECKING
import color
if TYPE_CHECKING:
from tcod import Console
from engine import Engine
from game_map import GameMap
def get_names_at_location(x: int, y:int, game_map: GameMap) -> str:
if not game_map.in_bounds(x, y) or not game_map.visible[x, y]:
return ""
names = ", ".join(
entity.name for entity in game_map.entities if entity.x == x and entity.y == y
)
return names.capitalize()
def render_bar(
console: Console, current_value: int, maximum_value: int, total_width: int
) -> None:
bar_width = int(float(current_value) / maximum_value * total_width)
console.draw_rect(x=0, y=45, width=20, height=1, ch=1, bg=color.bar_empty)
if bar_width > 0:
console.draw_rect(
x=0, y=45, width=bar_width, height=1, ch=1, bg=color.bar_filled
)
console.print(
x=1, y=45, string=f"HP: {current_value}/{maximum_value}", fg=color.bar_text
)
def render_dungeon_level(
console: Console, dungeon_level: int, location: Tuple[int, int]
) -> None:
x, y = location
console.print(x=x, y=y, string=f"Dungeon level: {dungeon_level}")
def render_names_at_mouse_location(
console: Console, x: int, y: int, engine: Engine
) -> None:
mouse_x, mouse_y = engine.mouse_location
names_at_mouse_location = get_names_at_location(
x=mouse_x, y=mouse_y, game_map=engine.game_map
)
console.print(x=x, y=y, string=names_at_mouse_location)
| 26.964912
| 86
| 0.677293
|
4a0a755d23cc7749d40344a935c93d785b796c14
| 4,307
|
py
|
Python
|
huaweicloud-sdk-servicestage/huaweicloudsdkservicestage/v2/model/create_hook_response.py
|
huaweicloud/huaweicloud-sdk-python-v3
|
7a6270390fcbf192b3882bf763e7016e6026ef78
|
[
"Apache-2.0"
] | 64
|
2020-06-12T07:05:07.000Z
|
2022-03-30T03:32:50.000Z
|
huaweicloud-sdk-servicestage/huaweicloudsdkservicestage/v2/model/create_hook_response.py
|
huaweicloud/huaweicloud-sdk-python-v3
|
7a6270390fcbf192b3882bf763e7016e6026ef78
|
[
"Apache-2.0"
] | 11
|
2020-07-06T07:56:54.000Z
|
2022-01-11T11:14:40.000Z
|
huaweicloud-sdk-servicestage/huaweicloudsdkservicestage/v2/model/create_hook_response.py
|
huaweicloud/huaweicloud-sdk-python-v3
|
7a6270390fcbf192b3882bf763e7016e6026ef78
|
[
"Apache-2.0"
] | 24
|
2020-06-08T11:42:13.000Z
|
2022-03-04T06:44:08.000Z
|
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class CreateHookResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'id': 'str',
'type': 'str',
'callback_url': 'str'
}
attribute_map = {
'id': 'id',
'type': 'type',
'callback_url': 'callback_url'
}
def __init__(self, id=None, type=None, callback_url=None):
"""CreateHookResponse - a model defined in huaweicloud sdk"""
super(CreateHookResponse, self).__init__()
self._id = None
self._type = None
self._callback_url = None
self.discriminator = None
if id is not None:
self.id = id
if type is not None:
self.type = type
if callback_url is not None:
self.callback_url = callback_url
@property
def id(self):
"""Gets the id of this CreateHookResponse.
hook ID。
:return: The id of this CreateHookResponse.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""Sets the id of this CreateHookResponse.
hook ID。
:param id: The id of this CreateHookResponse.
:type: str
"""
self._id = id
@property
def type(self):
"""Gets the type of this CreateHookResponse.
hook类型。
:return: The type of this CreateHookResponse.
:rtype: str
"""
return self._type
@type.setter
def type(self, type):
"""Sets the type of this CreateHookResponse.
hook类型。
:param type: The type of this CreateHookResponse.
:type: str
"""
self._type = type
@property
def callback_url(self):
"""Gets the callback_url of this CreateHookResponse.
回滚URL。
:return: The callback_url of this CreateHookResponse.
:rtype: str
"""
return self._callback_url
@callback_url.setter
def callback_url(self, callback_url):
"""Sets the callback_url of this CreateHookResponse.
回滚URL。
:param callback_url: The callback_url of this CreateHookResponse.
:type: str
"""
self._callback_url = callback_url
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, CreateHookResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 25.485207
| 79
| 0.550035
|
4a0a77bc4d8f95da5807a9a0acc2a06d3c707b97
| 3,321
|
py
|
Python
|
support_files/scraping/entries/proj_1959/proj_1959/settings.py
|
miccaldas/new_rss
|
9580887ac44b5c3e4c4ed5045478f2c7fef36afe
|
[
"MIT"
] | null | null | null |
support_files/scraping/entries/proj_1959/proj_1959/settings.py
|
miccaldas/new_rss
|
9580887ac44b5c3e4c4ed5045478f2c7fef36afe
|
[
"MIT"
] | null | null | null |
support_files/scraping/entries/proj_1959/proj_1959/settings.py
|
miccaldas/new_rss
|
9580887ac44b5c3e4c4ed5045478f2c7fef36afe
|
[
"MIT"
] | null | null | null |
# Scrapy settings for proj_1959 project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
BOT_NAME = 'proj_1959'
SPIDER_MODULES = ['proj_1959.spiders']
NEWSPIDER_MODULE = 'proj_1959.spiders'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'proj_1959 (+http://www.yourdomain.com)'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
#COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False
# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
#}
# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
# 'proj_1959.middlewares.Proj1959SpiderMiddleware': 543,
#}
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
# 'proj_1959.middlewares.Proj1959DownloaderMiddleware': 543,
#}
# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
# 'scrapy.extensions.telnet.TelnetConsole': None,
#}
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'proj_1959.pipelines.Proj1959Pipeline': 300,
#}
# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
ITEM_PIPELINES = {'scrapy.pipelines.images.ImagesPipeline': 1}
IMAGES_STORE = 'proj_1959/imgs'
FEED_EXPORT_FIELDS = ["title", "links", "content", "images", "image_urls"]
IMAGES_URLS_FIELD = "image_urls"
IMAGES_RESULT_FIELD = "images"
| 35.329787
| 103
| 0.777176
|
4a0a7830f0d532d972aa672aeace24158a251e8a
| 2,260
|
py
|
Python
|
about_arrow.py
|
jonathadv/python-libs-playground
|
233f3a70d1f66951fb3436782f3e85b7191d7bc9
|
[
"MIT"
] | null | null | null |
about_arrow.py
|
jonathadv/python-libs-playground
|
233f3a70d1f66951fb3436782f3e85b7191d7bc9
|
[
"MIT"
] | null | null | null |
about_arrow.py
|
jonathadv/python-libs-playground
|
233f3a70d1f66951fb3436782f3e85b7191d7bc9
|
[
"MIT"
] | null | null | null |
"""
# Arrow: Better dates & times for Python
Arrow is a Python library that offers a sensible and human-friendly approach
to creating, manipulating, formatting and converting dates, times and timestamps.
It implements and updates the datetime type, plugging gaps in functionality and
providing an intelligent module API that supports many common creation scenarios.
Simply put, it helps you work with dates and times with fewer imports and a lot less code.
Arrow is named after the arrow of time and is heavily inspired by moment.js and requests.
source: https://arrow.readthedocs.io/en/latest/
"""
import arrow
def arrow_date():
now_local = arrow.now()
print(f"{now_local=}")
now_utc = arrow.utcnow()
print(f"{now_utc=}")
now_utc_minus_one_hour = now_utc.shift(hours=-1)
print(f"{now_utc_minus_one_hour=}")
now_us_new_your = now_utc.to("America/New_York")
print(f"{now_us_new_your=}")
def arrow_date_parsing():
yyyy_mm_dd_parsed_date = arrow.get("2021-01-22")
print(f"{yyyy_mm_dd_parsed_date=}")
mm_yyyy_dd_parsed_date = arrow.get("01-2021-22", "MM-YYYY-DD")
print(f"{mm_yyyy_dd_parsed_date=}")
mm_yy_dd_parsed_date = arrow.get("01-21-22", "MM-YY-DD")
print(f"{mm_yy_dd_parsed_date=}")
yyyy_mm_dd_parsed_to_datetime = arrow.get("2021-01-22").datetime
print(f"{yyyy_mm_dd_parsed_to_datetime=}")
def arrow_properties():
now = arrow.now()
print(f"{now=}")
print(f"now.naive: {now.naive}")
print(f"now.tzinfo: {now.tzinfo}")
print(f"now.year: {now.year}")
print(f"now.month: {now.month}")
print(f"now.day: {now.day}")
def arrow_humanize():
now = arrow.now()
print(f"now.humanize(): {now.humanize()}")
past = now.shift(hours=-1)
print(f"past.humanize(): {past.humanize()}")
past2 = now.shift(minutes=-30)
print(f"past2.humanize(): {past2.humanize()}")
future = now.shift(hours=1)
print(f"future.humanize(): {future.humanize()}")
future2 = now.shift(minutes=30)
print(f"future2.humanize(): {future2.humanize()}")
if __name__ == "__main__":
print("-" * 20)
arrow_date()
print("-" * 20)
arrow_date_parsing()
print("-" * 20)
arrow_properties()
print("-" * 20)
arrow_humanize()
| 26.588235
| 90
| 0.676991
|
4a0a7899d03e9b3713fbfcdc4fc0a0cbba563e55
| 20,861
|
py
|
Python
|
_test/jupman_tools_test.py
|
DavidLeoni/prova-qcb
|
38520ab66b34a145e43ffb0ee808562eae31c325
|
[
"Apache-2.0"
] | null | null | null |
_test/jupman_tools_test.py
|
DavidLeoni/prova-qcb
|
38520ab66b34a145e43ffb0ee808562eae31c325
|
[
"Apache-2.0"
] | null | null | null |
_test/jupman_tools_test.py
|
DavidLeoni/prova-qcb
|
38520ab66b34a145e43ffb0ee808562eae31c325
|
[
"Apache-2.0"
] | 1
|
2021-03-21T15:20:51.000Z
|
2021-03-21T15:20:51.000Z
|
import sys
sys.path.append('../')
sys.path.append('.') # good lord, without this debugging in VSCode doesn't work
#keep it first so we don't get depreation warnings
import jupman_tools as jmt
from hypothesis import given
from pprint import pprint
from hypothesis.strategies import text
from jupman_tools import ignore_spaces, tag_regex, Jupman
import pytest
import re
from sphinx.application import Sphinx
import os
import nbformat
import time
import filecmp
import shutil
import nbsphinx
from common_test import *
import datetime
def test_detect_release():
res = jmt.detect_release()
assert res == 'dev' or len(res.split('.')) >= 2
def test_get_version():
res = jmt.get_version(jmt.detect_release())
assert res == 'dev' or len(res.split('.')) == 2
def test_parse_date():
assert jmt.parse_date('2000-12-31') == datetime.datetime(2000,12,31)
with pytest.raises(Exception):
jmt.parse_date('2000-31-12')
def test_parse_date_str():
assert jmt.parse_date_str('2000-12-31') == '2000-12-31'
with pytest.raises(Exception):
jmt.parse_date_str('2000-31-12')
def test_jupman_constructor():
jm = Jupman()
# only testing the vital attrs
assert jm.filename == 'jupman'
#NOTE: putting '/' at the end causes exclude_patterns to not work !
assert jm.build == '_build'
assert jm.generated == '_static/generated'
class MockSphinx:
def add_config_value(self, a,b,c):
pass
def add_transform(self, a):
pass
def add_javascript(self, a):
pass
def add_stylesheet(self, a):
pass
def test_uproot():
assert jmt.uproot('jupman.py') == ''
assert jmt.uproot('_test/') == '../'
assert jmt.uproot('_test/test-chapter/data/pop.csv') == '../../../'
# this is supposed to be a directory
assert jmt.uproot('_test/non-existing') == '../../'
assert jmt.uproot('_static/img') == '../../'
assert jmt.uproot('_static/img/cc-by.png') == '../../'
assert jmt.uproot('_static/img/non-existing') == '../../../'
def test_replace_sysrel():
assert jmt.replace_py_rel("""import sys
sys.do_something()""", 'python-example').strip() == """import sys
sys.do_something()"""
assert jmt.replace_py_rel("""
import sys
sys.path.append('../')
import jupman
""", 'python-example').strip() == 'import jupman'
assert jmt.replace_py_rel("""
import sys
sys.path.append('../')
import jupman
sys.do_something()
""", 'python-example').strip() == """import sys
import jupman
sys.do_something()"""
def test_is_zip_ignored():
jm = make_jm()
assert jm.is_zip_ignored('.ipynb_checkpoints')
assert jm.is_zip_ignored('prova/.ipynb_checkpoints')
assert jm.is_zip_ignored('prova/__pycache__')
assert not jm.is_zip_ignored('good')
assert not jm.is_zip_ignored('very/good')
def test_is_code_sol_to_strip():
jm = make_jm()
solution = '# SOLUTION\nx=5\n'
write_here = '# write here\nx=5\n'
jupman_raise = '#jupman-raise\nx=5\n#/jupman-raise\n'
jupman_strip = '#jupman-strip\nx=5\n#/jupman-strip\n'
jupman_preprocess = '#jupman-preprocess\nbla\n'
jupman_purge = '#jupman-purge\nx=5\n#/jupman-purge\n'
jupman_purge_input = 'bla\n#jupman-purge-input\nbla\n'
jupman_purge_output = 'bla\n#jupman-purge-output\nbla\n'
jupman_purge_io = 'bla\n#jupman-purge-io\nbla\n'
assert jm.is_to_strip(solution) == True
assert jm.is_to_strip(write_here) == True
assert jm.is_to_strip(jupman_raise) == True
assert jm.is_to_strip(jupman_strip) == True
assert jm.is_to_strip(jupman_purge) == True
assert jm.is_to_strip(jupman_preprocess) == True
assert jm.is_to_strip(jupman_purge_input) == True
assert jm.is_to_strip(jupman_purge_output) == True
assert jm.is_to_strip(jupman_purge_io) == True
assert jm.is_code_sol(solution) == True
assert jm.is_code_sol(write_here) == True
assert jm.is_code_sol(jupman_raise) == True
assert jm.is_code_sol(jupman_strip) == True
assert jm.is_code_sol(jupman_purge) == False
assert jm.is_code_sol(jupman_purge_io) == False
assert jm.is_code_sol(jupman_purge_input) == False
assert jm.is_code_sol(jupman_purge_output) == False
assert jm.is_code_sol(jupman_preprocess) == False
cx = """x = 9
#jupman-purge
# present neither in solution nor in exercises
# NOTE: this is NOT considered a solution
y = 'purged!'
#/jupman-purge
# after"""
assert jm.is_to_strip(cx) == True
assert jm.is_code_sol(cx) == False
def test_purge_tags():
jm = make_jm()
# single tag directive
assert jm._purge_tags("""
bla
#jupman-preprocess
ble
""") == '\n bla\n \n ble\n '
# single tag directive
assert jm._purge_tags("""#jupman-preprocess
ble
""") == '\n ble\n '
# span tag purge directive, removes between
assert jm._purge_tags("""
bla
#jupman-purge
ble
#/jupman-purge
blo
""") == '\n bla\n \n blo\n '
# purge io directive, removes all
assert jm._purge_tags("""
bla
#jupman-purge-io
ble
""") == ''
# purge input directive, removes all
assert jm._purge_tags("""
bla
#jupman-purge-input
ble
""") == ''
# purge output directive, no effect
assert jm._purge_tags("""
bla
#jupman-purge-output
ble
""") == '\n bla\n \n ble\n '
# solution span tag
assert jm._purge_tags("""
#jupman-raise
bla
#/jupman-raise""") == '\n \n bla\n '
# solution span tag
assert jm._purge_tags("""
#jupman-strip
bla
#/jupman-strip""") == '\n \n bla\n '
assert jm._purge_tags("""
bla
#jupman-strip
ble
#/jupman-strip
blo""") == '\n bla\n \n ble\n \n blo'
def test_copy_chapter():
clean()
jm = make_jm()
os.makedirs(jm.build)
dest_dir = os.path.join(jm.build, 'test-chapter')
jm.copy_code('_test/test-chapter',
dest_dir,
copy_solutions=True)
assert os.path.isdir(dest_dir)
replacements_fn = os.path.join(dest_dir, 'replacements.ipynb')
assert os.path.isfile(replacements_fn)
nb_node = nbformat.read(replacements_fn, nbformat.NO_CONVERT)
# markdown
assert '[some link](index.ipynb)' in nb_node.cells[1].source
assert '' in nb_node.cells[2].source
assert '[some link](data/pop.csv)' in nb_node.cells[3].source
assert '<a href="index.ipynb" target="_blank">a link</a>' in nb_node.cells[4].source
assert '<img src="_static/img/cc-by.png">' in nb_node.cells[5].source
assert '<a href="data/pop.csv">a link</a>' in nb_node.cells[6].source
assert '<a href="index.ipynb">a link</a>' in nb_node.cells[7].source
assert '<img src="_static/img/cc-by.png">' in nb_node.cells[8].source
assert '<a href="data/pop.csv">a link</a>' in nb_node.cells[9].source
assert '# Python\nimport jupman' in nb_node.cells[10].source
assert '#jupman-raise' in nb_node.cells[10].source
assert 'stay!' in nb_node.cells[10].source
assert '<a href="index.html">a link</a>' in nb_node.cells[11].source
assert '<a href="https://jupman.softpython.org">a link</a>' in nb_node.cells[12].source
py_fn = os.path.join(dest_dir, 'file.py')
assert os.path.isfile(py_fn)
with open(py_fn, encoding='utf-8') as py_f:
py_code = py_f.read()
assert '# Python\nimport jupman' in py_code
assert '#jupman-raise' in py_code
test_fn = os.path.join(dest_dir, 'some_test.py')
assert os.path.isfile(test_fn)
with open(test_fn, encoding='utf-8') as test_f:
test_code = test_f.read()
assert 'some_sol' not in test_code
assert '# Python\nimport some\nimport jupman' in test_code
assert '#jupman-raise' in test_code
sol_fn = os.path.join(dest_dir, 'some_sol.py')
assert os.path.isfile(sol_fn)
with open(sol_fn, encoding='utf-8') as py_sol_f:
sol_code = py_sol_f.read()
assert '# Python\nimport jupman' in sol_code
assert '#jupman-raise' not in sol_code
assert '#jupman-strip' not in sol_code
assert '#jupman-purge' not in sol_code
assert 'stripped!' in sol_code
assert 'purged!' not in sol_code
assert "# work!\n\nprint('hi')" in sol_code
ex_fn = os.path.join(dest_dir, 'some.py')
assert os.path.isfile(ex_fn)
with open(ex_fn, encoding='utf-8') as py_ex_f:
py_ex_code = py_ex_f.read()
assert '# Python\nimport jupman' in py_ex_code
assert '#jupman-raise' not in py_ex_code
assert '# work!\nraise' in py_ex_code
# nb_ex ----------------------------
nb_ex_fn = os.path.join(dest_dir, 'nb.ipynb')
assert os.path.isfile(nb_ex_fn)
nb_ex = nbformat.read(nb_ex_fn, nbformat.NO_CONVERT)
#pprint(nb_ex)
assert "# Notebook EXERCISES" in nb_ex.cells[0].source
assert "#before\nraise" in nb_ex.cells[1].source
assert nb_ex.cells[2].source == "" # SOLUTION strips everything
assert nb_ex.cells[3].source.strip() == "# 3\n# write here" # write here strips afterwards
#4 question
#5 answer: must begin with answer and strips everything after
assert nb_ex.cells[5].source == '**ANSWER**:\n'
#6 write here
assert nb_ex.cells[6].source == 'x = 6\n# write here fast please\n\n'
assert nb_ex.cells[7].source == '' # SOLUTION strips everything
assert nb_ex.cells[8].source == 'x = 8\n\n# after' # jupman-strip strips everything inside exercises
assert nb_ex.cells[9].source == 'x = 9\n\n# after' # jupman-purge everything inside exercises
assert '#jupman-strip' not in nb_ex.cells[10].source
assert '#jupman-purge' not in nb_ex.cells[10].source
assert nb_ex.cells[11].source == ''
assert 'purged!11' in nb_ex.cells[11].outputs[0]['text']
assert '#jupman-purge-output' not in nb_ex.cells[12].source
assert '-output' not in nb_ex.cells[12].source
assert 'purged!12' in nb_ex.cells[12].source
assert nb_ex.cells[12].outputs == []
assert nb_ex.cells[13].source == ''
assert nb_ex.cells[13].outputs == []
assert nb_ex.cells[13].metadata['nbsphinx'] == 'hidden'
# nb_sol --------------------
nb_sol_fn = os.path.join(dest_dir, 'nb-sol.ipynb')
nb_sol = nbformat.read(nb_sol_fn, nbformat.NO_CONVERT)
assert 'stripped!' in nb_sol.cells[8].source # jupman-strip strips everything inside exercises
assert '#jupman-strip' not in nb_sol.cells[8].source
assert 'purged!' not in nb_sol.cells[9].source # jupman-purge strips everything also in solutions
assert '#jupman-purge' not in nb_sol.cells[9].source
assert '#jupman-strip' not in nb_sol.cells[10].source
assert '#jupman-purge' not in nb_sol.cells[10].source
assert 'stripped!' in nb_sol.cells[10].source
assert 'purged!10' not in nb_sol.cells[10].source
assert nb_sol.cells[11].source == ''
assert 'purged!11' in nb_sol.cells[11].outputs[0]['text']
assert '#jupman-purge-output' not in nb_sol.cells[12].source
assert '-output' not in nb_sol.cells[12].source
assert 'purged!12' in nb_sol.cells[12].source
assert nb_sol.cells[12].outputs == []
assert nb_sol.cells[13].source == ''
assert nb_sol.cells[13].outputs == []
assert nb_sol.cells[13].metadata['nbsphinx'] == 'hidden'
# nb_sol_web --------------------
nb_sol_fn = os.path.join(dest_dir, 'nb-sol.ipynb')
nb_sol_web = nbformat.read(nb_sol_fn, nbformat.NO_CONVERT)
jm._sol_nb_to_ex(nb_sol_web,
os.path.abspath(nb_sol_fn),
website=True)
stripped8 = 0
stripped10 = 0
for cell in nb_sol_web.cells:
if 'stripped!8' in cell.source:
stripped8 += 1
if 'stripped!10' in cell.source:
stripped10 += 1
assert 'purged!9' not in cell.source
assert 'purged!10' not in cell.source
assert 'purged!11' not in cell.source
if getattr(cell, 'outputs', None):
assert 'purged!12' not in cell.outputs[0]['text']
assert 'purged!13' not in cell.source
if getattr(cell, 'outputs', None):
assert 'purged!13' not in cell.outputs[0]['text']
assert stripped8 == 1
assert stripped10 == 1
# chal --------------------
py_chal_sol_fn = os.path.join(dest_dir, 'my_chal_sol.py')
assert not os.path.isfile(py_chal_sol_fn)
py_chal_fn = os.path.join(dest_dir, 'my_chal.py')
assert os.path.isfile(py_chal_fn)
py_chal_test_fn = os.path.join(dest_dir, 'my_chal_test.py')
assert os.path.isfile(py_chal_test_fn)
with open(py_chal_test_fn) as py_chal_test_f:
py_chal_test_code = py_chal_test_f.read()
assert 'from my_chal import *' in py_chal_test_code
nb_chal_ex_fn = os.path.join(dest_dir, 'nb-chal.ipynb')
assert os.path.isfile(nb_chal_ex_fn)
nb_chal_sol_fn = os.path.join(dest_dir, 'nb-chal-sol.ipynb')
assert not os.path.isfile(nb_chal_sol_fn)
nb_chal_ex = nbformat.read(nb_chal_ex_fn, nbformat.NO_CONVERT)
assert jm.ipynb_solutions not in nb_chal_ex.cells[1].source
def test_setup(tconf):
mockapp = MockSphinx()
tconf.setup(mockapp)
# if so tests run smoothly also on non-jupman projects
if os.path.exists('jupyter-example'):
assert os.path.isfile(os.path.join(tconf.jm.generated, 'jupyter-example.zip'))
if os.path.exists('python-example'):
assert os.path.isfile(os.path.join(tconf.jm.generated, 'python-example.zip'))
if os.path.exists('jup-and-py-example'):
assert os.path.isfile(os.path.join(tconf.jm.generated, 'jup-and-py-example.zip'))
if os.path.exists('challenge-example'):
assert os.path.isfile(os.path.join(tconf.jm.generated, 'challenge-example.zip'))
# test reproducible build zips
# https://github.com/DavidLeoni/jupman/issues/60
if os.path.exists('jup-and-py-example'):
zpath1 = os.path.join(tconf.jm.generated, 'jup-and-py-example.zip')
zpath2 = os.path.join(tconf.test_tmp, 'jup-and-py-example.zip')
shutil.copyfile(zpath1, zpath2)
time.sleep(2)
tconf.setup(mockapp)
assert filecmp.cmp(zpath1, zpath2, shallow=False)
def TODO_test_reproducible_build_html():
""" NOTE: 2020 12: if img alt is not specified, a random id is assigned which makes build non-deterministic
"""
hpath1 = os.path.join(tconf.jm.build, 'html/jupman-tests.html')
hpath2 = os.path.join(tconf.test_tmp, 'html/jupman-tests.html')
shutil.copyfile(hpath1, hpath2)
time.sleep(2)
assert filecmp.cmp(zpath1, zpath2, shallow=False)
def test_tag_regex():
with pytest.raises(ValueError):
tag_regex("")
p = re.compile(tag_regex(" a b"))
assert p.match(" a b")
assert p.match(" a b")
assert p.match(" a b ")
assert p.match(" a b ")
assert p.match(" a b\n")
assert p.match(" a b\n")
assert not p.match(" ab")
assert not p.match("c b")
def test_write_solution_here():
jm = make_jm()
p = re.compile(jm.write_solution_here)
#print(p)
assert p.match(" # write here a b\nc")
assert p.match(" # write here a b c \nc\n1d")
assert p.match('# write here\n')
#assert p.match('# write here') # corner case, there is no \n
#assert p.match('# write here ') # corner case, there is no \n
def test_span_pattern():
jm = make_jm()
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab #/ab') == 'z'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab c #/ab') == 'z'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab\n#/ab') == 'z'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab\n#/ab') == 'z'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab #/ab c') == 'z c'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab #/ab\nc') == 'z\nc'
assert re.sub( jmt.span_pattern('ab'), 'z', ' #ab #/ab') == ' z'
assert re.sub( jmt.span_pattern('ab'), 'z', '#a b #/ab') == '#a b #/ab'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab #ab') == '#ab #ab'
assert re.sub( jmt.span_pattern('ab'), 'z', '#abc #/ab') == '#abc #/ab'
assert re.sub( jmt.span_pattern('ab'), 'z', '#abc#/abc') == '#abc#/abc'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab c #/ab w #ab d #/ab') == 'z w z'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab c #/ab\n#ab d #/ab') == 'z\nz'
assert re.sub( jmt.span_pattern('ab'), 'z', '#ab c #/ab #ab d #/ab') == 'z z'
def test_validate_code_tags():
jm = make_jm()
assert jm.validate_code_tags('# SOLUTION\nbla', 'some_file') == 1
assert jm.validate_code_tags(' # SOLUTION\nbla', 'some_file') == 1
assert jm.validate_code_tags('something before # SOLUTION\nbla', 'some_file') == 0
assert jm.validate_code_tags('#jupman-strip\nblabla#/jupman-strip', 'some_file') == 1
assert jm.validate_code_tags('#jupman-strip\nA#/jupman-strip #jupman-raise\nB#/jupman-raise', 'some_file') == 2
assert jm.validate_code_tags('#jupman-preprocess', 'some_file') == 0
assert jm.validate_code_tags('#jupman-purge\nblabla#/jupman-purge', 'some_file') == 0
assert jm.validate_code_tags('#jupman-purge-input\nA', 'some_file') == 0
assert jm.validate_code_tags('#jupman-purge-output\nA', 'some_file') == 0
assert jm.validate_code_tags('#jupman-purge-io\nA', 'some_file') == 0
# pairs count as one
assert jm.validate_code_tags('#jupman-raise\nA#/jupman-raise', 'some_file') == 1
assert jm.validate_code_tags("""
hello
#jupman-raise
something
#/jupman-raise
#jupman-raise
bla
#/jupman-raise""", 'some_file') == 2
def test_validate_markdown_tags():
jm = make_jm()
assert jm.validate_markdown_tags('**ANSWER**: hello', 'some_file') == 1
assert jm.validate_markdown_tags(' **ANSWER**: hello', 'some_file') == 1
assert jm.validate_markdown_tags('bla **ANSWER**: hello', 'some_file') == 0
def test_preprocessor_sol():
jm = make_jm()
jmt.init(jm)
nb_fn = '_test/test-chapter/nb-sol.ipynb'
resources = make_nb_resources(nb_fn)
d = '_build/test/.doctrees/nbsphinx/'
if not os.path.isdir(d):
os.makedirs(d)
exp = nbsphinx.Exporter()
nb_orig = nbformat.read(nb_fn, nbformat.NO_CONVERT)
purged_count = 0
stripped_count = 0
for cell in nb_orig.cells:
if 'stripped!8' in cell.source:
stripped_count += 1
if 'purged!9' in cell.source:
purged_count += 1
assert purged_count == 1
assert stripped_count == 1
nb_new, new_res = exp.from_notebook_node(nb_orig, resources)
stripped_count = 0
for cell in nb_orig.cells:
if 'stripped!8' in cell.source:
stripped_count += 1
assert not 'purged!9' in cell.source
assert stripped_count == 1
def test_preprocessor_force():
jm = make_jm()
jmt.init(jm)
nb_fn = '_test/test-chapter/force-preprocess.ipynb'
resources = make_nb_resources(nb_fn)
d = '_build/test/.doctrees/nbsphinx/'
if not os.path.isdir(d):
os.makedirs(d)
exp = nbsphinx.Exporter()
nb_orig = nbformat.read(nb_fn, nbformat.NO_CONVERT)
assert 'stripped!' in nb_orig.cells[2].source
assert 'purged!' in nb_orig.cells[3].source
nb_new, new_res = exp.from_notebook_node(nb_orig, resources)
stripped_count = 0
for cell in nb_orig.cells:
if 'stripped!' in cell.source:
stripped_count += 1
assert '#jupman-strip' not in cell.source
assert '#jupman-preprocess' not in cell.source
assert 'purged!' not in cell.source
assert stripped_count == 1
def test_preprocessor_normal():
jm = make_jm()
jmt.init(jm)
nb_fn = '_test/test-chapter/replacements.ipynb'
resources = make_nb_resources(nb_fn)
d = '_build/test/.doctrees/nbsphinx/'
if not os.path.isdir(d):
os.makedirs(d)
exp = nbsphinx.Exporter()
nb_orig = nbformat.read(nb_fn, nbformat.NO_CONVERT)
assert 'stay!' in nb_orig.cells[10].source
nb_new, new_res = exp.from_notebook_node(nb_orig, resources)
assert 'stay!' in nb_orig.cells[10].source
| 32.595313
| 115
| 0.622405
|
4a0a790f671ecbc13b5186b852fcbbff30b71240
| 189
|
py
|
Python
|
tools/leetcode.242.Valid Anagram/leetcode.242.Valid Anagram.submission0.py
|
tedye/leetcode
|
975d7e3b8cb9b6be9e80e07febf4bcf6414acd46
|
[
"MIT"
] | 4
|
2015-10-10T00:30:55.000Z
|
2020-07-27T19:45:54.000Z
|
tools/leetcode.242.Valid Anagram/leetcode.242.Valid Anagram.submission0.py
|
tedye/leetcode
|
975d7e3b8cb9b6be9e80e07febf4bcf6414acd46
|
[
"MIT"
] | null | null | null |
tools/leetcode.242.Valid Anagram/leetcode.242.Valid Anagram.submission0.py
|
tedye/leetcode
|
975d7e3b8cb9b6be9e80e07febf4bcf6414acd46
|
[
"MIT"
] | null | null | null |
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
return sorted(list(s))==sorted(list(t))
| 189
| 189
| 0.47619
|
4a0a79dc388700a32e0ff0d4f695ad3201bc5f28
| 6,796
|
py
|
Python
|
Python-Bing-DwenDwen.py
|
zhouxuanyi-zxy/Python-Bing-Dwen-Dwen
|
805529ed699a719c23bdae8dd4292692329194c0
|
[
"MIT"
] | null | null | null |
Python-Bing-DwenDwen.py
|
zhouxuanyi-zxy/Python-Bing-Dwen-Dwen
|
805529ed699a719c23bdae8dd4292692329194c0
|
[
"MIT"
] | null | null | null |
Python-Bing-DwenDwen.py
|
zhouxuanyi-zxy/Python-Bing-Dwen-Dwen
|
805529ed699a719c23bdae8dd4292692329194c0
|
[
"MIT"
] | 2
|
2022-02-12T08:04:35.000Z
|
2022-02-21T06:41:06.000Z
|
import turtle
turtle.speed(0)
# 左手
turtle.up()
turtle.goto(177,112)
turtle.pencolor("lightgray")
turtle.pensize(3)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.down()
turtle.setheading(80)
turtle.circle(-45,200)
turtle.circle(-300,23)
turtle.end_fill()
# 左手内
turtle.up()
turtle.goto(182,95)
turtle.pencolor("black")
turtle.pensize(1)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.setheading(95)
turtle.down()
turtle.circle(-37,160)
turtle.circle(-20,50)
turtle.circle(-200,30)
turtle.end_fill()
# 轮廓
# 头顶
turtle.up()
turtle.goto(-73,230)
turtle.pencolor("lightgray")
turtle.pensize(3)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.down()
turtle.setheading(20)
turtle.circle(-250,35)
# 左耳
turtle.setheading(50)
turtle.circle(-42,180)
# 左侧
turtle.setheading(-50)
turtle.circle(-190,30)
turtle.circle(-320,45)
# 左腿
turtle.circle(120,30)
turtle.circle(200,12)
turtle.circle(-18,85)
turtle.circle(-180,23)
turtle.circle(-20,110)
turtle.circle(15,115)
turtle.circle(100,12)
# 右腿
turtle.circle(15,120)
turtle.circle(-15,110)
turtle.circle(-150,30)
turtle.circle(-15,70)
turtle.circle(-150,10)
turtle.circle(200,35)
turtle.circle(-150,20)
# 右手
turtle.setheading(-120)
turtle.circle(50,30)
turtle.circle(-35,200)
turtle.circle(-300,23)
# 右侧
turtle.setheading(86)
turtle.circle(-300,26)
# 右耳
turtle.setheading(122)
turtle.circle(-53,160)
turtle.end_fill()
# 右耳内
turtle.up()
turtle.goto(-130,180)
turtle.pencolor("black")
turtle.pensize(1)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.down()
turtle.setheading(120)
turtle.circle(-28,160)
turtle.setheading(210)
turtle.circle(150,20)
turtle.end_fill()
# 左耳内
turtle.up()
turtle.goto(90,230)
turtle.setheading(40)
turtle.begin_fill()
turtle.down()
turtle.circle(-30,170)
turtle.setheading(125)
turtle.circle(150,23)
turtle.end_fill()
# 右手内
turtle.up()
turtle.goto(-180,-55)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.setheading(-120)
turtle.down()
turtle.circle(50,30)
turtle.circle(-27,200)
turtle.circle(-300,20)
turtle.setheading(-90)
turtle.circle(300,14)
turtle.end_fill()
# 左腿内
turtle.up()
turtle.goto(108,-168)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.down()
turtle.setheading(-115)
turtle.circle(110,15)
turtle.circle(200,10)
turtle.circle(-18,80)
turtle.circle(-180,13)
turtle.circle(-20,90)
turtle.circle(15,60)
turtle.setheading(42)
turtle.circle(-200,29)
turtle.end_fill()
# 右腿内
turtle.up()
turtle.goto(-38,-210)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.down()
turtle.setheading(-155)
turtle.circle(15,100)
turtle.circle(-10,110)
turtle.circle(-100,30)
turtle.circle(-15,65)
turtle.circle(-100,10)
turtle.circle(200,15)
turtle.setheading(-14)
turtle.circle(-200,27)
turtle.end_fill()
# 右眼
# 眼圈
turtle.up()
turtle.goto(-64,120)
turtle.begin_fill()
turtle.down()
turtle.setheading(40)
turtle.circle(-35,152)
turtle.circle(-100,50)
turtle.circle(-35,130)
turtle.circle(-100,50)
turtle.end_fill()
# 眼珠
turtle.up()
turtle.goto(-47,55)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(25,360)
turtle.end_fill()
turtle.up()
turtle.goto(-45,62)
turtle.pencolor("darkslategray")
turtle.fillcolor("darkslategray")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(19,360)
turtle.end_fill()
turtle.up()
turtle.goto(-45,68)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(10,360)
turtle.end_fill()
turtle.up()
turtle.goto(-47,86)
turtle.pencolor("white")
turtle.fillcolor("white")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(5,360)
turtle.end_fill()
# 左眼
# 眼圈
turtle.up()
turtle.goto(51,82)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.down()
turtle.setheading(120)
turtle.circle(-32,152)
turtle.circle(-100,55)
turtle.circle(-25,120)
turtle.circle(-120,45)
turtle.end_fill()
# 眼珠
turtle.up()
turtle.goto(79,60)
turtle.fillcolor("white")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(24,360)
turtle.end_fill()
turtle.up()
turtle.goto(79,64)
turtle.pencolor("darkslategray")
turtle.fillcolor("darkslategray")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(19,360)
turtle.end_fill()
turtle.up()
turtle.goto(79,70)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(10,360)
turtle.end_fill()
turtle.up()
turtle.goto(79,88)
turtle.pencolor("white")
turtle.fillcolor("white")
turtle.begin_fill()
turtle.down()
turtle.setheading(0)
turtle.circle(5,360)
turtle.end_fill()
# 鼻子
turtle.up()
turtle.goto(37,80)
turtle.fillcolor("black")
turtle.begin_fill()
turtle.down()
turtle.circle(-8,130)
turtle.circle(-22,100)
turtle.circle(-8,130)
turtle.end_fill()
# 嘴
turtle.up()
turtle.goto(-15,48)
turtle.setheading(-36)
turtle.begin_fill()
turtle.down()
turtle.circle(60,70)
turtle.setheading(-132)
turtle.circle(-45,100)
turtle.end_fill()
# 彩虹圈
turtle.up()
turtle.goto(-135,120)
turtle.pensize(5)
turtle.pencolor("cyan")
turtle.pendown()
turtle.setheading(60)
turtle.circle(-165,150)
turtle.circle(-130,78)
turtle.circle(-250,30)
turtle.circle(-138,105)
turtle.up()
turtle.goto(-131,116)
turtle.pencolor("slateblue")
turtle.down()
turtle.setheading(60)
turtle.circle(-160,144)
turtle.circle(-120,78)
turtle.circle(-242,30)
turtle.circle(-135,105)
turtle.up()
turtle.goto(-127,112)
turtle.pencolor("orangered")
turtle.down()
turtle.setheading(60)
turtle.circle(-155,136)
turtle.circle(-116,86)
turtle.circle(-220,30)
turtle.circle(-134,103)
turtle.up()
turtle.goto(-123,108)
turtle.pencolor("gold")
turtle.down()
turtle.setheading(60)
turtle.circle(-150,136)
turtle.circle(-104,84)
turtle.circle(-220,30)
turtle.circle(-126,102)
turtle.up()
turtle.goto(-120,104)
turtle.pencolor("greenyellow")
turtle.down()
turtle.setheading(60)
turtle.circle(-145,136)
turtle.circle(-90,83)
turtle.circle(-220,30)
turtle.circle(-120,100)
turtle.up()
# 爱心
turtle.up()
turtle.goto(220,115)
turtle.pencolor("brown")
turtle.pensize(1)
turtle.fillcolor("brown")
turtle.begin_fill()
turtle.down()
turtle.setheading(36)
turtle.circle(-8,180)
turtle.circle(-60,24)
turtle.setheading(110)
turtle.circle(-60,24)
turtle.circle(-8,180)
turtle.end_fill()
# 五环
turtle.up()
turtle.goto(-5,-170)
turtle.down()
turtle.pencolor("blue")
turtle.circle(6)
turtle.up()
turtle.goto(10,-170)
turtle.down()
turtle.pencolor("black")
turtle.circle(6)
turtle.up()
turtle.goto(25,-170)
turtle.down()
turtle.pencolor("brown")
turtle.circle(6)
turtle.circle(6)
turtle.up()
turtle.goto(2,-175)
turtle.down()
turtle.pencolor("lightgoldenrod")
turtle.circle(6)
turtle.up()
turtle.goto(16,-175)
turtle.down()
turtle.pencolor("green")
turtle.circle(6)
turtle.up()
# 字
turtle.pencolor("black")
turtle.goto(-16,-160)
turtle.write("BEIJING 2022",font=('Arial',10,'bold italic'))
turtle.ht()
turtle.done()
| 17.884211
| 60
| 0.745438
|
4a0a7a1e8ca51e2191ffea8c4afb38eca20b45ab
| 4,902
|
py
|
Python
|
demo/fcos_demo.py
|
cenchaojun/FCOS
|
fe13fd5cf86fd2ae88b5258081d1214b29e2e272
|
[
"BSD-2-Clause"
] | null | null | null |
demo/fcos_demo.py
|
cenchaojun/FCOS
|
fe13fd5cf86fd2ae88b5258081d1214b29e2e272
|
[
"BSD-2-Clause"
] | null | null | null |
demo/fcos_demo.py
|
cenchaojun/FCOS
|
fe13fd5cf86fd2ae88b5258081d1214b29e2e272
|
[
"BSD-2-Clause"
] | null | null | null |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2, os
from fcos_core.config import cfg
from predictor import COCODemo
import time
def main():
parser = argparse.ArgumentParser(description="PyTorch Object Detection Webcam Demo")
parser.add_argument(
"--config-file",
default="/home/cen/PycharmProjects/FCOS/configs/fcos/fcos_imprv_R_50_FPN_1x.yaml",
metavar="FILE",
help="path to config file",
)
parser.add_argument(
"--weights",
default="FCOS_imprv_R_50_FPN_1x.pth",
metavar="FILE",
help="path to the trained model",
)
parser.add_argument(
"--images-dir",
default="/home/cen/PycharmProjects/FCOS/demo/my_images",
metavar="DIR",
help="path to demo images directory",
)
parser.add_argument(
"--min-image-size",
type=int,
default=800,
help="Smallest size of the image to feed to the model. "
"Model was trained with 800, which gives best results",
)
parser.add_argument(
"opts",
help="Modify model config options using the command-line",
default=None,
nargs=argparse.REMAINDER,
)
args = parser.parse_args()
# load config from file and command-line arguments
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.MODEL.WEIGHT = args.weights
cfg.freeze()
# The following per-class thresholds are computed by maximizing
# per-class f-measure in their precision-recall curve.
# Please see compute_thresholds_for_classes() in coco_eval.py for details.
thresholds_for_classes = [
0.4923645853996277, 0.4928510785102844, 0.5040897727012634,
0.4912887513637543, 0.5016880631446838, 0.5278812646865845,
0.5351834893226624, 0.5003424882888794, 0.4955945909023285,
0.43564629554748535, 0.6089804172515869, 0.666087806224823,
0.5932040214538574, 0.48406165838241577, 0.4062422513961792,
0.5571075081825256, 0.5671307444572449, 0.5268378257751465,
0.5112953186035156, 0.4647842049598694, 0.5324517488479614,
0.5795850157737732, 0.5152440071105957, 0.5280804634094238,
0.4791383445262909, 0.5261335372924805, 0.4906163215637207,
0.523737907409668, 0.47027698159217834, 0.5103300213813782,
0.4645252823829651, 0.5384289026260376, 0.47796186804771423,
0.4403403103351593, 0.5101461410522461, 0.5535093545913696,
0.48472103476524353, 0.5006796717643738, 0.5485560894012451,
0.4863888621330261, 0.5061569809913635, 0.5235867500305176,
0.4745445251464844, 0.4652363359928131, 0.4162440598011017,
0.5252017974853516, 0.42710989713668823, 0.4550687372684479,
0.4943239390850067, 0.4810051918029785, 0.47629663348197937,
0.46629616618156433, 0.4662836790084839, 0.4854755401611328,
0.4156557023525238, 0.4763634502887726, 0.4724511504173279,
0.4915047585964203, 0.5006274580955505, 0.5124194622039795,
0.47004589438438416, 0.5374764204025269, 0.5876904129981995,
0.49395060539245605, 0.5102297067642212, 0.46571290493011475,
0.5164387822151184, 0.540651798248291, 0.5323763489723206,
0.5048757195472717, 0.5302401781082153, 0.48333442211151123,
0.5109739303588867, 0.4077408015727997, 0.5764586925506592,
0.5109297037124634, 0.4685552418231964, 0.5148998498916626,
0.4224434792995453, 0.4998510777950287
]
demo_im_names = os.listdir(args.images_dir)
# prepare object that handles inference plus adds predictions on top of image
coco_demo = COCODemo(
cfg,
confidence_thresholds_for_classes=thresholds_for_classes,
min_image_size=args.min_image_size
)
for im_name in demo_im_names:
img = cv2.imread(os.path.join(args.images_dir, im_name))
if img is None:
continue
start_time = time.time()
composite = coco_demo.run_on_opencv_image(img)
print("{}\tinference time: {:.2f}s".format(im_name, time.time() - start_time))
cv2.imwrite('/home/cen/PycharmProjects/FCOS/demo/out_image/{}.png'.format(im_name),composite)
cv2.imshow(im_name, composite)
print("Press any keys to exit ...")
cv2.waitKey()
cv2.destroyAllWindows()
# for 循环遍历整个图片文件但是还没保存的地方
# for im_name in demo_im_names:
# img = cv2.imread(os.path.join(args.images_dir, im_name))
# if img is None:
# continue
# start_time = time.time()
# composite = coco_demo.run_on_opencv_image(img)
# print("{}\tinference time: {:.2f}s".format(im_name, time.time() - start_time))
# cv2.imshow(im_name, composite)
# print("Press any keys to exit ...")
# cv2.waitKey()
# cv2.destroyAllWindows()
if __name__ == "__main__":
main()
| 4,902
| 4,902
| 0.687475
|
4a0a7a360209059937222e9eaebbd38f05c6240e
| 357
|
py
|
Python
|
speculation-rules/prefetch/resources/prefetch.py
|
BasixKOR/wpt
|
aa27d567c10dcdb2aea6884d5155dfaaa177a800
|
[
"BSD-3-Clause"
] | null | null | null |
speculation-rules/prefetch/resources/prefetch.py
|
BasixKOR/wpt
|
aa27d567c10dcdb2aea6884d5155dfaaa177a800
|
[
"BSD-3-Clause"
] | 112
|
2021-09-27T14:39:02.000Z
|
2022-03-30T14:26:35.000Z
|
speculation-rules/prefetch/resources/prefetch.py
|
clopez/wpt
|
4ba8a4a1f41e166289c0a7feaa5665e1385e90f3
|
[
"BSD-3-Clause"
] | null | null | null |
from wptserve.handlers import json_handler
@json_handler
def main(request, response):
uuid = request.GET[b"uuid"]
prefetch = request.headers.get(
"Sec-Purpose", b"").decode("utf-8").startswith("prefetch")
n = request.server.stash.take(uuid)
if n is None:
n = 0
if prefetch:
n += 1
request.server.stash.put(uuid, n)
return n
| 21
| 64
| 0.666667
|
4a0a7b0e438e7c9a0c803e30cbc8fcb2765f9bbd
| 138
|
py
|
Python
|
kunai/hydra_utils/__init__.py
|
mjun0812/kunai
|
6a457c7242ed98dadb29f7002a3c0385ae6c1701
|
[
"MIT"
] | null | null | null |
kunai/hydra_utils/__init__.py
|
mjun0812/kunai
|
6a457c7242ed98dadb29f7002a3c0385ae6c1701
|
[
"MIT"
] | null | null | null |
kunai/hydra_utils/__init__.py
|
mjun0812/kunai
|
6a457c7242ed98dadb29f7002a3c0385ae6c1701
|
[
"MIT"
] | null | null | null |
from .hydra_utils import get_default_config, set_hydra, validate_config
__all__ = ("set_hydra", "validate_config", "get_default_config")
| 34.5
| 71
| 0.811594
|
4a0a7b378f2509ca9819d7e3feb51f59a3c62777
| 2,138
|
py
|
Python
|
rx3/core/observable/zip.py
|
samiur/RxPY
|
ea6b3554ab06cfc70e28b532c0a54b910b6ee470
|
[
"MIT"
] | null | null | null |
rx3/core/observable/zip.py
|
samiur/RxPY
|
ea6b3554ab06cfc70e28b532c0a54b910b6ee470
|
[
"MIT"
] | null | null | null |
rx3/core/observable/zip.py
|
samiur/RxPY
|
ea6b3554ab06cfc70e28b532c0a54b910b6ee470
|
[
"MIT"
] | null | null | null |
from typing import Optional, List
from rx3 import from_future
from rx3.core import Observable, typing
from rx3.disposable import CompositeDisposable, SingleAssignmentDisposable
from rx3.internal.utils import is_future
# pylint: disable=redefined-builtin
def _zip(*args: Observable) -> Observable:
"""Merges the specified observable sequences into one observable
sequence by creating a tuple whenever all of the
observable sequences have produced an element at a corresponding
index.
Example:
>>> res = zip(obs1, obs2)
Args:
args: Observable sources to zip.
Returns:
An observable sequence containing the result of combining
elements of the sources as tuple.
"""
sources = list(args)
def subscribe(observer: typing.Observer, scheduler: Optional[typing.Scheduler] = None):
n = len(sources)
queues : List[List] = [[] for _ in range(n)]
is_done = [False] * n
def next(i):
if all([len(q) for q in queues]):
try:
queued_values = [x.pop(0) for x in queues]
res = tuple(queued_values)
except Exception as ex: # pylint: disable=broad-except
observer.on_error(ex)
return
observer.on_next(res)
elif all([x for j, x in enumerate(is_done) if j != i]):
observer.on_completed()
def done(i):
is_done[i] = True
if all(is_done):
observer.on_completed()
subscriptions = [None]*n
def func(i):
source = sources[i]
sad = SingleAssignmentDisposable()
source = from_future(source) if is_future(source) else source
def on_next(x):
queues[i].append(x)
next(i)
sad.disposable = source.subscribe_(on_next, observer.on_error, lambda: done(i), scheduler)
subscriptions[i] = sad
for idx in range(n):
func(idx)
return CompositeDisposable(subscriptions)
return Observable(subscribe)
| 30.985507
| 102
| 0.594013
|
4a0a7c29e2706803e2153b3e24e886449ec1497d
| 4,511
|
py
|
Python
|
tests/unit/transport/test_ipc.py
|
haodeon/salt
|
af2964f4ddbf9c5635d1528a495e473996cc7b71
|
[
"Apache-2.0"
] | null | null | null |
tests/unit/transport/test_ipc.py
|
haodeon/salt
|
af2964f4ddbf9c5635d1528a495e473996cc7b71
|
[
"Apache-2.0"
] | null | null | null |
tests/unit/transport/test_ipc.py
|
haodeon/salt
|
af2964f4ddbf9c5635d1528a495e473996cc7b71
|
[
"Apache-2.0"
] | null | null | null |
"""
:codeauthor: Mike Place <mp@saltstack.com>
"""
import errno
import logging
import os
import threading
import pytest
import salt.config
import salt.exceptions
import salt.ext.tornado.gen
import salt.ext.tornado.ioloop
import salt.ext.tornado.testing
import salt.transport.ipc
import salt.utils.platform
from salt.ext.tornado.iostream import StreamClosedError
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import skipIf
pytestmark = [
pytest.mark.skip_on_darwin,
pytest.mark.skip_on_freebsd,
pytest.mark.skip_on_windows,
]
log = logging.getLogger(__name__)
@skipIf(salt.utils.platform.is_windows(), "Windows does not support Posix IPC")
class IPCMessagePubSubCase(salt.ext.tornado.testing.AsyncTestCase):
"""
Test all of the clear msg stuff
"""
def setUp(self):
super().setUp()
self.opts = {"ipc_write_buffer": 0}
if not os.path.exists(RUNTIME_VARS.TMP):
os.mkdir(RUNTIME_VARS.TMP)
self.socket_path = os.path.join(RUNTIME_VARS.TMP, "ipc_test.ipc")
self.pub_channel = self._get_pub_channel()
self.sub_channel = self._get_sub_channel()
def _get_pub_channel(self):
pub_channel = salt.transport.ipc.IPCMessagePublisher(
self.opts,
self.socket_path,
)
pub_channel.start()
return pub_channel
def _get_sub_channel(self):
sub_channel = salt.transport.ipc.IPCMessageSubscriber(
socket_path=self.socket_path,
io_loop=self.io_loop,
)
sub_channel.connect(callback=self.stop)
self.wait()
return sub_channel
def tearDown(self):
super().tearDown()
try:
self.pub_channel.close()
except OSError as exc:
if exc.errno != errno.EBADF:
# If its not a bad file descriptor error, raise
raise
try:
self.sub_channel.close()
except OSError as exc:
if exc.errno != errno.EBADF:
# If its not a bad file descriptor error, raise
raise
os.unlink(self.socket_path)
del self.pub_channel
del self.sub_channel
def test_multi_client_reading(self):
# To be completely fair let's create 2 clients.
client1 = self.sub_channel
client2 = self._get_sub_channel()
call_cnt = []
# Create a watchdog to be safe from hanging in sync loops (what old code did)
evt = threading.Event()
def close_server():
if evt.wait(1):
return
client2.close()
self.stop()
watchdog = threading.Thread(target=close_server)
watchdog.start()
# Runs in ioloop thread so we're safe from race conditions here
def handler(raw):
call_cnt.append(raw)
if len(call_cnt) >= 2:
evt.set()
self.stop()
# Now let both waiting data at once
client1.read_async(handler)
client2.read_async(handler)
self.pub_channel.publish("TEST")
self.wait()
self.assertEqual(len(call_cnt), 2)
self.assertEqual(call_cnt[0], "TEST")
self.assertEqual(call_cnt[1], "TEST")
def test_sync_reading(self):
# To be completely fair let's create 2 clients.
client1 = self.sub_channel
client2 = self._get_sub_channel()
call_cnt = []
# Now let both waiting data at once
self.pub_channel.publish("TEST")
ret1 = client1.read_sync()
ret2 = client2.read_sync()
self.assertEqual(ret1, "TEST")
self.assertEqual(ret2, "TEST")
@salt.ext.tornado.testing.gen_test
def test_async_reading_streamclosederror(self):
client1 = self.sub_channel
call_cnt = []
# Create a watchdog to be safe from hanging in sync loops (what old code did)
evt = threading.Event()
def close_server():
if evt.wait(0.001):
return
client1.close()
self.stop()
watchdog = threading.Thread(target=close_server)
watchdog.start()
# Runs in ioloop thread so we're safe from race conditions here
def handler(raw):
pass
try:
ret1 = yield client1.read_async(handler)
self.wait()
except StreamClosedError as ex:
assert False, "StreamClosedError was raised inside the Future"
| 29.103226
| 85
| 0.615828
|
4a0a7c35d43930ba998ac74c19e410733c9a2bbe
| 6,789
|
py
|
Python
|
bugsy_15_puzzle.py
|
trattner/bugsy
|
47b0de9bdb1e50c3bf45fa785ba44266aa48547b
|
[
"MIT"
] | null | null | null |
bugsy_15_puzzle.py
|
trattner/bugsy
|
47b0de9bdb1e50c3bf45fa785ba44266aa48547b
|
[
"MIT"
] | null | null | null |
bugsy_15_puzzle.py
|
trattner/bugsy
|
47b0de9bdb1e50c3bf45fa785ba44266aa48547b
|
[
"MIT"
] | null | null | null |
#for leslie kaelbling bling bling
#Michael and Andy
#Weight of time and solution cost
import time
import heapq
from math import log
import sys
class Puzzle:
"""
A 15-puzzle instance which takes input startin_state as a well-formed typle of 16 entries
method next_states returns successors, goal_state is proper termination state
"""
def __init__(self, starting_state):
self.goal_state=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0)
#State '0' represents the empty slot in the puzzle
self.initial_state=starting_state
def next_states(self, current_state):
i = current_state.index(0)
#Returns the position of the empty(0) slot
validswaps = []
v1 = i-4
#Moving up
v2 = i+4
#Moving down
v3 = i - 1
#Moving left
v4 = i + 1
#Moving right
if v1 >= 0:
#Prevents you from going past top left corner
validswaps.append(v1)
if v2 <= 15:
#Prevents you from going past bottom left corner
validswaps.append(v2)
if v3 % 4 < i % 4:
#Prevents you from going past left side
'''
WORKING CASE:
15(i) mod 4 returns 3
14(v3) mod 4 returns 2
So if the empty space is in position 15
This would be a valid swap
FAILURE CASE:
12(i) mod 4 returns 0
11(v2) mod 4 returns 1
So if the empty space is in position 12
This would not be a valid swap
(Same case for 8,4,0)
'''
validswaps.append(v3)
if v4 % 4 > i % 4:
'''
WORKING CASE:
10(i) mod 4 returns 2
11(v4) mod 4 returns 3
So if the empty space is in position 10
This would be a valid swap
FAILURE CASE:
1. 11(i) mod 4 returns 3
12(v4) mod 4 returns 0
So if the empty space is in position 11
This would not be a valid swap
(Same case for 3,7)
'''
validswaps.append(v4)
next_states = []
for v in validswaps:
'''
Swaps the empty space from the old position
to the new position
Will add each state from valid swaps to a list
And return that list
'''
old = list(current_state)
new = list(current_state)
new[i] = old[v]
new[v] = old[i]
next_states.append(tuple(new))
return next_states
#make bugsy happen
def bugsy(puzzle, u, g, w_t, w_f):
'''
Search function based on utility, a linear combination of estimated time to find goal and cost of path
inputs 15-Puzzle instance, utility function, cost function g*, utility weights
outputs a maximum utility path if one exists, else returns false
'''
start_time = time.time()
closed = []
Uhat = -sys.maxint
frontier = [(Uhat, puzzle.initial_state, [], start_time)]
#States are composed of (utility, current state - tuple, parent path - list, t_instantiated)
expansion_count = 0
delay = 0
total_delay_time = 0
total_exp_time = 0
t_exp = 0
#goal state dictionary allows for quick lookup for Manhattan Dist Calc
goal_state_dictionary = convert_to_tuples(puzzle.goal_state)
stopnow = 0
while len(frontier) > 0 and stopnow < 300:
current = heapq.heappop(frontier)
if puzzle.goal_state == current[1]:
return current[2]
closed.append(current)
if not expansion_count == 0:
delay += total_delay_time / expansion_count
#calc exp time
t_exp_1 = time.time()
for state in puzzle.next_states(current[1]):
parent_path = current[2][:]
parent_path.append(current[1])
util = u(delay, t_exp, w_t, w_f, g, state, goal_state_dictionary)
child = (util, state, parent_path, time.time())
if child[1] is puzzle.goal_state:
heapq.heappush(frontier,child)
elif child in closed or child in frontier:
print 'child explored'
elif util < Uhat:
print 'util too small (' + str(util)+')'
else:
expansion_count += 1
heapq.heappush(frontier, child)
total_exp_time+=time.time()-t_exp_1
t_exp = total_exp_time/expansion_count
frontier, Uhat = find_uhat(frontier, expansion_count, u, delay, t_exp, w_t, w_f, g, Uhat)
stopnow+=1
return False
def convert_to_tuples(state):
output = {}
for i in range(1, len(state)+1):
x = (i-1) % 4
w = int((i-1) / 4)
output[state[i-1]] = (x, w)
return output
def u(delay, t_exp, w_t, w_f, g, node, goal_state_dictionary):
'''
utility = something here ****
Involving w_t and w_f
^
U = max { max( n in frontier) - (w_f * f(n) + w_t * d(n) * delay * t_exp)}
^
You expand the node that produces the U value above
d(n) = Manhattan distance
f(n) = g*(n) + d(n)
Calculate d:
-Loop and use the difference between the index of each number
-in current state and the index of those same numbers in goal state
'''
utility = -1 * (w_f * g(node) + w_t * man_dist(node ,goal_state_dictionary) * delay * t_exp)
return utility
def g(node):
return len(node)
def man_dist(puzzle_state, goal_state_dict):
dict_puzzle = convert_to_tuples(puzzle_state)
d = 0
for i in xrange(1, len(goal_state_dict)):
dx = abs(dict_puzzle[i][0] - goal_state_dict[i][0])
dw = abs(dict_puzzle[i][1] - goal_state_dict[i][1])
d += (dx + dw)
return d
def find_uhat(frontier, count, u, delay, t_exp, w_t, w_f, g, Uhat):
if type(log(count, 2)) is int:
new_frontier = []
u_new = Uhat
for node in frontier:
util = u(delay, t_exp, w_t, w_f, g, node)
new_frontier.append((util, node[1], node[2], node[3]))
u_new = max(u_new, util)
return (heapq.heapify(new_frontier), u_new)
else:
return (frontier, Uhat)
#test cases
w_t = 9
w_f = 9
start_state = (0, 1, 2, 3, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12)
new_puz = Puzzle(start_state)
new_puz = Puzzle(new_puz.goal_state)
goal_state_dict = convert_to_tuples(new_puz.goal_state)
print bugsy(new_puz, u, g, w_t, w_f)
| 33.279412
| 107
| 0.554279
|
4a0a7d9427e6a1c84eed59ba6f78e616c60be9f1
| 1,309
|
py
|
Python
|
visualization_doc.py
|
adimaini/bias-scoring-algorithm
|
03d56b2836a9f6d30cbbb2ca3e9fb8f582d63e06
|
[
"MIT"
] | 2
|
2020-11-16T02:28:57.000Z
|
2020-11-20T02:05:10.000Z
|
visualization_doc.py
|
adimaini/bias-scoring-algorithm
|
03d56b2836a9f6d30cbbb2ca3e9fb8f582d63e06
|
[
"MIT"
] | 3
|
2020-11-23T02:26:47.000Z
|
2020-11-23T02:28:38.000Z
|
visualization_doc.py
|
adimaini/Text-Recognition-for-PII
|
03d56b2836a9f6d30cbbb2ca3e9fb8f582d63e06
|
[
"MIT"
] | 1
|
2020-11-25T00:31:39.000Z
|
2020-11-25T00:31:39.000Z
|
import lib.data_processing as lib
import importlib
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import texthero as hero
from collections import Counter
df = pd.read_csv('./bias_data/bias_data/transcripts/transcripts.csv')
print(df.shape)
df = df.iloc[:2000, :]
df['clean_text'] = hero.clean(df['transcript'])
df['tfidf_clean_text'] = hero.tfidf(df['clean_text'], max_features=200)
df['pca'] = hero.pca(df['tfidf_clean_text'], 3)
# print(df.head(5))
print(Counter(list(df['host'])).keys())
print(Counter(list(df['host'])).values())
# print(list(df['clean_text'])[:100])
hostNum = len(Counter(list(df['host'])).values())
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
x = list(x[0] for x in df['pca'])
y = list(x[1] for x in df['pca'])
z = list(x[2] for x in df['pca'])
maxLen = max([len(x) for x in df['host']])
c = []
nameMapping = dict()
for i in df['host']:
c.append(len(i)/maxLen)
nameMapping[len(i)/maxLen] = i
fig.suptitle('Transcript Dataset Visualization (2000 samples)')
sc = ax.scatter(x, y, z, c=c, cmap=plt.cm.get_cmap('Accent',hostNum))
formatter = plt.FuncFormatter(lambda val, loc: nameMapping[val])
plt.colorbar(sc, ticks=list(Counter(c).keys()), format=formatter)
plt.show()
| 31.166667
| 72
| 0.675325
|
4a0a7deb60c92cab7c792c9c5abb5dd4d02a1c13
| 9,645
|
py
|
Python
|
testsuite/ui/views/admin/audience/account.py
|
dlaso99/3scale-tests
|
b31a3b3596af6d632b393e383c0417ea56bd95ca
|
[
"Apache-2.0"
] | 5
|
2021-11-04T14:09:24.000Z
|
2021-12-23T13:48:36.000Z
|
testsuite/ui/views/admin/audience/account.py
|
dlaso99/3scale-tests
|
b31a3b3596af6d632b393e383c0417ea56bd95ca
|
[
"Apache-2.0"
] | 41
|
2021-11-03T14:27:21.000Z
|
2022-03-29T14:46:16.000Z
|
testsuite/ui/views/admin/audience/account.py
|
dlaso99/3scale-tests
|
b31a3b3596af6d632b393e383c0417ea56bd95ca
|
[
"Apache-2.0"
] | 12
|
2021-11-03T17:28:31.000Z
|
2021-11-30T12:28:25.000Z
|
"""View representations of Accounts pages"""
from widgetastic.widget import TextInput, GenericLocatorWidget, Text, View
from widgetastic_patternfly4 import PatternflyTable
from testsuite.ui.navigation import step
from testsuite.ui.views.admin.audience import BaseAudienceView
from testsuite.ui.widgets import ThreescaleDropdown, AudienceTable, ThreescaleCheckBox
from testsuite.ui.widgets.buttons import ThreescaleUpdateButton, ThreescaleDeleteButton, \
ThreescaleEditButton, ThreescaleSubmitButton, ThreescaleSearchButton
class AccountsView(BaseAudienceView):
"""View representation of Accounts Listing page"""
# TODO search will be separated into the AudienceTable Widget later.
path_pattern = '/buyers/accounts'
new_account = Text("//a[@href='/buyers/accounts/new']")
table = AudienceTable("//*[@id='buyer_accounts']")
search_button = ThreescaleSearchButton()
search_bar = TextInput(id="search_query")
def search(self, value: str):
"""Search in account table by given value"""
self.search_bar.fill(value)
self.search_button.click()
@step("AccountNewView")
def new(self):
"""Create new Account"""
self.new_account.click()
@step("AccountsDetailView")
def detail(self, account):
"""Opens detail Account by ID"""
self.table.row(_row__attr=('id', f'account_{account.entity_id}')).grouporg.click()
def prerequisite(self):
return BaseAudienceView
@property
def is_displayed(self):
return BaseAudienceView.is_displayed.fget(self) and self.new_account.is_displayed and \
self.table.is_displayed and self.path in self.browser.url
class AccountsDetailView(BaseAudienceView):
"""View representation of Account detail page"""
path_pattern = '/buyers/accounts/{account_id}'
edit_button = ThreescaleEditButton()
plan_dropdown = ThreescaleDropdown("//*[@id='account_contract_plan_id']")
change_plan_button = GenericLocatorWidget("//*[@value='Change']")
applications_button = Text("//*[contains(@title,'applications')]")
users_button = Text("//*[contains(@title,'users')]")
invoices_button = Text("//*[contains(@title,'invoices')]")
def __init__(self, parent, account):
super().__init__(parent, account_id=account.entity_id)
def change_plan(self, value):
"""Change account plan"""
self.plan_dropdown.select_by_value(value)
self.change_plan_button.click(handle_alert=True)
@step("AccountEditView")
def edit(self):
"""Edit account"""
self.edit_button.click()
@step("AccountApplicationsView")
def applications(self):
"""Open account's applications"""
self.applications_button.click()
@step("AccountUserView")
def users(self):
"""Open account's users"""
self.users_button.click()
@step("AccountInvoicesView")
def invoices(self):
"""Open account's users"""
self.invoices_button.click()
def prerequisite(self):
return AccountsView
@property
def is_displayed(self):
return BaseAudienceView.is_displayed.fget(self) and self.path in self.browser.url and \
self.edit_button.is_displayed and self.applications_button.is_displayed
class AccountNewView(BaseAudienceView):
"""View representation of New Account page"""
path_pattern = '/buyers/accounts/new'
username = TextInput(id='account_user_username')
email = TextInput(id='account_user_email')
password = TextInput(id='account_user_password')
organization = TextInput(id='account_org_name')
create_button = ThreescaleSubmitButton()
def create(self, username: str, email: str, password: str, organization: str):
"""Crate new account"""
self.username.fill(username)
self.email.fill(email)
self.password.fill(password)
self.organization.fill(organization)
self.create_button.click()
def prerequisite(self):
return AccountsView
@property
def is_displayed(self):
return BaseAudienceView.is_displayed.fget(self) and self.path in self.browser.url \
and self.username.is_displayed and self.email.is_displayed \
and self.organization.is_displayed
class AccountEditView(BaseAudienceView):
"""View representation of Edit Account page"""
path_pattern = "/buyers/accounts/{account_id}/edit"
org_name = TextInput(id="account_org_name")
update_button = GenericLocatorWidget("//input[@value='Update Account']")
delete_button = ThreescaleDeleteButton()
def __init__(self, parent, account):
super().__init__(parent, account_id=account.entity_id)
def update(self, org_name: str):
"""Update account"""
self.org_name.fill(org_name)
self.update_button.click()
def delete(self):
"""Delete account"""
self.delete_button.click()
def prerequisite(self):
return AccountsDetailView
@property
def is_displayed(self):
return BaseAudienceView.is_displayed.fget(self) and self.org_name.is_displayed \
and self.org_name.is_displayed and self.update_button.is_displayed
class AccountApplicationsView(BaseAudienceView):
"""View representation of Account's Applications page"""
path_pattern = "/buyers/accounts/{account_id}/applications"
create_button = Text("//*[contains(@href,'/applications/new')]")
def __init__(self, parent, account):
super().__init__(parent, account_id=account.entity_id)
@step("ApplicationNewView")
def new(self):
"""Crate new application"""
self.create_button.click()
def prerequisite(self):
return AccountsDetailView
@property
def is_displayed(self):
return BaseAudienceView.is_displayed.fget(self) and self.create_button.is_displayed and \
self.path in self.browser.url
class AccountInvoicesView(BaseAudienceView):
"""View representation of Account's Applications page"""
path_pattern = "/buyers/accounts/{account_id}/invoices"
create_button = Text(".action.new")
table = PatternflyTable(".data")
def __init__(self, parent, account):
super().__init__(parent, account_id=account.entity_id)
@step("InvoiceDetailView")
def new_invoice(self):
"""
Creates new invoice
Note: It creates new open invoice, without any form with random ID
"""
self.create_button.click()
next(self.table.rows()).id.click()
def prerequisite(self):
return AccountsDetailView
@property
def is_displayed(self):
return BaseAudienceView.is_displayed.fget(self) and self.create_button.is_displayed and \
self.path in self.browser.url
class LineItemForm(View):
"""Nested view for a Line add form"""
ROOT = "//div[@id='colorbox']"
name_input = TextInput("line_item[name]")
quantity_input = TextInput("line_item[quantity]")
description_input = TextInput("line_item[description]")
cost_input = TextInput("line_item[cost]")
submit = Text("//input[@type='submit']")
def add_item(self, name, quantity, cost, description):
"""Adds item to an invoice"""
self.name_input.fill(name)
self.quantity_input.fill(quantity)
self.description_input.fill(description)
self.cost_input.fill(cost)
self.submit.click()
class InvoiceDetailView(BaseAudienceView):
"""Invoice Detail page"""
issue_button = Text("//form[contains(@action, 'issue.js')]/button")
charge_button = Text("//form[contains(@action, 'charge.js')]/button")
id_field = Text("#field-friendly_id")
state_field = Text("#field-state")
# Selector which we can use to check if the charge has finished
paid_field = Text("//td[@id='field-state' and text()='Paid']")
add_item_btn = GenericLocatorWidget("//a[contains(@class,'action add')]")
line_item_form = View.nested(LineItemForm)
def add_item(self, name, quantity, cost, description):
"""Adds item to an invoice"""
self.add_item_btn.click()
self.line_item_form.wait_displayed()
self.line_item_form.add_item(name, quantity, cost, description)
def issue(self):
"""Issues the invoices (OPEN -> PENDING)"""
self.issue_button.click(handle_alert=True)
self.browser.wait_for_element(self.charge_button, timeout=10)
def charge(self):
"""Charges the invoices (PENDING -> PAID)"""
# Charge button has two alerts which completely messed up with widgetastic.
# https://issues.redhat.com/browse/THREESCALE-7276
self.browser.click(self.charge_button, ignore_ajax=True)
self.browser.handle_double_alert()
# Wait until charge is done
self.browser.wait_for_element(self.paid_field, timeout=5)
def prerequisite(self):
return AccountInvoicesView
class UsageRulesView(BaseAudienceView):
"""View representation of Account's Usage Rules page"""
path_pattern = "/site/usage_rules/edit"
account_plans_checkbox = ThreescaleCheckBox(locator="//input[@id='settings_account_plans_ui_visible']")
update_button = ThreescaleUpdateButton()
def account_plans(self):
"""Allow account plans"""
self.account_plans_checkbox.check()
self.update_button.click()
def prerequisite(self):
return BaseAudienceView
@property
def is_displayed(self):
return BaseAudienceView.is_displayed.fget(self) and self.account_plans_checkbox.is_displayed and \
self.path in self.browser.url
| 35.722222
| 107
| 0.689062
|
4a0a7e4b82d22a5c2e5634f4b28146de274c8106
| 167,879
|
py
|
Python
|
cime/scripts/tests/scripts_regression_tests.py
|
CLM-PFLOTRAN/E3SM
|
cedb30ce46658392447baff069a350bad4418753
|
[
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null |
cime/scripts/tests/scripts_regression_tests.py
|
CLM-PFLOTRAN/E3SM
|
cedb30ce46658392447baff069a350bad4418753
|
[
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null |
cime/scripts/tests/scripts_regression_tests.py
|
CLM-PFLOTRAN/E3SM
|
cedb30ce46658392447baff069a350bad4418753
|
[
"FTL",
"zlib-acknowledgement",
"RSA-MD"
] | null | null | null |
#!/usr/bin/env python
"""
Script containing CIME python regression test suite. This suite should be run
to confirm overall CIME correctness.
"""
import glob, os, re, shutil, signal, sys, tempfile, \
threading, time, logging, unittest, getpass, \
filecmp, time
from xml.etree.ElementTree import ParseError
LIB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)),"..","lib")
sys.path.append(LIB_DIR)
# Remove all pyc files to ensure we're testing the right things
import subprocess, argparse
subprocess.call('/bin/rm -f $(find . -name "*.pyc")', shell=True, cwd=LIB_DIR)
import six
from six import assertRaisesRegex
import stat as osstat
import collections
from CIME.utils import run_cmd, run_cmd_no_fail, get_lids, get_current_commit, safe_copy, CIMEError, get_cime_root
import get_tests
import CIME.test_scheduler, CIME.wait_for_tests
from CIME.test_scheduler import TestScheduler
from CIME.XML.compilers import Compilers
from CIME.XML.env_run import EnvRun
from CIME.XML.machines import Machines
from CIME.XML.files import Files
from CIME.case import Case
from CIME.code_checker import check_code, get_all_checkable_files
from CIME.test_status import *
SCRIPT_DIR = CIME.utils.get_scripts_root()
TOOLS_DIR = os.path.join(SCRIPT_DIR,"Tools")
TEST_COMPILER = None
GLOBAL_TIMEOUT = None
TEST_MPILIB = None
MACHINE = None
FAST_ONLY = False
NO_BATCH = False
NO_CMAKE = False
TEST_ROOT = None
NO_TEARDOWN = False
os.environ["CIME_GLOBAL_WALLTIME"] = "0:05:00"
# pragma pylint: disable=protected-access
###############################################################################
def run_cmd_assert_result(test_obj, cmd, from_dir=None, expected_stat=0, env=None, verbose=False):
###############################################################################
from_dir = os.getcwd() if from_dir is None else from_dir
stat, output, errput = run_cmd(cmd, from_dir=from_dir, env=env, verbose=verbose)
if expected_stat == 0:
expectation = "SHOULD HAVE WORKED, INSTEAD GOT STAT %s" % stat
else:
expectation = "EXPECTED STAT %s, INSTEAD GOT STAT %s" % (expected_stat, stat)
msg = \
"""
COMMAND: %s
FROM_DIR: %s
%s
OUTPUT: %s
ERRPUT: %s
""" % (cmd, from_dir, expectation, output, errput)
test_obj.assertEqual(stat, expected_stat, msg=msg)
return output
###############################################################################
def assert_test_status(test_obj, test_name, test_status_obj, test_phase, expected_stat):
###############################################################################
test_status = test_status_obj.get_status(test_phase)
test_obj.assertEqual(test_status, expected_stat, msg="Problem with {}: for phase '{}': has status '{}', expected '{}'".format(test_name, test_phase, test_status, expected_stat))
###############################################################################
def verify_perms(test_obj, root_dir):
###############################################################################
for root, dirs, files in os.walk(root_dir):
for filename in files:
full_path = os.path.join(root, filename)
st = os.stat(full_path)
test_obj.assertTrue(st.st_mode & osstat.S_IWGRP, msg="file {} is not group writeable".format(full_path))
test_obj.assertTrue(st.st_mode & osstat.S_IRGRP, msg="file {} is not group readable".format(full_path))
test_obj.assertTrue(st.st_mode & osstat.S_IROTH, msg="file {} is not world readable".format(full_path))
for dirname in dirs:
full_path = os.path.join(root, dirname)
st = os.stat(full_path)
test_obj.assertTrue(st.st_mode & osstat.S_IWGRP, msg="dir {} is not group writable".format(full_path))
test_obj.assertTrue(st.st_mode & osstat.S_IRGRP, msg="dir {} is not group readable".format(full_path))
test_obj.assertTrue(st.st_mode & osstat.S_IXGRP, msg="dir {} is not group executable".format(full_path))
test_obj.assertTrue(st.st_mode & osstat.S_IROTH, msg="dir {} is not world readable".format(full_path))
test_obj.assertTrue(st.st_mode & osstat.S_IXOTH, msg="dir {} is not world executable".format(full_path))
###############################################################################
class A_RunUnitTests(unittest.TestCase):
###############################################################################
def test_resolve_variable_name(self):
files = Files()
machinefile = files.get_value("MACHINES_SPEC_FILE")
self.assertTrue(os.path.isfile(machinefile),
msg="Path did not resolve to existing file %s" % machinefile)
def test_unittests(self):
# Finds all files contained in CIME/tests or its subdirectories that
# match the pattern 'test*.py', and runs the unit tests found there
# (i.e., tests defined using python's unittest module).
#
# This is analogous to running:
# python -m unittest discover -s CIME/tests -t .
# from cime/scripts/lib
#
# Yes, that means we have a bunch of unit tests run from this one unit
# test.
testsuite = unittest.defaultTestLoader.discover(
start_dir = os.path.join(LIB_DIR,"CIME","tests"),
pattern = 'test*.py',
top_level_dir = LIB_DIR)
testrunner = unittest.TextTestRunner(buffer=False)
# Disable logging; otherwise log messages written by code under test
# clutter the unit test output
log_lvl = logging.getLogger().getEffectiveLevel()
logging.disable(logging.CRITICAL)
try:
results = testrunner.run(testsuite)
finally:
logging.getLogger().setLevel(log_lvl)
self.assertTrue(results.wasSuccessful())
def test_lib_doctests(self):
# Find and run all the doctests in the lib directory tree
skip_list = ["six.py", "CIME/SystemTests/mvk.py", "CIME/SystemTests/pgn.py"]
for root, _, files in os.walk(LIB_DIR):
for file_ in files:
filepath = os.path.join(root, file_)[len(LIB_DIR)+1:]
if filepath.endswith(".py") and filepath not in skip_list:
with open(os.path.join(root, file_)) as fd:
content = fd.read()
if '>>>' in content:
print("Running doctests for {}".format(filepath))
run_cmd_assert_result(self, 'PYTHONPATH={}:$PYTHONPATH python -m doctest {} 2>&1'.format(LIB_DIR, filepath), from_dir=LIB_DIR)
else:
print("{} has no doctests".format(filepath))
###############################################################################
def make_fake_teststatus(path, testname, status, phase):
###############################################################################
expect(phase in CORE_PHASES, "Bad phase '%s'" % phase)
with TestStatus(test_dir=path, test_name=testname) as ts:
for core_phase in CORE_PHASES:
if core_phase == phase:
ts.set_status(core_phase, status, comments=("time=42" if phase == RUN_PHASE else ""))
break
else:
ts.set_status(core_phase, TEST_PASS_STATUS, comments=("time=42" if phase == RUN_PHASE else ""))
###############################################################################
def parse_test_status(line):
###############################################################################
regex = re.compile(r"Test '(\w+)' finished with status '(\w+)'")
m = regex.match(line)
return m.groups()
###############################################################################
def kill_subprocesses(name=None, sig=signal.SIGKILL, expected_num_killed=None, tester=None):
###############################################################################
# Kill all subprocesses
proc_ids = CIME.utils.find_proc_id(proc_name=name, children_only=True)
if (expected_num_killed is not None):
tester.assertEqual(len(proc_ids), expected_num_killed,
msg="Expected to find %d processes to kill, found %d" % (expected_num_killed, len(proc_ids)))
for proc_id in proc_ids:
try:
os.kill(proc_id, sig)
except OSError:
pass
###############################################################################
def kill_python_subprocesses(sig=signal.SIGKILL, expected_num_killed=None, tester=None):
###############################################################################
kill_subprocesses("[Pp]ython", sig, expected_num_killed, tester)
###########################################################################
def assert_dashboard_has_build(tester, build_name, expected_count=1):
###########################################################################
# Do not test E3SM dashboard if model is CESM
if CIME.utils.get_model() == "e3sm":
time.sleep(10) # Give chance for cdash to update
wget_file = tempfile.mktemp()
run_cmd_no_fail("wget https://my.cdash.org/api/v1/index.php?project=ACME_test --no-check-certificate -O %s" % wget_file)
raw_text = open(wget_file, "r").read()
os.remove(wget_file)
num_found = raw_text.count(build_name)
tester.assertEqual(num_found, expected_count,
msg="Dashboard did not have expected num occurances of build name '%s'. Expected %s, found %s" % (build_name, expected_count, num_found))
###############################################################################
def setup_proxy():
###############################################################################
if ("http_proxy" not in os.environ):
proxy = MACHINE.get_value("PROXY")
if (proxy is not None):
os.environ["http_proxy"] = proxy
return True
return False
###############################################################################
class N_TestUnitTest(unittest.TestCase):
###############################################################################
@classmethod
def setUpClass(cls):
cls._do_teardown = []
cls._testroot = os.path.join(TEST_ROOT, 'TestUnitTests')
cls._testdirs = []
def _has_unit_test_support(self):
if TEST_COMPILER is None:
default_compiler = MACHINE.get_default_compiler()
compiler = Compilers(MACHINE, compiler=default_compiler)
else:
compiler = Compilers(MACHINE, compiler=TEST_COMPILER)
attrs = {'MPILIB': 'mpi-serial', 'compile_threaded': 'FALSE'}
pfunit_path = compiler.get_optional_compiler_node("PFUNIT_PATH",
attributes=attrs)
if pfunit_path is None:
return False
else:
return True
def test_a_unit_test(self):
cls = self.__class__
if not self._has_unit_test_support():
self.skipTest("Skipping TestUnitTest - PFUNIT_PATH not found for the default compiler on this machine")
test_dir = os.path.join(cls._testroot,"unit_tester_test")
cls._testdirs.append(test_dir)
os.makedirs(test_dir)
unit_test_tool = os.path.abspath(os.path.join(get_cime_root(),"scripts","fortran_unit_testing","run_tests.py"))
test_spec_dir = os.path.join(os.path.dirname(unit_test_tool),"Examples", "interpolate_1d", "tests")
args = "--build-dir {} --test-spec-dir {}".format(test_dir, test_spec_dir)
args += " --machine {}".format(MACHINE.get_machine_name())
run_cmd_no_fail("{} {}".format(unit_test_tool, args))
cls._do_teardown.append(test_dir)
def test_b_cime_f90_unit_tests(self):
cls = self.__class__
if (FAST_ONLY):
self.skipTest("Skipping slow test")
if not self._has_unit_test_support():
self.skipTest("Skipping TestUnitTest - PFUNIT_PATH not found for the default compiler on this machine")
test_dir = os.path.join(cls._testroot,"driver_f90_tests")
cls._testdirs.append(test_dir)
os.makedirs(test_dir)
test_spec_dir = get_cime_root()
unit_test_tool = os.path.abspath(os.path.join(test_spec_dir,"scripts","fortran_unit_testing","run_tests.py"))
args = "--build-dir {} --test-spec-dir {}".format(test_dir, test_spec_dir)
args += " --machine {}".format(MACHINE.get_machine_name())
run_cmd_no_fail("{} {}".format(unit_test_tool, args))
cls._do_teardown.append(test_dir)
@classmethod
def tearDownClass(cls):
do_teardown = len(cls._do_teardown) > 0 and sys.exc_info() == (None, None, None) and not NO_TEARDOWN
teardown_root = True
for tfile in cls._testdirs:
if tfile not in cls._do_teardown:
print("Detected failed test or user request no teardown")
print("Leaving case directory : %s"%tfile)
teardown_root = False
elif do_teardown:
shutil.rmtree(tfile)
if teardown_root and do_teardown:
shutil.rmtree(cls._testroot)
###############################################################################
class J_TestCreateNewcase(unittest.TestCase):
###############################################################################
@classmethod
def setUpClass(cls):
cls._testdirs = []
cls._do_teardown = []
cls._testroot = os.path.join(TEST_ROOT, 'TestCreateNewcase')
def test_a_createnewcase(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'testcreatenewcase')
if os.path.exists(testdir):
shutil.rmtree(testdir)
args = " --case %s --compset X --output-root %s --handle-preexisting-dirs=r " % (testdir, cls._testroot)
if TEST_COMPILER is not None:
args = args + " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args = args + " --mpilib %s"%TEST_MPILIB
if CIME.utils.get_cime_default_driver() == "nuopc":
args += " --res f19_g17 "
else:
args += " --res f19_g16 "
cls._testdirs.append(testdir)
run_cmd_assert_result(self, "./create_newcase %s"%(args), from_dir=SCRIPT_DIR)
self.assertTrue(os.path.exists(testdir))
self.assertTrue(os.path.exists(os.path.join(testdir, "case.setup")))
run_cmd_assert_result(self, "./case.setup", from_dir=testdir)
run_cmd_assert_result(self, "./case.build", from_dir=testdir)
with Case(testdir, read_only=False) as case:
ntasks = case.get_value("NTASKS_ATM")
case.set_value("NTASKS_ATM", ntasks+1)
# this should fail with a locked file issue
run_cmd_assert_result(self, "./case.build",
from_dir=testdir, expected_stat=1)
run_cmd_assert_result(self, "./case.setup --reset", from_dir=testdir)
run_cmd_assert_result(self, "./case.build", from_dir=testdir)
with Case(testdir, read_only=False) as case:
case.set_value("CHARGE_ACCOUNT", "fred")
# this should not fail with a locked file issue
run_cmd_assert_result(self, "./case.build", from_dir=testdir)
run_cmd_assert_result(self, "./case.st_archive --test-all", from_dir=testdir)
# Trying to set values outside of context manager should fail
case = Case(testdir, read_only=False)
with self.assertRaises(CIMEError):
case.set_value("NTASKS_ATM", 42)
# Trying to read_xml with pending changes should fail
with self.assertRaises(CIMEError):
with Case(testdir, read_only=False) as case:
case.set_value("CHARGE_ACCOUNT", "fouc")
case.read_xml()
cls._do_teardown.append(testdir)
def test_aa_no_flush_on_instantiate(self):
testdir = os.path.join(self.__class__._testroot, 'testcreatenewcase')
with Case(testdir, read_only=False) as case:
for env_file in case._files:
self.assertFalse(env_file.needsrewrite, msg="Instantiating a case should not trigger a flush call")
with Case(testdir, read_only=False) as case:
case.set_value("HIST_OPTION","nyears")
runfile = case.get_env('run')
self.assertTrue(runfile.needsrewrite, msg="Expected flush call not triggered")
for env_file in case._files:
if env_file != runfile:
self.assertFalse(env_file.needsrewrite, msg="Unexpected flush triggered for file {}"
.format(env_file.filename))
# Flush the file
runfile.write()
# set it again to the same value
case.set_value("HIST_OPTION","nyears")
# now the file should not need to be flushed
for env_file in case._files:
self.assertFalse(env_file.needsrewrite, msg="Unexpected flush triggered for file {}"
.format(env_file.filename))
# Check once more with a new instance
with Case(testdir, read_only=False) as case:
case.set_value("HIST_OPTION","nyears")
for env_file in case._files:
self.assertFalse(env_file.needsrewrite, msg="Unexpected flush triggered for file {}"
.format(env_file.filename))
def test_b_user_mods(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'testusermods')
if os.path.exists(testdir):
shutil.rmtree(testdir)
cls._testdirs.append(testdir)
user_mods_dir = os.path.join(CIME.utils.get_python_libs_root(), "..", "tests", "user_mods_test1")
args = " --case %s --compset X --user-mods-dir %s --output-root %s --handle-preexisting-dirs=r"% (testdir, user_mods_dir, cls._testroot)
if TEST_COMPILER is not None:
args = args + " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args = args + " --mpilib %s"%TEST_MPILIB
if CIME.utils.get_cime_default_driver() == "nuopc":
args += " --res f19_g17 "
else:
args += " --res f19_g16 "
run_cmd_assert_result(self, "%s/create_newcase %s "
% (SCRIPT_DIR, args),from_dir=SCRIPT_DIR)
self.assertTrue(os.path.isfile(os.path.join(testdir,"SourceMods","src.drv","somefile.F90")), msg="User_mods SourceMod missing")
with open(os.path.join(testdir,"user_nl_cpl"),"r") as fd:
contents = fd.read()
self.assertTrue("a different cpl test option" in contents, msg="User_mods contents of user_nl_cpl missing")
self.assertTrue("a cpl namelist option" in contents, msg="User_mods contents of user_nl_cpl missing")
cls._do_teardown.append(testdir)
def test_c_create_clone_keepexe(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'test_create_clone_keepexe')
if os.path.exists(testdir):
shutil.rmtree(testdir)
prevtestdir = cls._testdirs[0]
user_mods_dir = os.path.join(CIME.utils.get_python_libs_root(), "..", "tests", "user_mods_test3")
cmd = "%s/create_clone --clone %s --case %s --keepexe --user-mods-dir %s" \
% (SCRIPT_DIR, prevtestdir, testdir, user_mods_dir)
run_cmd_assert_result(self, cmd, from_dir=SCRIPT_DIR, expected_stat=1)
def test_d_create_clone_new_user(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'test_create_clone_new_user')
if os.path.exists(testdir):
shutil.rmtree(testdir)
prevtestdir = cls._testdirs[0]
cls._testdirs.append(testdir)
# change the USER and CIME_OUTPUT_ROOT to nonsense values
# this is intended as a test of whether create_clone is independent of user
run_cmd_assert_result(self, "./xmlchange USER=this_is_not_a_user",
from_dir=prevtestdir)
fakeoutputroot = cls._testroot.replace(os.environ.get("USER"), "this_is_not_a_user")
run_cmd_assert_result(self, "./xmlchange CIME_OUTPUT_ROOT=%s"%fakeoutputroot,
from_dir=prevtestdir)
# this test should pass (user name is replaced)
run_cmd_assert_result(self, "%s/create_clone --clone %s --case %s " %
(SCRIPT_DIR, prevtestdir, testdir),from_dir=SCRIPT_DIR)
shutil.rmtree(testdir)
# this test should pass
run_cmd_assert_result(self, "%s/create_clone --clone %s --case %s --cime-output-root %s" %
(SCRIPT_DIR, prevtestdir, testdir, cls._testroot),from_dir=SCRIPT_DIR)
cls._do_teardown.append(testdir)
def test_dd_create_clone_not_writable(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'test_create_clone_not_writable')
if os.path.exists(testdir):
shutil.rmtree(testdir)
prevtestdir = cls._testdirs[0]
cls._testdirs.append(testdir)
with Case(prevtestdir, read_only=False) as case1:
case2 = case1.create_clone(testdir)
with self.assertRaises(CIMEError):
case2.set_value("CHARGE_ACCOUNT", "fouc")
def test_e_xmlquery(self):
# Set script and script path
xmlquery = "./xmlquery"
cls = self.__class__
casedir = cls._testdirs[0]
# Check for environment
self.assertTrue(os.path.isdir(SCRIPT_DIR))
self.assertTrue(os.path.isdir(TOOLS_DIR))
self.assertTrue(os.path.isfile(os.path.join(casedir,xmlquery)))
# Test command line options
with Case(casedir, read_only=True) as case:
STOP_N = case.get_value("STOP_N")
COMP_CLASSES = case.get_values("COMP_CLASSES")
BUILD_COMPLETE = case.get_value("BUILD_COMPLETE")
cmd = xmlquery + " STOP_N --value"
output = run_cmd_no_fail(cmd, from_dir=casedir)
self.assertTrue(output == str(STOP_N), msg="%s != %s"%(output, STOP_N))
cmd = xmlquery + " BUILD_COMPLETE --value"
output = run_cmd_no_fail(cmd, from_dir=casedir)
self.assertTrue(output == "TRUE", msg="%s != %s"%(output, BUILD_COMPLETE))
# we expect DOCN_MODE to be undefined in this X compset
# this test assures that we do not try to resolve this as a compvar
cmd = xmlquery + " DOCN_MODE --value"
_, output, error = run_cmd(cmd, from_dir=casedir)
self.assertTrue(error == "ERROR: No results found for variable DOCN_MODE",
msg="unexpected result for DOCN_MODE, output {}, error {}".
format(output, error))
for comp in COMP_CLASSES:
caseresult = case.get_value("NTASKS_%s"%comp)
cmd = xmlquery + " NTASKS_%s --value"%comp
output = run_cmd_no_fail(cmd, from_dir=casedir)
self.assertTrue(output == str(caseresult), msg="%s != %s"%(output, caseresult))
cmd = xmlquery + " NTASKS --subgroup %s --value"%comp
output = run_cmd_no_fail(cmd, from_dir=casedir)
self.assertTrue(output == str(caseresult), msg="%s != %s"%(output, caseresult))
if MACHINE.has_batch_system():
JOB_QUEUE = case.get_value("JOB_QUEUE", subgroup="case.run")
cmd = xmlquery + " JOB_QUEUE --subgroup case.run --value"
output = run_cmd_no_fail(cmd, from_dir=casedir)
self.assertTrue(output == JOB_QUEUE, msg="%s != %s"%(output, JOB_QUEUE))
cmd = xmlquery + " --listall"
run_cmd_no_fail(cmd, from_dir=casedir)
cls._do_teardown.append(cls._testroot)
def test_f_createnewcase_with_user_compset(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'testcreatenewcase_with_user_compset')
if os.path.exists(testdir):
shutil.rmtree(testdir)
cls._testdirs.append(testdir)
pesfile = os.path.join("..","src","drivers","mct","cime_config","config_pes.xml")
args = "--case %s --compset 2000_SATM_XLND_SICE_SOCN_XROF_XGLC_SWAV --pesfile %s --res f19_g16 --output-root %s --handle-preexisting-dirs=r" % (testdir, pesfile, cls._testroot)
if CIME.utils.get_model() == "cesm":
args += " --run-unsupported"
if TEST_COMPILER is not None:
args += " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args = args + " --mpilib %s"%TEST_MPILIB
run_cmd_assert_result(self, "%s/create_newcase %s"%(SCRIPT_DIR, args), from_dir=SCRIPT_DIR)
run_cmd_assert_result(self, "./case.setup", from_dir=testdir)
run_cmd_assert_result(self, "./case.build", from_dir=testdir)
cls._do_teardown.append(testdir)
def test_g_createnewcase_with_user_compset_and_env_mach_pes(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'testcreatenewcase_with_user_compset_and_env_mach_pes')
if os.path.exists(testdir):
shutil.rmtree(testdir)
previous_testdir = cls._testdirs[-1]
cls._testdirs.append(testdir)
pesfile = os.path.join(previous_testdir,"env_mach_pes.xml")
args = "--case %s --compset 2000_SATM_XLND_SICE_SOCN_XROF_XGLC_SWAV --pesfile %s --res f19_g16 --output-root %s --handle-preexisting-dirs=r" % (testdir, pesfile, cls._testroot)
if CIME.utils.get_model() == "cesm":
args += " --run-unsupported"
if TEST_COMPILER is not None:
args += " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args += " --mpilib %s"%TEST_MPILIB
run_cmd_assert_result(self, "%s/create_newcase %s"%(SCRIPT_DIR, args), from_dir=SCRIPT_DIR)
run_cmd_assert_result(self, "diff env_mach_pes.xml %s"%(previous_testdir), from_dir=testdir)
# this line should cause the diff to fail (I assume no machine is going to default to 17 tasks)
run_cmd_assert_result(self, "./xmlchange NTASKS=17", from_dir=testdir)
run_cmd_assert_result(self, "diff env_mach_pes.xml %s"%(previous_testdir), from_dir=testdir,
expected_stat=1)
cls._do_teardown.append(testdir)
def test_h_primary_component(self):
cls = self.__class__
testdir = os.path.join(cls._testroot, 'testprimarycomponent')
if os.path.exists(testdir):
shutil.rmtree(testdir)
cls._testdirs.append(testdir)
args = " --case CreateNewcaseTest --script-root %s --compset X --output-root %s --handle-preexisting-dirs u" % (testdir, cls._testroot)
if TEST_COMPILER is not None:
args += " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args += " --mpilib %s"%TEST_MPILIB
if CIME.utils.get_cime_default_driver() == "nuopc":
args += " --res f19_g17 "
else:
args += " --res f19_g16 "
run_cmd_assert_result(self, "%s/create_newcase %s" % (SCRIPT_DIR, args), from_dir=SCRIPT_DIR)
self.assertTrue(os.path.exists(testdir))
self.assertTrue(os.path.exists(os.path.join(testdir, "case.setup")))
with Case(testdir, read_only=False) as case:
case._compsetname = case.get_value("COMPSET")
case.set_comp_classes(case.get_values("COMP_CLASSES"))
primary = case._find_primary_component()
self.assertEqual(primary, "drv", msg="primary component test expected drv but got %s"%primary)
# now we are going to corrupt the case so that we can do more primary_component testing
case.set_valid_values("COMP_GLC","%s,fred"%case.get_value("COMP_GLC"))
case.set_value("COMP_GLC","fred")
primary = case._find_primary_component()
self.assertEqual(primary, "fred", msg="primary component test expected fred but got %s"%primary)
case.set_valid_values("COMP_ICE","%s,wilma"%case.get_value("COMP_ICE"))
case.set_value("COMP_ICE","wilma")
primary = case._find_primary_component()
self.assertEqual(primary, "wilma", msg="primary component test expected wilma but got %s"%primary)
case.set_valid_values("COMP_OCN","%s,bambam,docn"%case.get_value("COMP_OCN"))
case.set_value("COMP_OCN","bambam")
primary = case._find_primary_component()
self.assertEqual(primary, "bambam", msg="primary component test expected bambam but got %s"%primary)
case.set_valid_values("COMP_LND","%s,barney"%case.get_value("COMP_LND"))
case.set_value("COMP_LND","barney")
primary = case._find_primary_component()
# This is a "J" compset
self.assertEqual(primary, "allactive", msg="primary component test expected allactive but got %s"%primary)
case.set_value("COMP_OCN","docn")
case.set_valid_values("COMP_LND","%s,barney"%case.get_value("COMP_LND"))
case.set_value("COMP_LND","barney")
primary = case._find_primary_component()
self.assertEqual(primary, "barney", msg="primary component test expected barney but got %s"%primary)
case.set_valid_values("COMP_ATM","%s,wilma"%case.get_value("COMP_ATM"))
case.set_value("COMP_ATM","wilma")
primary = case._find_primary_component()
self.assertEqual(primary, "wilma", msg="primary component test expected wilma but got %s"%primary)
# this is a "E" compset
case._compsetname = case._compsetname.replace("XOCN","DOCN%SOM")
primary = case._find_primary_component()
self.assertEqual(primary, "allactive", msg="primary component test expected allactive but got %s"%primary)
# finally a "B" compset
case.set_value("COMP_OCN","bambam")
primary = case._find_primary_component()
self.assertEqual(primary, "allactive", msg="primary component test expected allactive but got %s"%primary)
cls._do_teardown.append(testdir)
def test_j_createnewcase_user_compset_vs_alias(self):
"""
Create a compset using the alias and another compset using the full compset name
and make sure they are the same by comparing the namelist files in CaseDocs.
Ignore the modelio files and clean the directory names out first.
"""
cls = self.__class__
testdir1 = os.path.join(cls._testroot, 'testcreatenewcase_user_compset')
if os.path.exists(testdir1):
shutil.rmtree(testdir1)
cls._testdirs.append(testdir1)
args = ' --case CreateNewcaseTest --script-root {} --compset 2000_DATM%NYF_SLND_SICE_DOCN%SOMAQP_SROF_SGLC_SWAV --res f19_g16 --output-root {} --handle-preexisting-dirs u' .format(testdir1, cls._testroot)
if CIME.utils.get_model() == "cesm":
args += " --run-unsupported"
if TEST_COMPILER is not None:
args += " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args += " --mpilib %s"%TEST_MPILIB
run_cmd_assert_result(self, "{}/create_newcase {}" .format (SCRIPT_DIR, args), from_dir=SCRIPT_DIR)
run_cmd_assert_result(self, "./case.setup ", from_dir=testdir1)
run_cmd_assert_result(self, "./preview_namelists ", from_dir=testdir1)
dir1 = os.path.join(testdir1,"CaseDocs")
dir2 = os.path.join(testdir1,"CleanCaseDocs")
os.mkdir(dir2)
for _file in os.listdir(dir1):
if "modelio" in _file:
continue
with open(os.path.join(dir1,_file),"r") as fi:
file_text = fi.read()
file_text = file_text.replace(os.path.basename(testdir1),"PATH")
file_text = re.sub(r"logfile =.*","",file_text)
with open(os.path.join(dir2,_file), "w") as fo:
fo.write(file_text)
cleancasedocs1 = dir2
testdir2 = os.path.join(cls._testroot, 'testcreatenewcase_alias_compset')
if os.path.exists(testdir2):
shutil.rmtree(testdir2)
cls._testdirs.append(testdir2)
args = ' --case CreateNewcaseTest --script-root {} --compset ADSOMAQP --res f19_g16 --output-root {} --handle-preexisting-dirs u'.format(testdir2, cls._testroot)
if CIME.utils.get_model() == "cesm":
args += " --run-unsupported"
if TEST_COMPILER is not None:
args += " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args += " --mpilib %s"%TEST_MPILIB
run_cmd_assert_result(self, "{}/create_newcase {}".format(SCRIPT_DIR, args), from_dir=SCRIPT_DIR)
run_cmd_assert_result(self, "./case.setup ", from_dir=testdir2)
run_cmd_assert_result(self, "./preview_namelists ", from_dir=testdir2)
dir1 = os.path.join(testdir2,"CaseDocs")
dir2 = os.path.join(testdir2,"CleanCaseDocs")
os.mkdir(dir2)
for _file in os.listdir(dir1):
if "modelio" in _file:
continue
with open(os.path.join(dir1,_file),"r") as fi:
file_text = fi.read()
file_text = file_text.replace(os.path.basename(testdir2),"PATH")
file_text = re.sub(r"logfile =.*","",file_text)
with open(os.path.join(dir2,_file), "w") as fo:
fo.write(file_text)
cleancasedocs2 = dir2
dcmp = filecmp.dircmp(cleancasedocs1, cleancasedocs2)
self.assertTrue(len(dcmp.diff_files) == 0, "CaseDocs differ {}".format(dcmp.diff_files))
cls._do_teardown.append(testdir1)
cls._do_teardown.append(testdir2)
def test_k_append_config(self):
machlist_before = MACHINE.list_available_machines()
self.assertEqual(len(machlist_before)>1, True, msg="Problem reading machine list")
newmachfile = os.path.join(get_cime_root(),"config",
"xml_schemas","config_machines_template.xml")
MACHINE.read(newmachfile)
machlist_after = MACHINE.list_available_machines()
self.assertEqual(len(machlist_after)-len(machlist_before), 1, msg="Not able to append config_machines.xml {} {}".format(len(machlist_after), len(machlist_before)))
self.assertEqual("mymachine" in machlist_after, True, msg="Not able to append config_machines.xml")
def test_m_createnewcase_alternate_drivers(self):
# Test that case.setup runs for nuopc and moab drivers
cls = self.__class__
model = CIME.utils.get_model()
for driver in ("nuopc", "moab"):
if not os.path.exists(os.path.join(get_cime_root(),"src","drivers",driver)):
self.skipTest("Skipping driver test for {}, driver not found".format(driver))
if ((model == 'cesm' and driver == 'moab') or
(model == 'e3sm' and driver == 'nuopc')):
continue
testdir = os.path.join(cls._testroot, 'testcreatenewcase.{}'.format( driver))
if os.path.exists(testdir):
shutil.rmtree(testdir)
args = " --driver {} --case {} --compset X --res f19_g16 --output-root {} --handle-preexisting-dirs=r".format(driver, testdir, cls._testroot)
if model == "cesm":
args += " --run-unsupported"
if TEST_COMPILER is not None:
args = args + " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args = args + " --mpilib %s"%TEST_MPILIB
cls._testdirs.append(testdir)
run_cmd_assert_result(self, "./create_newcase %s"%(args), from_dir=SCRIPT_DIR)
self.assertTrue(os.path.exists(testdir))
self.assertTrue(os.path.exists(os.path.join(testdir, "case.setup")))
run_cmd_assert_result(self, "./case.setup", from_dir=testdir)
with Case(testdir, read_only=False) as case:
comp_interface = case.get_value("COMP_INTERFACE")
self.assertTrue(driver == comp_interface, msg="%s != %s"%(driver, comp_interface))
cls._do_teardown.append(testdir)
def test_n_createnewcase_bad_compset(self):
cls = self.__class__
model = CIME.utils.get_model()
testdir = os.path.join(cls._testroot, 'testcreatenewcase_bad_compset')
if os.path.exists(testdir):
shutil.rmtree(testdir)
args = " --case %s --compset InvalidCompsetName --output-root %s --handle-preexisting-dirs=r " % (testdir, cls._testroot)
if model == "cesm":
args += " --run-unsupported"
if TEST_COMPILER is not None:
args = args + " --compiler %s"%TEST_COMPILER
if TEST_MPILIB is not None:
args = args + " --mpilib %s"%TEST_MPILIB
if CIME.utils.get_cime_default_driver() == "nuopc":
args += " --res f19_g17 "
else:
args += " --res f19_g16 "
cls._testdirs.append(testdir)
run_cmd_assert_result(self, "./create_newcase %s"%(args),
from_dir=SCRIPT_DIR, expected_stat=1)
self.assertFalse(os.path.exists(testdir))
@classmethod
def tearDownClass(cls):
do_teardown = len(cls._do_teardown) > 0 and sys.exc_info() == (None, None, None) and not NO_TEARDOWN
for tfile in cls._testdirs:
if tfile not in cls._do_teardown:
print("Detected failed test or user request no teardown")
print("Leaving case directory : %s"%tfile)
elif do_teardown:
try:
print ("Attempt to remove directory {}".format(tfile))
shutil.rmtree(tfile)
except BaseException:
print("Could not remove directory {}".format(tfile))
###############################################################################
class M_TestWaitForTests(unittest.TestCase):
###############################################################################
###########################################################################
def setUp(self):
###########################################################################
self._testroot = os.path.join(TEST_ROOT,"TestWaitForTests")
self._timestamp = CIME.utils.get_timestamp()
# basic tests
self._testdir_all_pass = os.path.join(self._testroot, 'scripts_regression_tests.testdir_all_pass')
self._testdir_with_fail = os.path.join(self._testroot, 'scripts_regression_tests.testdir_with_fail')
self._testdir_unfinished = os.path.join(self._testroot, 'scripts_regression_tests.testdir_unfinished')
self._testdir_unfinished2 = os.path.join(self._testroot, 'scripts_regression_tests.testdir_unfinished2')
# live tests
self._testdir_teststatus1 = os.path.join(self._testroot, 'scripts_regression_tests.testdir_teststatus1')
self._testdir_teststatus2 = os.path.join(self._testroot, 'scripts_regression_tests.testdir_teststatus2')
self._testdirs = [self._testdir_all_pass, self._testdir_with_fail, self._testdir_unfinished, self._testdir_unfinished2,
self._testdir_teststatus1, self._testdir_teststatus2]
basic_tests = self._testdirs[:self._testdirs.index(self._testdir_teststatus1)]
for testdir in self._testdirs:
if os.path.exists(testdir):
shutil.rmtree(testdir)
os.makedirs(testdir)
for r in range(10):
for testdir in basic_tests:
os.makedirs(os.path.join(testdir, str(r)))
make_fake_teststatus(os.path.join(testdir, str(r)), "Test_%d" % r, TEST_PASS_STATUS, RUN_PHASE)
make_fake_teststatus(os.path.join(self._testdir_with_fail, "5"), "Test_5", TEST_FAIL_STATUS, RUN_PHASE)
make_fake_teststatus(os.path.join(self._testdir_unfinished, "5"), "Test_5", TEST_PEND_STATUS, RUN_PHASE)
make_fake_teststatus(os.path.join(self._testdir_unfinished2, "5"), "Test_5", TEST_PASS_STATUS, SUBMIT_PHASE)
integration_tests = self._testdirs[len(basic_tests):]
for integration_test in integration_tests:
os.makedirs(os.path.join(integration_test, "0"))
make_fake_teststatus(os.path.join(integration_test, "0"), "Test_0", TEST_PASS_STATUS, CORE_PHASES[0])
# Set up proxy if possible
self._unset_proxy = setup_proxy()
self._thread_error = None
###########################################################################
def tearDown(self):
###########################################################################
do_teardown = sys.exc_info() == (None, None, None) and not NO_TEARDOWN
if do_teardown:
for testdir in self._testdirs:
shutil.rmtree(testdir)
kill_subprocesses()
if (self._unset_proxy):
del os.environ["http_proxy"]
###########################################################################
def simple_test(self, testdir, expected_results, extra_args="", build_name=None):
###########################################################################
# Need these flags to test dashboard if e3sm
if CIME.utils.get_model() == "e3sm" and build_name is not None:
extra_args += " -b %s" % build_name
expected_stat = 0 if expected_results == ["PASS"]*len(expected_results) else CIME.utils.TESTS_FAILED_ERR_CODE
output = run_cmd_assert_result(self, "%s/wait_for_tests -p ACME_test */TestStatus %s" % (TOOLS_DIR, extra_args),
from_dir=testdir, expected_stat=expected_stat)
lines = [line for line in output.splitlines() if line.startswith("Test '")]
self.assertEqual(len(lines), len(expected_results))
for idx, line in enumerate(lines):
testname, status = parse_test_status(line)
self.assertEqual(status, expected_results[idx])
self.assertEqual(testname, "Test_%d" % idx)
###########################################################################
def threaded_test(self, testdir, expected_results, extra_args="", build_name=None):
###########################################################################
try:
self.simple_test(testdir, expected_results, extra_args, build_name)
except AssertionError as e:
self._thread_error = str(e)
###########################################################################
def test_wait_for_test_all_pass(self):
###########################################################################
self.simple_test(self._testdir_all_pass, ["PASS"] * 10)
###########################################################################
def test_wait_for_test_with_fail(self):
###########################################################################
expected_results = ["FAIL" if item == 5 else "PASS" for item in range(10)]
self.simple_test(self._testdir_with_fail, expected_results)
###########################################################################
def test_wait_for_test_no_wait(self):
###########################################################################
expected_results = ["PEND" if item == 5 else "PASS" for item in range(10)]
self.simple_test(self._testdir_unfinished, expected_results, "-n")
###########################################################################
def test_wait_for_test_timeout(self):
###########################################################################
expected_results = ["PEND" if item == 5 else "PASS" for item in range(10)]
self.simple_test(self._testdir_unfinished, expected_results, "--timeout=3")
###########################################################################
def test_wait_for_test_wait_for_pend(self):
###########################################################################
run_thread = threading.Thread(target=self.threaded_test, args=(self._testdir_unfinished, ["PASS"] * 10))
run_thread.daemon = True
run_thread.start()
time.sleep(5) # Kinda hacky
self.assertTrue(run_thread.isAlive(), msg="wait_for_tests should have waited")
with TestStatus(test_dir=os.path.join(self._testdir_unfinished, "5")) as ts:
ts.set_status(RUN_PHASE, TEST_PASS_STATUS)
run_thread.join(timeout=10)
self.assertFalse(run_thread.isAlive(), msg="wait_for_tests should have finished")
self.assertTrue(self._thread_error is None, msg="Thread had failure: %s" % self._thread_error)
###########################################################################
def test_wait_for_test_wait_for_missing_run_phase(self):
###########################################################################
run_thread = threading.Thread(target=self.threaded_test, args=(self._testdir_unfinished2, ["PASS"] * 10))
run_thread.daemon = True
run_thread.start()
time.sleep(5) # Kinda hacky
self.assertTrue(run_thread.isAlive(), msg="wait_for_tests should have waited")
with TestStatus(test_dir=os.path.join(self._testdir_unfinished2, "5")) as ts:
ts.set_status(RUN_PHASE, TEST_PASS_STATUS)
run_thread.join(timeout=10)
self.assertFalse(run_thread.isAlive(), msg="wait_for_tests should have finished")
self.assertTrue(self._thread_error is None, msg="Thread had failure: %s" % self._thread_error)
###########################################################################
def test_wait_for_test_wait_kill(self):
###########################################################################
expected_results = ["PEND" if item == 5 else "PASS" for item in range(10)]
run_thread = threading.Thread(target=self.threaded_test, args=(self._testdir_unfinished, expected_results))
run_thread.daemon = True
run_thread.start()
time.sleep(5)
self.assertTrue(run_thread.isAlive(), msg="wait_for_tests should have waited")
kill_python_subprocesses(signal.SIGTERM, expected_num_killed=1, tester=self)
run_thread.join(timeout=10)
self.assertFalse(run_thread.isAlive(), msg="wait_for_tests should have finished")
self.assertTrue(self._thread_error is None, msg="Thread had failure: %s" % self._thread_error)
###########################################################################
def test_wait_for_test_cdash_pass(self):
###########################################################################
expected_results = ["PASS"] * 10
build_name = "regression_test_pass_" + self._timestamp
run_thread = threading.Thread(target=self.threaded_test,
args=(self._testdir_all_pass, expected_results, "", build_name))
run_thread.daemon = True
run_thread.start()
run_thread.join(timeout=10)
self.assertFalse(run_thread.isAlive(), msg="wait_for_tests should have finished")
self.assertTrue(self._thread_error is None, msg="Thread had failure: %s" % self._thread_error)
assert_dashboard_has_build(self, build_name)
###########################################################################
def test_wait_for_test_cdash_kill(self):
###########################################################################
expected_results = ["PEND" if item == 5 else "PASS" for item in range(10)]
build_name = "regression_test_kill_" + self._timestamp
run_thread = threading.Thread(target=self.threaded_test,
args=(self._testdir_unfinished, expected_results, "", build_name))
run_thread.daemon = True
run_thread.start()
time.sleep(5)
self.assertTrue(run_thread.isAlive(), msg="wait_for_tests should have waited")
kill_python_subprocesses(signal.SIGTERM, expected_num_killed=1, tester=self)
run_thread.join(timeout=10)
self.assertFalse(run_thread.isAlive(), msg="wait_for_tests should have finished")
self.assertTrue(self._thread_error is None, msg="Thread had failure: %s" % self._thread_error)
assert_dashboard_has_build(self, build_name)
if CIME.utils.get_model() == "e3sm":
cdash_result_dir = os.path.join(self._testdir_unfinished, "Testing")
tag_file = os.path.join(cdash_result_dir, "TAG")
self.assertTrue(os.path.isdir(cdash_result_dir))
self.assertTrue(os.path.isfile(tag_file))
tag = open(tag_file, "r").readlines()[0].strip()
xml_file = os.path.join(cdash_result_dir, tag, "Test.xml")
self.assertTrue(os.path.isfile(xml_file))
xml_contents = open(xml_file, "r").read()
self.assertTrue(r'<TestList><Test>Test_0</Test><Test>Test_1</Test><Test>Test_2</Test><Test>Test_3</Test><Test>Test_4</Test><Test>Test_5</Test><Test>Test_6</Test><Test>Test_7</Test><Test>Test_8</Test><Test>Test_9</Test></TestList>'
in xml_contents)
self.assertTrue(r'<Test Status="notrun"><Name>Test_5</Name>' in xml_contents)
# TODO: Any further checking of xml output worth doing?
###########################################################################
def live_test_impl(self, testdir, expected_results, last_phase, last_status):
###########################################################################
run_thread = threading.Thread(target=self.threaded_test, args=(testdir, expected_results))
run_thread.daemon = True
run_thread.start()
time.sleep(5)
self.assertTrue(run_thread.isAlive(), msg="wait_for_tests should have waited")
for core_phase in CORE_PHASES[1:]:
with TestStatus(test_dir=os.path.join(self._testdir_teststatus1, "0")) as ts:
ts.set_status(core_phase, last_status if core_phase == last_phase else TEST_PASS_STATUS)
time.sleep(5)
if core_phase != last_phase:
self.assertTrue(run_thread.isAlive(), msg="wait_for_tests should have waited after passing phase {}".format(core_phase))
else:
run_thread.join(timeout=10)
self.assertFalse(run_thread.isAlive(), msg="wait_for_tests should have finished after phase {}".format(core_phase))
break
self.assertTrue(self._thread_error is None, msg="Thread had failure: %s" % self._thread_error)
###########################################################################
def test_wait_for_test_test_status_integration_pass(self):
###########################################################################
self.live_test_impl(self._testdir_teststatus1, ["PASS"], RUN_PHASE, TEST_PASS_STATUS)
###########################################################################
def test_wait_for_test_test_status_integration_submit_fail(self):
###########################################################################
self.live_test_impl(self._testdir_teststatus1, ["FAIL"], SUBMIT_PHASE, TEST_FAIL_STATUS)
###############################################################################
class TestCreateTestCommon(unittest.TestCase):
###############################################################################
###########################################################################
def setUp(self):
###########################################################################
self._thread_error = None
self._unset_proxy = setup_proxy()
self._machine = MACHINE.get_machine_name()
self._compiler = MACHINE.get_default_compiler() if TEST_COMPILER is None else TEST_COMPILER
self._baseline_name = "fake_testing_only_%s" % CIME.utils.get_timestamp()
self._baseline_area = os.path.join(TEST_ROOT, "baselines")
self._testroot = TEST_ROOT
self._hasbatch = MACHINE.has_batch_system() and not NO_BATCH
self._do_teardown = not NO_TEARDOWN
###########################################################################
def tearDown(self):
###########################################################################
kill_subprocesses()
if (self._unset_proxy):
del os.environ["http_proxy"]
files_to_clean = []
baselines = os.path.join(self._baseline_area, self._baseline_name)
if (os.path.isdir(baselines)):
files_to_clean.append(baselines)
for test_id in ["master", self._baseline_name]:
for leftover in glob.glob(os.path.join(self._testroot, "*%s*" % test_id)):
files_to_clean.append(leftover)
do_teardown = self._do_teardown and sys.exc_info() == (None, None, None)
if (not do_teardown):
print("Detected failed test or user request no teardown")
print("Leaving files:")
for file_to_clean in files_to_clean:
print(" " + file_to_clean)
else:
# For batch machines need to avoid race condition as batch system
# finishes I/O for the case.
if self._hasbatch:
time.sleep(5)
for file_to_clean in files_to_clean:
if (os.path.isdir(file_to_clean)):
shutil.rmtree(file_to_clean)
else:
os.remove(file_to_clean)
###########################################################################
def _create_test(self, extra_args, test_id=None, pre_run_errors=False, run_errors=False, env_changes=""):
###########################################################################
# All stub model not supported in nuopc driver
driver = CIME.utils.get_cime_default_driver()
if driver == 'nuopc':
extra_args.append(" ^SMS.T42_T42.S")
test_id = CIME.utils.get_timestamp() if test_id is None else test_id
extra_args.append("-t {}".format(test_id))
extra_args.append("--baseline-root {}".format(self._baseline_area))
if NO_BATCH:
extra_args.append("--no-batch")
if TEST_COMPILER and ([extra_arg for extra_arg in extra_args if "--compiler" in extra_arg] == []):
extra_args.append("--compiler={}".format(TEST_COMPILER))
if TEST_MPILIB and ([extra_arg for extra_arg in extra_args if "--mpilib" in extra_arg] == []):
extra_args.append("--mpilib={}".format(TEST_MPILIB))
extra_args.append("--test-root={0} --output-root={0}".format(TEST_ROOT))
full_run = (set(extra_args) & set(["-n", "--namelist-only", "--no-setup", "--no-build"])) == set()
if self._hasbatch:
expected_stat = 0 if not pre_run_errors else CIME.utils.TESTS_FAILED_ERR_CODE
else:
expected_stat = 0 if not pre_run_errors and not run_errors else CIME.utils.TESTS_FAILED_ERR_CODE
run_cmd_assert_result(self, "{} {}/create_test {}".format(env_changes, SCRIPT_DIR, " ".join(extra_args)),
expected_stat=expected_stat)
if full_run:
self._wait_for_tests(test_id, expect_works=(not pre_run_errors and not run_errors))
###########################################################################
def _wait_for_tests(self, test_id, expect_works=True):
###########################################################################
if self._hasbatch:
timeout_arg = "--timeout={}".format(GLOBAL_TIMEOUT) if GLOBAL_TIMEOUT is not None else ""
expected_stat = 0 if expect_works else CIME.utils.TESTS_FAILED_ERR_CODE
run_cmd_assert_result(self, "{}/wait_for_tests {} *{}/TestStatus".format(TOOLS_DIR, timeout_arg, test_id),
from_dir=self._testroot, expected_stat=expected_stat)
###############################################################################
class O_TestTestScheduler(TestCreateTestCommon):
###############################################################################
###########################################################################
def test_a_phases(self):
###########################################################################
# exclude the MEMLEAK tests here.
tests = get_tests.get_full_test_names(["cime_test_only",
"^TESTMEMLEAKFAIL_P1.f09_g16.X",
"^TESTMEMLEAKPASS_P1.f09_g16.X",
"^TESTRUNSTARCFAIL_P1.f19_g16_rx1.A",
"^TESTTESTDIFF_P1.f19_g16_rx1.A",
"^TESTBUILDFAILEXC_P1.f19_g16_rx1.A",
"^TESTRUNFAILEXC_P1.f19_g16_rx1.A"],
self._machine, self._compiler)
self.assertEqual(len(tests), 3)
ct = TestScheduler(tests, test_root=TEST_ROOT, output_root=TEST_ROOT,
compiler=self._compiler, mpilib=TEST_MPILIB)
build_fail_test = [item for item in tests if "TESTBUILDFAIL" in item][0]
run_fail_test = [item for item in tests if "TESTRUNFAIL" in item][0]
pass_test = [item for item in tests if "TESTRUNPASS" in item][0]
self.assertTrue("BUILDFAIL" in build_fail_test, msg="Wrong test '%s'" % build_fail_test)
self.assertTrue("RUNFAIL" in run_fail_test, msg="Wrong test '%s'" % run_fail_test)
self.assertTrue("RUNPASS" in pass_test, msg="Wrong test '%s'" % pass_test)
for idx, phase in enumerate(ct._phases):
for test in ct._tests:
if (phase == CIME.test_scheduler.TEST_START):
continue
elif (phase == MODEL_BUILD_PHASE):
ct._update_test_status(test, phase, TEST_PEND_STATUS)
if (test == build_fail_test):
ct._update_test_status(test, phase, TEST_FAIL_STATUS)
self.assertTrue(ct._is_broken(test))
self.assertFalse(ct._work_remains(test))
else:
ct._update_test_status(test, phase, TEST_PASS_STATUS)
self.assertFalse(ct._is_broken(test))
self.assertTrue(ct._work_remains(test))
elif (phase == RUN_PHASE):
if (test == build_fail_test):
with self.assertRaises(CIMEError):
ct._update_test_status(test, phase, TEST_PEND_STATUS)
else:
ct._update_test_status(test, phase, TEST_PEND_STATUS)
self.assertFalse(ct._work_remains(test))
if (test == run_fail_test):
ct._update_test_status(test, phase, TEST_FAIL_STATUS)
self.assertTrue(ct._is_broken(test))
else:
ct._update_test_status(test, phase, TEST_PASS_STATUS)
self.assertFalse(ct._is_broken(test))
self.assertFalse(ct._work_remains(test))
else:
with self.assertRaises(CIMEError):
ct._update_test_status(test, ct._phases[idx+1], TEST_PEND_STATUS)
with self.assertRaises(CIMEError):
ct._update_test_status(test, phase, TEST_PASS_STATUS)
ct._update_test_status(test, phase, TEST_PEND_STATUS)
self.assertFalse(ct._is_broken(test))
self.assertTrue(ct._work_remains(test))
with self.assertRaises(CIMEError):
ct._update_test_status(test, phase, TEST_PEND_STATUS)
ct._update_test_status(test, phase, TEST_PASS_STATUS)
with self.assertRaises(CIMEError):
ct._update_test_status(test, phase, TEST_FAIL_STATUS)
self.assertFalse(ct._is_broken(test))
self.assertTrue(ct._work_remains(test))
###########################################################################
def test_b_full(self):
###########################################################################
tests = get_tests.get_full_test_names(["cime_test_only"], self._machine, self._compiler)
test_id="%s-%s" % (self._baseline_name, CIME.utils.get_timestamp())
ct = TestScheduler(tests, test_id=test_id, no_batch=NO_BATCH, test_root=TEST_ROOT,
output_root=TEST_ROOT,compiler=self._compiler, mpilib=TEST_MPILIB)
build_fail_test = [item for item in tests if "TESTBUILDFAIL_" in item][0]
build_fail_exc_test = [item for item in tests if "TESTBUILDFAILEXC" in item][0]
run_fail_test = [item for item in tests if "TESTRUNFAIL_" in item][0]
run_fail_exc_test = [item for item in tests if "TESTRUNFAILEXC" in item][0]
pass_test = [item for item in tests if "TESTRUNPASS" in item][0]
test_diff_test = [item for item in tests if "TESTTESTDIFF" in item][0]
mem_fail_test = [item for item in tests if "TESTMEMLEAKFAIL" in item][0]
mem_pass_test = [item for item in tests if "TESTMEMLEAKPASS" in item][0]
st_arch_fail_test = [item for item in tests if "TESTRUNSTARCFAIL" in item][0]
log_lvl = logging.getLogger().getEffectiveLevel()
logging.disable(logging.CRITICAL)
try:
ct.run_tests()
finally:
logging.getLogger().setLevel(log_lvl)
self._wait_for_tests(test_id, expect_works=False)
test_statuses = glob.glob("%s/*%s/TestStatus" % (self._testroot, test_id))
self.assertEqual(len(tests), len(test_statuses))
for test_status in test_statuses:
ts = TestStatus(test_dir=os.path.dirname(test_status))
test_name = ts.get_name()
log_files = glob.glob("%s/%s*%s/TestStatus.log" % (self._testroot, test_name, test_id))
self.assertEqual(len(log_files), 1, "Expected exactly one TestStatus.log file, found %d" % len(log_files))
log_file = log_files[0]
if (test_name == build_fail_test):
assert_test_status(self, test_name, ts, MODEL_BUILD_PHASE, TEST_FAIL_STATUS)
data = open(log_file, "r").read()
self.assertTrue("Intentional fail for testing infrastructure" in data,
"Broken test did not report build error:\n%s" % data)
elif (test_name == build_fail_exc_test):
data = open(log_file, "r").read()
assert_test_status(self, test_name, ts, SHAREDLIB_BUILD_PHASE, TEST_FAIL_STATUS)
self.assertTrue("Exception from init" in data,
"Broken test did not report build error:\n%s" % data)
elif (test_name == run_fail_test):
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_FAIL_STATUS)
elif (test_name == run_fail_exc_test):
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_FAIL_STATUS)
data = open(log_file, "r").read()
self.assertTrue("Exception from run_phase" in data,
"Broken test did not report run error:\n%s" % data)
elif (test_name == mem_fail_test):
assert_test_status(self, test_name, ts, MEMLEAK_PHASE, TEST_FAIL_STATUS)
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_PASS_STATUS)
elif (test_name == test_diff_test):
assert_test_status(self, test_name, ts, "COMPARE_base_rest", TEST_FAIL_STATUS)
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_PASS_STATUS)
elif test_name == st_arch_fail_test:
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_PASS_STATUS)
assert_test_status(self, test_name, ts, STARCHIVE_PHASE, TEST_FAIL_STATUS)
else:
self.assertTrue(test_name in [pass_test, mem_pass_test])
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_PASS_STATUS)
if (test_name == mem_pass_test):
assert_test_status(self, test_name, ts, MEMLEAK_PHASE, TEST_PASS_STATUS)
###########################################################################
def test_c_use_existing(self):
###########################################################################
tests = get_tests.get_full_test_names(["TESTBUILDFAIL_P1.f19_g16_rx1.A", "TESTRUNFAIL_P1.f19_g16_rx1.A", "TESTRUNPASS_P1.f19_g16_rx1.A"],
self._machine, self._compiler)
test_id="%s-%s" % (self._baseline_name, CIME.utils.get_timestamp())
ct = TestScheduler(tests, test_id=test_id, no_batch=NO_BATCH, test_root=TEST_ROOT,
output_root=TEST_ROOT,compiler=self._compiler, mpilib=TEST_MPILIB)
build_fail_test = [item for item in tests if "TESTBUILDFAIL" in item][0]
run_fail_test = [item for item in tests if "TESTRUNFAIL" in item][0]
pass_test = [item for item in tests if "TESTRUNPASS" in item][0]
log_lvl = logging.getLogger().getEffectiveLevel()
logging.disable(logging.CRITICAL)
try:
ct.run_tests()
finally:
logging.getLogger().setLevel(log_lvl)
test_statuses = glob.glob("%s/*%s/TestStatus" % (self._testroot, test_id))
self.assertEqual(len(tests), len(test_statuses))
self._wait_for_tests(test_id, expect_works=False)
for test_status in test_statuses:
casedir = os.path.dirname(test_status)
ts = TestStatus(test_dir=casedir)
test_name = ts.get_name()
if test_name == build_fail_test:
assert_test_status(self, test_name, ts, MODEL_BUILD_PHASE, TEST_FAIL_STATUS)
with TestStatus(test_dir=casedir) as ts:
ts.set_status(MODEL_BUILD_PHASE, TEST_PEND_STATUS)
elif test_name == run_fail_test:
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_FAIL_STATUS)
with TestStatus(test_dir=casedir) as ts:
ts.set_status(SUBMIT_PHASE, TEST_PEND_STATUS)
else:
self.assertTrue(test_name == pass_test)
assert_test_status(self, test_name, ts, MODEL_BUILD_PHASE, TEST_PASS_STATUS)
assert_test_status(self, test_name, ts, SUBMIT_PHASE, TEST_PASS_STATUS)
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_PASS_STATUS)
os.environ["TESTBUILDFAIL_PASS"] = "True"
os.environ["TESTRUNFAIL_PASS"] = "True"
ct2 = TestScheduler(tests, test_id=test_id, no_batch=NO_BATCH, use_existing=True,
test_root=TEST_ROOT,output_root=TEST_ROOT,compiler=self._compiler,
mpilib=TEST_MPILIB)
log_lvl = logging.getLogger().getEffectiveLevel()
logging.disable(logging.CRITICAL)
try:
ct2.run_tests()
finally:
logging.getLogger().setLevel(log_lvl)
self._wait_for_tests(test_id)
for test_status in test_statuses:
ts = TestStatus(test_dir=os.path.dirname(test_status))
test_name = ts.get_name()
assert_test_status(self, test_name, ts, MODEL_BUILD_PHASE, TEST_PASS_STATUS)
assert_test_status(self, test_name, ts, SUBMIT_PHASE, TEST_PASS_STATUS)
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_PASS_STATUS)
del os.environ["TESTBUILDFAIL_PASS"]
del os.environ["TESTRUNFAIL_PASS"]
# test that passed tests are not re-run
ct2 = TestScheduler(tests, test_id=test_id, no_batch=NO_BATCH, use_existing=True,
test_root=TEST_ROOT,output_root=TEST_ROOT,compiler=self._compiler,
mpilib=TEST_MPILIB)
log_lvl = logging.getLogger().getEffectiveLevel()
logging.disable(logging.CRITICAL)
try:
ct2.run_tests()
finally:
logging.getLogger().setLevel(log_lvl)
self._wait_for_tests(test_id)
for test_status in test_statuses:
ts = TestStatus(test_dir=os.path.dirname(test_status))
test_name = ts.get_name()
assert_test_status(self, test_name, ts, MODEL_BUILD_PHASE, TEST_PASS_STATUS)
assert_test_status(self, test_name, ts, SUBMIT_PHASE, TEST_PASS_STATUS)
assert_test_status(self, test_name, ts, RUN_PHASE, TEST_PASS_STATUS)
###########################################################################
def test_d_retry(self):
###########################################################################
args = ["TESTBUILDFAIL_P1.f19_g16_rx1.A", "TESTRUNFAIL_P1.f19_g16_rx1.A", "TESTRUNPASS_P1.f19_g16_rx1.A", "--retry=1"]
self._create_test(args)
###############################################################################
class P_TestJenkinsGenericJob(TestCreateTestCommon):
###############################################################################
###########################################################################
def setUp(self):
###########################################################################
if CIME.utils.get_model() != "e3sm":
self.skipTest("Skipping Jenkins tests. E3SM feature")
TestCreateTestCommon.setUp(self)
# Need to run in a subdir in order to not have CTest clash. Name it
# such that it should be cleaned up by the parent tearDown
self._testdir = os.path.join(self._testroot, "jenkins_test_%s" % self._baseline_name)
os.makedirs(self._testdir)
# Change root to avoid clashing with other jenkins_generic_jobs
self._jenkins_root = os.path.join(self._testdir, "J")
###########################################################################
def tearDown(self):
###########################################################################
TestCreateTestCommon.tearDown(self)
if "TESTRUNDIFF_ALTERNATE" in os.environ:
del os.environ["TESTRUNDIFF_ALTERNATE"]
###########################################################################
def simple_test(self, expect_works, extra_args, build_name=None):
###########################################################################
if NO_BATCH:
extra_args += " --no-batch"
# Need these flags to test dashboard if e3sm
if CIME.utils.get_model() == "e3sm" and build_name is not None:
extra_args += " -p ACME_test --submit-to-cdash --cdash-build-group=Nightly -c %s" % build_name
run_cmd_assert_result(self, "%s/jenkins_generic_job -r %s %s -B %s" % (TOOLS_DIR, self._testdir, extra_args, self._baseline_area),
from_dir=self._testdir, expected_stat=(0 if expect_works else CIME.utils.TESTS_FAILED_ERR_CODE))
###########################################################################
def threaded_test(self, expect_works, extra_args, build_name=None):
###########################################################################
try:
self.simple_test(expect_works, extra_args, build_name)
except AssertionError as e:
self._thread_error = str(e)
###########################################################################
def assert_num_leftovers(self, suite):
###########################################################################
num_tests_in_tiny = len(get_tests.get_test_suite(suite))
jenkins_dirs = glob.glob("%s/*%s*/" % (self._jenkins_root, self._baseline_name.capitalize())) # case dirs
# scratch_dirs = glob.glob("%s/*%s*/" % (self._testroot, test_id)) # blr/run dirs
self.assertEqual(num_tests_in_tiny, len(jenkins_dirs),
msg="Wrong number of leftover directories in %s, expected %d, see %s" % \
(self._jenkins_root, num_tests_in_tiny, jenkins_dirs))
# JGF: Can't test this at the moment due to root change flag given to jenkins_generic_job
# self.assertEqual(num_tests_in_tiny + 1, len(scratch_dirs),
# msg="Wrong number of leftover directories in %s, expected %d, see %s" % \
# (self._testroot, num_tests_in_tiny, scratch_dirs))
###########################################################################
def test_jenkins_generic_job(self):
###########################################################################
# Generate fresh baselines so that this test is not impacted by
# unresolved diffs
self.simple_test(True, "-t cime_test_only_pass -g -b %s" % self._baseline_name)
self.assert_num_leftovers("cime_test_only_pass")
build_name = "jenkins_generic_job_pass_%s" % CIME.utils.get_timestamp()
self.simple_test(True, "-t cime_test_only_pass -b %s" % self._baseline_name, build_name=build_name)
self.assert_num_leftovers("cime_test_only_pass") # jenkins_generic_job should have automatically cleaned up leftovers from prior run
assert_dashboard_has_build(self, build_name)
###########################################################################
def test_jenkins_generic_job_kill(self):
###########################################################################
build_name = "jenkins_generic_job_kill_%s" % CIME.utils.get_timestamp()
run_thread = threading.Thread(target=self.threaded_test, args=(False, " -t cime_test_only_slow_pass -b master --baseline-compare=no", build_name))
run_thread.daemon = True
run_thread.start()
time.sleep(120)
kill_subprocesses(sig=signal.SIGTERM)
run_thread.join(timeout=30)
self.assertFalse(run_thread.isAlive(), msg="jenkins_generic_job should have finished")
self.assertTrue(self._thread_error is None, msg="Thread had failure: %s" % self._thread_error)
assert_dashboard_has_build(self, build_name)
###########################################################################
def test_jenkins_generic_job_realistic_dash(self):
###########################################################################
# The actual quality of the cdash results for this test can only
# be inspected manually
# Generate fresh baselines so that this test is not impacted by
# unresolved diffs
self.simple_test(False, "-t cime_test_all -g -b %s" % self._baseline_name)
self.assert_num_leftovers("cime_test_all")
# Should create a diff
os.environ["TESTRUNDIFF_ALTERNATE"] = "True"
# Should create a nml diff
# Modify namelist
fake_nl = """
&fake_nml
fake_item = 'fake'
fake = .true.
/"""
baseline_glob = glob.glob(os.path.join(self._baseline_area, self._baseline_name, "TESTRUNPASS*"))
self.assertEqual(len(baseline_glob), 1, msg="Expected one match, got:\n%s" % "\n".join(baseline_glob))
for baseline_dir in baseline_glob:
nl_path = os.path.join(baseline_dir, "CaseDocs", "datm_in")
self.assertTrue(os.path.isfile(nl_path), msg="Missing file %s" % nl_path)
os.chmod(nl_path, osstat.S_IRUSR | osstat.S_IWUSR)
with open(nl_path, "a") as nl_file:
nl_file.write(fake_nl)
build_name = "jenkins_generic_job_mixed_%s" % CIME.utils.get_timestamp()
self.simple_test(False, "-t cime_test_all -b %s" % self._baseline_name, build_name=build_name)
self.assert_num_leftovers("cime_test_all") # jenkins_generic_job should have automatically cleaned up leftovers from prior run
assert_dashboard_has_build(self, build_name)
###############################################################################
class M_TestCimePerformance(TestCreateTestCommon):
###############################################################################
###########################################################################
def test_cime_case_ctrl_performance(self):
###########################################################################
ts = time.time()
num_repeat = 5
for _ in range(num_repeat):
self._create_test(["cime_tiny","--no-build"])
elapsed = time.time() - ts
print("Perf test result: {:0.2f}".format(elapsed))
###############################################################################
class T_TestRunRestart(TestCreateTestCommon):
###############################################################################
###########################################################################
def test_run_restart(self):
###########################################################################
driver = CIME.utils.get_cime_default_driver()
if driver == "mct":
walltime="00:15:00"
else:
walltime="00:30:00"
self._create_test(["--walltime "+walltime,"NODEFAIL_P1.f09_g16.X"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"{}.{}".format(CIME.utils.get_full_test_name("NODEFAIL_P1.f09_g16.X", machine=self._machine, compiler=self._compiler), self._baseline_name))
rundir = run_cmd_no_fail("./xmlquery RUNDIR --value", from_dir=casedir)
fail_sentinel = os.path.join(rundir, "FAIL_SENTINEL")
self.assertTrue(os.path.exists(fail_sentinel), msg="Missing %s" % fail_sentinel)
self.assertEqual(open(fail_sentinel, "r").read().count("FAIL"), 3)
###########################################################################
def test_run_restart_too_many_fails(self):
###########################################################################
driver = CIME.utils.get_cime_default_driver()
if driver == "mct":
walltime="00:15:00"
else:
walltime="00:30:00"
self._create_test(["--walltime "+walltime,"NODEFAIL_P1.f09_g16.X"], test_id=self._baseline_name, env_changes="NODEFAIL_NUM_FAILS=5", run_errors=True)
casedir = os.path.join(self._testroot,
"{}.{}".format(CIME.utils.get_full_test_name("NODEFAIL_P1.f09_g16.X", machine=self._machine, compiler=self._compiler), self._baseline_name))
rundir = run_cmd_no_fail("./xmlquery RUNDIR --value", from_dir=casedir)
fail_sentinel = os.path.join(rundir, "FAIL_SENTINEL")
self.assertTrue(os.path.exists(fail_sentinel), msg="Missing %s" % fail_sentinel)
self.assertEqual(open(fail_sentinel, "r").read().count("FAIL"), 4)
###############################################################################
class Q_TestBlessTestResults(TestCreateTestCommon):
###############################################################################
###########################################################################
def setUp(self):
###########################################################################
TestCreateTestCommon.setUp(self)
# Set a restrictive umask so we can test that SharedAreas used for
# recording baselines are working
restrictive_mask = 0o027
self._orig_umask = os.umask(restrictive_mask)
###########################################################################
def tearDown(self):
###########################################################################
TestCreateTestCommon.tearDown(self)
if "TESTRUNDIFF_ALTERNATE" in os.environ:
del os.environ["TESTRUNDIFF_ALTERNATE"]
os.umask(self._orig_umask)
###############################################################################
def test_bless_test_results(self):
###############################################################################
# Generate some baselines
test_name = "TESTRUNDIFF_P1.f19_g16_rx1.A"
if CIME.utils.get_model() == "e3sm":
genargs = ["-g", "-o", "-b", self._baseline_name, test_name]
compargs = ["-c", "-b", self._baseline_name, test_name]
else:
genargs = ["-g", self._baseline_name, "-o", test_name,
"--baseline-root ", self._baseline_area]
compargs = ["-c", self._baseline_name, test_name,
"--baseline-root ", self._baseline_area]
self._create_test(genargs)
# Hist compare should pass
self._create_test(compargs)
# Change behavior
os.environ["TESTRUNDIFF_ALTERNATE"] = "True"
# Hist compare should now fail
test_id = "%s-%s" % (self._baseline_name, CIME.utils.get_timestamp())
self._create_test(compargs, test_id=test_id, run_errors=True)
# compare_test_results should detect the fail
cpr_cmd = "{}/compare_test_results --test-root {} -t {} 2>&1" \
.format(TOOLS_DIR, TEST_ROOT, test_id)
output = run_cmd_assert_result(self, cpr_cmd, expected_stat=CIME.utils.TESTS_FAILED_ERR_CODE)
# use regex
expected_pattern = re.compile(r'FAIL %s[^\s]* BASELINE' % test_name)
the_match = expected_pattern.search(output)
self.assertNotEqual(the_match, None,
msg="Cmd '%s' failed to display failed test in output:\n%s" % (cpr_cmd, output))
# Bless
run_cmd_no_fail("{}/bless_test_results --test-root {} --hist-only --force -t {}"
.format(TOOLS_DIR, TEST_ROOT, test_id))
# Hist compare should now pass again
self._create_test(compargs)
verify_perms(self, self._baseline_area)
###############################################################################
def test_rebless_namelist(self):
###############################################################################
# Generate some namelist baselines
test_to_change = "TESTRUNPASS_P1.f19_g16_rx1.A"
if CIME.utils.get_model() == "e3sm":
genargs = ["-n", "-g", "-o", "-b", self._baseline_name, "cime_test_only_pass"]
compargs = ["-n", "-c", "-b", self._baseline_name, "cime_test_only_pass"]
else:
genargs = ["-n", "-g", self._baseline_name, "-o", "cime_test_only_pass"]
compargs = ["-n", "-c", self._baseline_name, "cime_test_only_pass"]
self._create_test(genargs)
# Basic namelist compare
test_id = "%s-%s" % (self._baseline_name, CIME.utils.get_timestamp())
self._create_test(compargs, test_id=test_id)
# Check standalone case.cmpgen_namelists
casedir = os.path.join(self._testroot,
"%s.C.%s" % (CIME.utils.get_full_test_name(test_to_change, machine=self._machine, compiler=self._compiler), test_id))
run_cmd_assert_result(self, "./case.cmpgen_namelists", from_dir=casedir)
# compare_test_results should pass
cpr_cmd = "{}/compare_test_results --test-root {} -n -t {} 2>&1" \
.format(TOOLS_DIR, TEST_ROOT, test_id)
output = run_cmd_assert_result(self, cpr_cmd)
# use regex
expected_pattern = re.compile(r'PASS %s[^\s]* NLCOMP' % test_to_change)
the_match = expected_pattern.search(output)
self.assertNotEqual(the_match, None,
msg="Cmd '%s' failed to display passed test in output:\n%s" % (cpr_cmd, output))
# Modify namelist
fake_nl = """
&fake_nml
fake_item = 'fake'
fake = .true.
/"""
baseline_area = self._baseline_area
baseline_glob = glob.glob(os.path.join(baseline_area, self._baseline_name, "TEST*"))
self.assertEqual(len(baseline_glob), 3, msg="Expected three matches, got:\n%s" % "\n".join(baseline_glob))
for baseline_dir in baseline_glob:
nl_path = os.path.join(baseline_dir, "CaseDocs", "datm_in")
self.assertTrue(os.path.isfile(nl_path), msg="Missing file %s" % nl_path)
os.chmod(nl_path, osstat.S_IRUSR | osstat.S_IWUSR)
with open(nl_path, "a") as nl_file:
nl_file.write(fake_nl)
# Basic namelist compare should now fail
test_id = "%s-%s" % (self._baseline_name, CIME.utils.get_timestamp())
self._create_test(compargs, test_id=test_id, pre_run_errors=True)
casedir = os.path.join(self._testroot,
"%s.C.%s" % (CIME.utils.get_full_test_name(test_to_change, machine=self._machine, compiler=self._compiler), test_id))
run_cmd_assert_result(self, "./case.cmpgen_namelists", from_dir=casedir, expected_stat=100)
# preview namelists should work
run_cmd_assert_result(self, "./preview_namelists", from_dir=casedir)
# This should still fail
run_cmd_assert_result(self, "./case.cmpgen_namelists", from_dir=casedir, expected_stat=100)
# compare_test_results should fail
cpr_cmd = "{}/compare_test_results --test-root {} -n -t {} 2>&1" \
.format(TOOLS_DIR, TEST_ROOT, test_id)
output = run_cmd_assert_result(self, cpr_cmd, expected_stat=CIME.utils.TESTS_FAILED_ERR_CODE)
# use regex
expected_pattern = re.compile(r'FAIL %s[^\s]* NLCOMP' % test_to_change)
the_match = expected_pattern.search(output)
self.assertNotEqual(the_match, None,
msg="Cmd '%s' failed to display passed test in output:\n%s" % (cpr_cmd, output))
# Bless
run_cmd_no_fail("{}/bless_test_results --test-root {} -n --force -t {}"
.format(TOOLS_DIR, TEST_ROOT, test_id))
# Basic namelist compare should now pass again
self._create_test(compargs)
verify_perms(self, self._baseline_area)
class X_TestQueryConfig(unittest.TestCase):
def test_query_compsets(self):
run_cmd_no_fail("{}/query_config --compsets".format(SCRIPT_DIR))
def test_query_components(self):
run_cmd_no_fail("{}/query_config --components".format(SCRIPT_DIR))
def test_query_grids(self):
run_cmd_no_fail("{}/query_config --grids".format(SCRIPT_DIR))
def test_query_machines(self):
run_cmd_no_fail("{}/query_config --machines".format(SCRIPT_DIR))
###############################################################################
class Z_FullSystemTest(TestCreateTestCommon):
###############################################################################
###########################################################################
def test_full_system(self):
###########################################################################
# Put this inside any test that's slow
if (FAST_ONLY):
self.skipTest("Skipping slow test")
self._create_test(["--walltime=0:15:00", "cime_developer"], test_id=self._baseline_name)
run_cmd_assert_result(self, "%s/cs.status.%s" % (self._testroot, self._baseline_name),
from_dir=self._testroot)
# Ensure that we can get test times
test_statuses = glob.glob(os.path.join(self._testroot, "*%s" % self._baseline_name, "TestStatus"))
for test_status in test_statuses:
test_time = CIME.wait_for_tests.get_test_time(os.path.dirname(test_status))
self.assertIs(type(test_time), int, msg="get time did not return int for %s" % test_status)
self.assertTrue(test_time > 0, msg="test time was zero for %s" % test_status)
# Test that re-running works
tests = get_tests.get_test_suite("cime_developer", machine=self._machine, compiler=self._compiler)
for test in tests:
casedir = os.path.join(TEST_ROOT, "%s.%s" % (test, self._baseline_name))
# Subtle issue: The run phases of these tests will be in the PASS state until
# the submitted case.test script is run, which could take a while if the system is
# busy. This potentially leaves a window where the wait_for_tests command below will
# not wait for the re-submitted jobs to run because it sees the original PASS.
# The code below forces things back to PEND to avoid this race condition. Note
# that we must use the MEMLEAK phase, not the RUN phase, because RUN being in a non-PEND
# state is how system tests know they are being re-run and must reset certain
# case settings.
if self._hasbatch:
with TestStatus(test_dir=casedir) as ts:
ts.set_status(MEMLEAK_PHASE, TEST_PEND_STATUS)
run_cmd_assert_result(self, "./case.submit --skip-preview-namelist", from_dir=casedir)
self._wait_for_tests(self._baseline_name)
###############################################################################
class K_TestCimeCase(TestCreateTestCommon):
###############################################################################
###########################################################################
def test_cime_case(self):
###########################################################################
self._create_test(["--no-build", "TESTRUNPASS_P1.f19_g16_rx1.A"], test_id=self._baseline_name)
self.assertEqual(type(MACHINE.get_value("MAX_TASKS_PER_NODE")), int)
self.assertTrue(type(MACHINE.get_value("PROJECT_REQUIRED")) in [type(None) , bool])
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS_P1.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
with Case(casedir, read_only=False) as case:
build_complete = case.get_value("BUILD_COMPLETE")
self.assertFalse(build_complete,
msg="Build complete had wrong value '%s'" %
build_complete)
case.set_value("BUILD_COMPLETE", True)
build_complete = case.get_value("BUILD_COMPLETE")
self.assertTrue(build_complete,
msg="Build complete had wrong value '%s'" %
build_complete)
case.flush()
build_complete = run_cmd_no_fail("./xmlquery BUILD_COMPLETE --value",
from_dir=casedir)
self.assertEqual(build_complete, "TRUE",
msg="Build complete had wrong value '%s'" %
build_complete)
# Test some test properties
self.assertEqual(case.get_value("TESTCASE"), "TESTRUNPASS")
def _batch_test_fixture(self, testcase_name):
if not MACHINE.has_batch_system() or NO_BATCH:
self.skipTest("Skipping testing user prerequisites without batch systems")
testdir = os.path.join(TEST_ROOT, testcase_name)
if os.path.exists(testdir):
shutil.rmtree(testdir)
args = "--case {name} --script-root {testdir} --compset X --res f19_g16 --handle-preexisting-dirs=r --output-root {testdir}".format(name=testcase_name, testdir=testdir)
if CIME.utils.get_cime_default_driver() == 'nuopc':
args += " --run-unsupported"
run_cmd_assert_result(self, "{}/create_newcase {}".format(SCRIPT_DIR, args),
from_dir=SCRIPT_DIR)
run_cmd_assert_result(self, "./case.setup", from_dir=testdir)
return testdir
###########################################################################
def test_cime_case_prereq(self):
###########################################################################
testcase_name = 'prereq_test'
testdir = self._batch_test_fixture(testcase_name)
with Case(testdir, read_only=False) as case:
if case.get_value("depend_string") is None:
self.skipTest("Skipping prereq test, depend_string was not provided for this batch system")
job_name = "case.run"
prereq_name = 'prereq_test'
batch_commands = case.submit_jobs(prereq=prereq_name, job=job_name, skip_pnl=True, dry_run=True)
self.assertTrue(isinstance(batch_commands, collections.Sequence), "case.submit_jobs did not return a sequence for a dry run")
self.assertTrue(len(batch_commands) > 0, "case.submit_jobs did not return any job submission string")
# The first element in the internal sequence should just be the job name
# The second one (batch_cmd_index) should be the actual batch submission command
batch_cmd_index = 1
# The prerequisite should be applied to all jobs, though we're only expecting one
for batch_cmd in batch_commands:
self.assertTrue(isinstance(batch_cmd, collections.Sequence), "case.submit_jobs did not return a sequence of sequences")
self.assertTrue(len(batch_cmd) > batch_cmd_index, "case.submit_jobs returned internal sequences with length <= {}".format(batch_cmd_index))
self.assertTrue(isinstance(batch_cmd[1], six.string_types), "case.submit_jobs returned internal sequences without the batch command string as the second parameter: {}".format(batch_cmd[1]))
batch_cmd_args = batch_cmd[1]
jobid_ident = "jobid"
dep_str_fmt = case.get_env('batch').get_value('depend_string', subgroup=None)
self.assertTrue(jobid_ident in dep_str_fmt, "dependency string doesn't include the jobid identifier {}".format(jobid_ident))
dep_str = dep_str_fmt[:dep_str_fmt.index(jobid_ident)]
prereq_substr = None
while dep_str in batch_cmd_args:
dep_id_pos = batch_cmd_args.find(dep_str) + len(dep_str)
batch_cmd_args = batch_cmd_args[dep_id_pos:]
prereq_substr = batch_cmd_args[:len(prereq_name)]
if prereq_substr == prereq_name:
break
self.assertTrue(prereq_name in prereq_substr, "Dependencies added, but not the user specified one")
###########################################################################
def test_cime_case_allow_failed_prereq(self):
###########################################################################
testcase_name = 'allow_failed_prereq_test'
testdir = self._batch_test_fixture(testcase_name)
with Case(testdir, read_only=False) as case:
depend_allow = case.get_value("depend_allow_string")
if depend_allow is None:
self.skipTest("Skipping allow_failed_prereq test, depend_allow_string was not provided for this batch system")
job_name = "case.run"
prereq_name = "prereq_allow_fail_test"
depend_allow = depend_allow.replace("jobid", prereq_name)
batch_commands = case.submit_jobs(prereq=prereq_name, allow_fail=True, job=job_name, skip_pnl=True, dry_run=True)
self.assertTrue(isinstance(batch_commands, collections.Sequence), "case.submit_jobs did not return a sequence for a dry run")
num_submissions = 1
if case.get_value("DOUT_S"):
num_submissions = 2
self.assertTrue(len(batch_commands) == num_submissions, "case.submit_jobs did not return any job submission strings")
self.assertTrue(depend_allow in batch_commands[0][1])
###########################################################################
def test_cime_case_resubmit_immediate(self):
###########################################################################
testcase_name = 'resubmit_immediate_test'
testdir = self._batch_test_fixture(testcase_name)
with Case(testdir, read_only=False) as case:
depend_string = case.get_value("depend_string")
if depend_string is None:
self.skipTest("Skipping resubmit_immediate test, depend_string was not provided for this batch system")
depend_string = re.sub('jobid.*$','',depend_string)
job_name = "case.run"
num_submissions = 6
case.set_value("RESUBMIT", num_submissions - 1)
batch_commands = case.submit_jobs(job=job_name, skip_pnl=True, dry_run=True, resubmit_immediate=True)
self.assertTrue(isinstance(batch_commands, collections.Sequence), "case.submit_jobs did not return a sequence for a dry run")
if case.get_value("DOUT_S"):
num_submissions = 12
self.assertTrue(len(batch_commands) == num_submissions, "case.submit_jobs did not return {} submitted jobs".format(num_submissions))
for i, cmd in enumerate(batch_commands):
if i > 0:
self.assertTrue(depend_string in cmd[1])
###########################################################################
def test_cime_case_st_archive_resubmit(self):
###########################################################################
testcase_name = "st_archive_resubmit_test"
testdir = self._batch_test_fixture(testcase_name)
with Case(testdir, read_only=False) as case:
case.case_setup(clean=False, test_mode=False, reset=True)
orig_resubmit = 2
case.set_value("RESUBMIT", orig_resubmit)
case.case_st_archive(resubmit=False)
new_resubmit = case.get_value("RESUBMIT")
self.assertTrue(orig_resubmit == new_resubmit, "st_archive resubmitted when told not to")
case.case_st_archive(resubmit=True)
new_resubmit = case.get_value("RESUBMIT")
self.assertTrue((orig_resubmit - 1) == new_resubmit, "st_archive did not resubmit when told to")
###########################################################################
def test_cime_case_build_threaded_1(self):
###########################################################################
self._create_test(["--no-build", "TESTRUNPASS_P1x1.f19_g16_rx1.A"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS_P1x1.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
with Case(casedir, read_only=False) as case:
build_threaded = case.get_value("SMP_PRESENT")
self.assertFalse(build_threaded)
build_threaded = case.get_build_threaded()
self.assertFalse(build_threaded)
case.set_value("FORCE_BUILD_SMP", True)
build_threaded = case.get_build_threaded()
self.assertTrue(build_threaded)
###########################################################################
def test_cime_case_build_threaded_2(self):
###########################################################################
self._create_test(["--no-build", "TESTRUNPASS_P1x2.f19_g16_rx1.A"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS_P1x2.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
with Case(casedir, read_only=False) as case:
build_threaded = case.get_value("SMP_PRESENT")
self.assertTrue(build_threaded)
build_threaded = case.get_build_threaded()
self.assertTrue(build_threaded)
###########################################################################
def test_cime_case_mpi_serial(self):
###########################################################################
self._create_test(["--no-build", "TESTRUNPASS_Mmpi-serial_P10.f19_g16_rx1.A"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS_Mmpi-serial_P10.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
with Case(casedir, read_only=True) as case:
# Serial cases should not be using pnetcdf
self.assertEqual(case.get_value("CPL_PIO_TYPENAME"), "netcdf")
# Serial cases should be using 1 task
self.assertEqual(case.get_value("TOTALPES"), 1)
self.assertEqual(case.get_value("NTASKS_CPL"), 1)
###########################################################################
def test_cime_case_force_pecount(self):
###########################################################################
self._create_test(["--no-build", "--force-procs=16", "--force-threads=8", "TESTRUNPASS.f19_g16_rx1.A"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS_P16x8.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
with Case(casedir, read_only=True) as case:
self.assertEqual(case.get_value("NTASKS_CPL"), 16)
self.assertEqual(case.get_value("NTHRDS_CPL"), 8)
###########################################################################
def test_cime_case_xmlchange_append(self):
###########################################################################
self._create_test(["--no-build", "TESTRUNPASS_P1x1.f19_g16_rx1.A"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS_P1x1.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
run_cmd_assert_result(self, "./xmlchange --id PIO_CONFIG_OPTS --val='-opt1'", from_dir=casedir)
result = run_cmd_assert_result(self, "./xmlquery --value PIO_CONFIG_OPTS", from_dir=casedir)
self.assertEqual(result, "-opt1")
run_cmd_assert_result(self, "./xmlchange --id PIO_CONFIG_OPTS --val='-opt2' --append", from_dir=casedir)
result = run_cmd_assert_result(self, "./xmlquery --value PIO_CONFIG_OPTS", from_dir=casedir)
self.assertEqual(result, "-opt1 -opt2")
###########################################################################
def test_cime_case_test_walltime_mgmt_1(self):
###########################################################################
if CIME.utils.get_model() != "e3sm":
self.skipTest("Skipping walltime test. Depends on E3SM batch settings")
test_name = "ERS.f19_g16_rx1.A"
machine, compiler = "blues", "gnu"
self._create_test(["--no-setup", "--machine={}".format(machine), test_name], test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=machine, compiler=compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
result = run_cmd_assert_result(self, "./xmlquery JOB_WALLCLOCK_TIME --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "0:10:00")
result = run_cmd_assert_result(self, "./xmlquery JOB_QUEUE --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "batch")
###########################################################################
def test_cime_case_test_walltime_mgmt_2(self):
###########################################################################
if CIME.utils.get_model() != "e3sm":
self.skipTest("Skipping walltime test. Depends on E3SM batch settings")
test_name = "ERS_P64.f19_g16_rx1.A"
machine, compiler = "blues", "gnu"
self._create_test(["--no-setup", "--machine={}".format(machine), test_name], test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=machine, compiler=compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
result = run_cmd_assert_result(self, "./xmlquery JOB_WALLCLOCK_TIME --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "03:00:00")
result = run_cmd_assert_result(self, "./xmlquery JOB_QUEUE --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "batch")
###########################################################################
def test_cime_case_test_walltime_mgmt_3(self):
###########################################################################
if CIME.utils.get_model() != "e3sm":
self.skipTest("Skipping walltime test. Depends on E3SM batch settings")
test_name = "ERS_P64.f19_g16_rx1.A"
machine, compiler = "blues", "gnu"
self._create_test(["--no-setup", "--machine={}".format(machine), "--walltime=0:10:00", test_name], test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=machine, compiler=compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
result = run_cmd_assert_result(self, "./xmlquery JOB_WALLCLOCK_TIME --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "0:10:00")
result = run_cmd_assert_result(self, "./xmlquery JOB_QUEUE --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "batch") # Not smart enough to select faster queue
###########################################################################
def test_cime_case_test_walltime_mgmt_4(self):
###########################################################################
if CIME.utils.get_model() != "e3sm":
self.skipTest("Skipping walltime test. Depends on E3SM batch settings")
test_name = "ERS_P1.f19_g16_rx1.A"
machine, compiler = "blues", "gnu"
self._create_test(["--no-setup", "--machine={}".format(machine), "--walltime=2:00:00", test_name], test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=machine, compiler=compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
result = run_cmd_assert_result(self, "./xmlquery JOB_WALLCLOCK_TIME --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "2:00:00")
result = run_cmd_assert_result(self, "./xmlquery JOB_QUEUE --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "batch")
###########################################################################
def test_cime_case_test_walltime_mgmt_5(self):
###########################################################################
if CIME.utils.get_model() != "e3sm":
self.skipTest("Skipping walltime test. Depends on E3SM batch settings")
test_name = "ERS_P1.f19_g16_rx1.A"
machine, compiler = "blues", "gnu"
self._create_test(["--no-setup", "--machine={}".format(machine), test_name], test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=machine, compiler=compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
run_cmd_assert_result(self, "./xmlchange JOB_QUEUE=slartibartfast --subgroup=case.test", from_dir=casedir, expected_stat=1)
run_cmd_assert_result(self, "./xmlchange JOB_QUEUE=slartibartfast --force --subgroup=case.test", from_dir=casedir)
result = run_cmd_assert_result(self, "./xmlquery JOB_WALLCLOCK_TIME --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "03:00:00")
result = run_cmd_assert_result(self, "./xmlquery JOB_QUEUE --subgroup=case.test --value", from_dir=casedir)
self.assertEqual(result, "slartibartfast")
###########################################################################
def test_cime_case_test_walltime_mgmt_6(self):
###########################################################################
if not self._hasbatch:
self.skipTest("Skipping walltime test. Depends on batch system")
test_name = "ERS_P1.f19_g16_rx1.A"
self._create_test(["--no-build", test_name], test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
run_cmd_assert_result(self, "./xmlchange JOB_WALLCLOCK_TIME=421:32:11 --subgroup=case.test", from_dir=casedir)
run_cmd_assert_result(self, "./case.setup --reset", from_dir=casedir)
result = run_cmd_assert_result(self, "./xmlquery JOB_WALLCLOCK_TIME --subgroup=case.test --value", from_dir=casedir)
with Case(casedir) as case:
walltime_format = case.get_value("walltime_format", subgroup=None)
if walltime_format is not None and walltime_format.count(":") == 1:
self.assertEqual(result, "421:32")
else:
self.assertEqual(result, "421:32:11")
###########################################################################
def test_cime_case_test_walltime_mgmt_7(self):
###########################################################################
if not self._hasbatch:
self.skipTest("Skipping walltime test. Depends on batch system")
test_name = "ERS_P1.f19_g16_rx1.A"
self._create_test(["--no-build", "--walltime=01:00:00", test_name], test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
run_cmd_assert_result(self, "./xmlchange JOB_WALLCLOCK_TIME=421:32:11 --subgroup=case.test", from_dir=casedir)
run_cmd_assert_result(self, "./case.setup --reset", from_dir=casedir)
result = run_cmd_assert_result(self, "./xmlquery JOB_WALLCLOCK_TIME --subgroup=case.test --value", from_dir=casedir)
with Case(casedir) as case:
walltime_format = case.get_value("walltime_format", subgroup=None)
if walltime_format is not None and walltime_format.count(":") == 1:
self.assertEqual(result, "421:32")
else:
self.assertEqual(result, "421:32:11")
###########################################################################
def test_cime_case_test_custom_project(self):
###########################################################################
test_name = "ERS_P1.f19_g16_rx1.A"
machine, compiler = "melvin", "gnu" # have to use a machine both models know and one that doesn't put PROJECT in any key paths
self._create_test(["--no-setup", "--machine={}".format(machine), "--compiler={}".format(compiler), "--project=testproj", test_name],
test_id=self._baseline_name,
env_changes="unset CIME_GLOBAL_WALLTIME &&")
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name(test_name, machine=machine, compiler=compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
result = run_cmd_assert_result(self, "./xmlquery --value PROJECT --subgroup=case.test", from_dir=casedir)
self.assertEqual(result, "testproj")
###########################################################################
def test_create_test_longname(self):
###########################################################################
self._create_test(["SMS.f19_g16.2000_SATM_XLND_SICE_SOCN_XROF_XGLC_SWAV", "--no-build"])
###########################################################################
def test_env_loading(self):
###########################################################################
if self._machine != "melvin":
self.skipTest("Skipping env load test - Only works on melvin")
self._create_test(["--no-build", "TESTRUNPASS.f19_g16_rx1.A"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
with Case(casedir, read_only=True) as case:
env_mach = case.get_env("mach_specific")
orig_env = dict(os.environ)
env_mach.load_env(case)
module_env = dict(os.environ)
os.environ.clear()
os.environ.update(orig_env)
env_mach.load_env(case, force_method="generic")
generic_env = dict(os.environ)
os.environ.clear()
os.environ.update(orig_env)
problems = ""
for mkey, mval in module_env.items():
if mkey not in generic_env:
if not mkey.startswith("PS") and mkey != "OLDPWD":
problems += "Generic missing key: {}\n".format(mkey)
elif mval != generic_env[mkey] and mkey not in ["_", "SHLVL", "PWD"] and not mkey.endswith("()"):
problems += "Value mismatch for key {}: {} != {}\n".format(mkey, repr(mval), repr(generic_env[mkey]))
for gkey in generic_env.keys():
if gkey not in module_env:
problems += "Modules missing key: {}\n".format(gkey)
self.assertEqual(problems, "", msg=problems)
###########################################################################
def test_case_submit_interface(self):
###########################################################################
try:
import imp
except ImportError:
print("imp not found, skipping case.submit interface test")
return
sys.path.append(TOOLS_DIR)
case_submit_path = os.path.join(TOOLS_DIR, "case.submit")
submit_interface = imp.load_source("case_submit_interface", case_submit_path)
sys.argv = ["case.submit", "--batch-args", "'random_arguments_here.%j'",
"--mail-type", "fail", "--mail-user", "'random_arguments_here.%j'"]
submit_interface._main_func(None, True)
###########################################################################
def test_xml_caching(self):
###########################################################################
self._create_test(["--no-build", "TESTRUNPASS.f19_g16_rx1.A"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"%s.%s" % (CIME.utils.get_full_test_name("TESTRUNPASS.f19_g16_rx1.A", machine=self._machine, compiler=self._compiler), self._baseline_name))
self.assertTrue(os.path.isdir(casedir), msg="Missing casedir '%s'" % casedir)
active = os.path.join(casedir, "env_run.xml")
backup = os.path.join(casedir, "env_run.xml.bak")
safe_copy(active, backup)
with Case(casedir, read_only=False) as case:
env_run = EnvRun(casedir, read_only=True)
self.assertEqual(case.get_value("RUN_TYPE"), "startup")
case.set_value("RUN_TYPE", "branch")
self.assertEqual(case.get_value("RUN_TYPE"), "branch")
self.assertEqual(env_run.get_value("RUN_TYPE"), "branch")
with Case(casedir) as case:
self.assertEqual(case.get_value("RUN_TYPE"), "branch")
time.sleep(0.2)
safe_copy(backup, active)
with Case(casedir, read_only=False) as case:
self.assertEqual(case.get_value("RUN_TYPE"), "startup")
case.set_value("RUN_TYPE", "branch")
with Case(casedir, read_only=False) as case:
self.assertEqual(case.get_value("RUN_TYPE"), "branch")
time.sleep(0.2)
safe_copy(backup, active)
case.read_xml() # Manual re-sync
self.assertEqual(case.get_value("RUN_TYPE"), "startup")
case.set_value("RUN_TYPE", "branch")
self.assertEqual(case.get_value("RUN_TYPE"), "branch")
with Case(casedir) as case:
self.assertEqual(case.get_value("RUN_TYPE"), "branch")
time.sleep(0.2)
safe_copy(backup, active)
env_run = EnvRun(casedir, read_only=True)
self.assertEqual(env_run.get_value("RUN_TYPE"), "startup")
with Case(casedir, read_only=False) as case:
self.assertEqual(case.get_value("RUN_TYPE"), "startup")
case.set_value("RUN_TYPE", "branch")
# behind the back detection
with self.assertRaises(CIMEError):
with Case(casedir, read_only=False) as case:
time.sleep(0.2)
safe_copy(backup, active)
with Case(casedir, read_only=False) as case:
case.set_value("RUN_TYPE", "branch")
with self.assertRaises(CIMEError):
with Case(casedir) as case:
time.sleep(0.2)
safe_copy(backup, active)
###########################################################################
def test_configure(self):
###########################################################################
self._create_test(["SMS.f09_g16.X", "--no-build"], test_id=self._baseline_name)
casedir = os.path.join(self._testroot,
"{}.{}".format(CIME.utils.get_full_test_name("SMS.f09_g16.X", machine=self._machine, compiler=self._compiler), self._baseline_name))
manual_config_dir = os.path.join(casedir, "manual_config")
os.mkdir(manual_config_dir)
run_cmd_no_fail("{} --machine={} --compiler={}".format(os.path.join(get_cime_root(), "tools", "configure"), self._machine, self._compiler), from_dir=manual_config_dir)
with open(os.path.join(casedir, "env_mach_specific.xml"), "r") as fd:
case_env_contents = fd.read()
with open(os.path.join(manual_config_dir, "env_mach_specific.xml"), "r") as fd:
man_env_contents = fd.read()
self.assertEqual(case_env_contents, man_env_contents)
###############################################################################
class X_TestSingleSubmit(TestCreateTestCommon):
###############################################################################
###########################################################################
def test_single_submit(self):
###########################################################################
# Skip unless on a batch system and users did not select no-batch
if (not self._hasbatch):
self.skipTest("Skipping single submit. Not valid without batch")
if CIME.utils.get_model() != "e3sm":
self.skipTest("Skipping single submit. E3SM experimental feature")
if self._machine not in ["sandiatoss3"]:
self.skipTest("Skipping single submit. Only works on sandiatoss3")
# Keep small enough for now that we don't have to worry about load balancing
self._create_test(["--single-submit", "SMS_Ln9_P8.f45_g37_rx1.A", "SMS_Ln9_P8.f19_g16_rx1.A"],
env_changes="unset CIME_GLOBAL_WALLTIME &&")
###############################################################################
class L_TestSaveTimings(TestCreateTestCommon):
###############################################################################
###########################################################################
def simple_test(self, manual_timing=False):
###########################################################################
timing_flag = "" if manual_timing else "--save-timing"
driver = CIME.utils.get_cime_default_driver()
if driver == "mct":
walltime="00:15:00"
else:
walltime="00:30:00"
self._create_test(["SMS_Ln9_P1.f19_g16_rx1.A", timing_flag, "--walltime="+walltime], test_id=self._baseline_name)
statuses = glob.glob("%s/*%s/TestStatus" % (self._testroot, self._baseline_name))
self.assertEqual(len(statuses), 1, msg="Should have had exactly one match, found %s" % statuses)
casedir = os.path.dirname(statuses[0])
with Case(casedir, read_only=True) as case:
lids = get_lids(case)
timing_dir = case.get_value("SAVE_TIMING_DIR")
casename = case.get_value("CASE")
self.assertEqual(len(lids), 1, msg="Expected one LID, found %s" % lids)
if manual_timing:
run_cmd_assert_result(self, "cd %s && %s/save_provenance postrun" % (casedir, TOOLS_DIR))
if CIME.utils.get_model() == "e3sm":
provenance_dirs = glob.glob(os.path.join(timing_dir, "performance_archive", getpass.getuser(), casename, lids[0] + "*"))
self.assertEqual(len(provenance_dirs), 1, msg="provenance dirs were missing")
verify_perms(self, timing_dir)
###########################################################################
def test_save_timings(self):
###########################################################################
self.simple_test()
###########################################################################
def test_save_timings_manual(self):
###########################################################################
self.simple_test(manual_timing=True)
# Machinery for Macros generation tests.
class MockMachines(object):
"""A mock version of the Machines object to simplify testing."""
def __init__(self, name, os_):
"""Store the name."""
self.name = name
self.os = os_
def get_machine_name(self):
"""Return the name we were given."""
return self.name
def get_value(self, var_name):
"""Allow the operating system to be queried."""
assert var_name == "OS", "Build asked for a value not " \
"implemented in the testing infrastructure."
return self.os
def is_valid_compiler(self, _): # pylint:disable=no-self-use
"""Assume all compilers are valid."""
return True
def is_valid_MPIlib(self, _):
"""Assume all MPILIB settings are valid."""
return True
# pragma pylint: disable=unused-argument
def get_default_MPIlib(self, attributes=None):
return "mpich2"
def get_default_compiler(self):
return "intel"
def get_macros(macro_maker, build_xml, build_system):
"""Generate build system ("Macros" file) output from config_compilers XML.
Arguments:
macro_maker - The underlying Build object.
build_xml - A string containing the XML to operate on.
build_system - Either "Makefile" or "CMake", depending on desired output.
The return value is a string containing the build system output.
"""
# Build.write_macros expects file-like objects as input, so
# we need to wrap the strings in StringIO objects.
xml = six.StringIO(str(build_xml))
output = six.StringIO()
output_format = None
if build_system == "Makefile":
output_format = "make"
elif build_system == "CMake":
output_format = "cmake"
else:
output_format = build_system
macro_maker.write_macros_file(macros_file=output,
output_format=output_format, xml=xml)
return str(output.getvalue())
def _wrap_config_compilers_xml(inner_string):
"""Utility function to create a config_compilers XML string.
Pass this function a string containing <compiler> elements, and it will add
the necessary header/footer to the file.
"""
_xml_template = """<?xml version="1.0" encoding="UTF-8"?>
<config_compilers>
{}
</config_compilers>
"""
return _xml_template.format(inner_string)
class MakefileTester(object):
"""Helper class for checking Makefile output.
Public methods:
__init__
query_var
assert_variable_equals
assert_variable_matches
"""
# Note that the following is a Makefile and the echo line must begin with a tab
_makefile_template = """
include Macros
query:
\techo '$({})' > query.out
"""
def __init__(self, parent, make_string):
"""Constructor for Makefile test helper class.
Arguments:
parent - The TestCase object that is using this item.
make_string - Makefile contents to test.
"""
self.parent = parent
self.make_string = make_string
def query_var(self, var_name, env, var):
"""Request the value of a variable in the Makefile, as a string.
Arguments:
var_name - Name of the variable to query.
env - A dict containing extra environment variables to set when calling
make.
var - A dict containing extra make variables to set when calling make.
(The distinction between env and var actually matters only for
CMake, though.)
"""
if env is None:
env = dict()
if var is None:
var = dict()
# Write the Makefile strings to temporary files.
temp_dir = tempfile.mkdtemp()
macros_file_name = os.path.join(temp_dir, "Macros")
makefile_name = os.path.join(temp_dir, "Makefile")
output_name = os.path.join(temp_dir, "query.out")
with open(macros_file_name, "w") as macros_file:
macros_file.write(self.make_string)
with open(makefile_name, "w") as makefile:
makefile.write(self._makefile_template.format(var_name))
environment = os.environ.copy()
environment.update(env)
environment.update(var)
gmake_exe = MACHINE.get_value("GMAKE")
if gmake_exe is None:
gmake_exe = "gmake"
run_cmd_assert_result(self.parent, "%s query --directory=%s 2>&1" % (gmake_exe, temp_dir), env=environment)
with open(output_name, "r") as output:
query_result = output.read().strip()
# Clean up the Makefiles.
shutil.rmtree(temp_dir)
return query_result
def assert_variable_equals(self, var_name, value, env=None, var=None):
"""Assert that a variable in the Makefile has a given value.
Arguments:
var_name - Name of variable to check.
value - The string that the variable value should be equal to.
env - Optional. Dict of environment variables to set when calling make.
var - Optional. Dict of make variables to set when calling make.
"""
self.parent.assertEqual(self.query_var(var_name, env, var), value)
def assert_variable_matches(self, var_name, regex, env=None, var=None):
"""Assert that a variable in the Makefile matches a regex.
Arguments:
var_name - Name of variable to check.
regex - The regex to match.
env - Optional. Dict of environment variables to set when calling make.
var - Optional. Dict of make variables to set when calling make.
"""
self.parent.assertRegexpMatches(self.query_var(var_name, env, var), regex)
class CMakeTester(object):
"""Helper class for checking CMake output.
Public methods:
__init__
query_var
assert_variable_equals
assert_variable_matches
"""
_cmakelists_template = """
include(./Macros.cmake)
file(WRITE query.out "${{{}}}")
"""
def __init__(self, parent, cmake_string):
"""Constructor for CMake test helper class.
Arguments:
parent - The TestCase object that is using this item.
cmake_string - CMake contents to test.
"""
self.parent = parent
self.cmake_string = cmake_string
def query_var(self, var_name, env, var):
"""Request the value of a variable in Macros.cmake, as a string.
Arguments:
var_name - Name of the variable to query.
env - A dict containing extra environment variables to set when calling
cmake.
var - A dict containing extra CMake variables to set when calling cmake.
"""
if env is None:
env = dict()
if var is None:
var = dict()
# Write the CMake strings to temporary files.
temp_dir = tempfile.mkdtemp()
macros_file_name = os.path.join(temp_dir, "Macros.cmake")
cmakelists_name = os.path.join(temp_dir, "CMakeLists.txt")
output_name = os.path.join(temp_dir, "query.out")
with open(macros_file_name, "w") as macros_file:
for key in var:
macros_file.write("set({} {})\n".format(key, var[key]))
macros_file.write(self.cmake_string)
with open(cmakelists_name, "w") as cmakelists:
cmakelists.write(self._cmakelists_template.format(var_name))
environment = os.environ.copy()
environment.update(env)
os_ = MACHINE.get_value("OS")
# cmake will not work on cray systems without this flag
if os_ == "CNL":
cmake_args = "-DCMAKE_SYSTEM_NAME=Catamount"
else:
cmake_args = ""
run_cmd_assert_result(self.parent, "cmake %s . 2>&1" % cmake_args, from_dir=temp_dir, env=environment)
with open(output_name, "r") as output:
query_result = output.read().strip()
# Clean up the CMake files.
shutil.rmtree(temp_dir)
return query_result
def assert_variable_equals(self, var_name, value, env=None, var=None):
"""Assert that a variable in the CMakeLists has a given value.
Arguments:
var_name - Name of variable to check.
value - The string that the variable value should be equal to.
env - Optional. Dict of environment variables to set when calling cmake.
var - Optional. Dict of CMake variables to set when calling cmake.
"""
self.parent.assertEqual(self.query_var(var_name, env, var), value)
def assert_variable_matches(self, var_name, regex, env=None, var=None):
"""Assert that a variable in the CMkeLists matches a regex.
Arguments:
var_name - Name of variable to check.
regex - The regex to match.
env - Optional. Dict of environment variables to set when calling cmake.
var - Optional. Dict of CMake variables to set when calling cmake.
"""
self.parent.assertRegexpMatches(self.query_var(var_name, env, var), regex)
###############################################################################
class G_TestMacrosBasic(unittest.TestCase):
###############################################################################
"""Basic infrastructure tests.
This class contains tests that do not actually depend on the output of the
macro file conversion. This includes basic smoke testing and tests of
error-handling in the routine.
"""
def test_script_is_callable(self):
"""The test script can be called on valid output without dying."""
# This is really more a smoke test of this script than anything else.
maker = Compilers(MockMachines("mymachine", "SomeOS"), version=2.0)
test_xml = _wrap_config_compilers_xml("<compiler><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>")
get_macros(maker, test_xml, "Makefile")
def test_script_rejects_bad_xml(self):
"""The macro writer rejects input that's not valid XML."""
maker = Compilers(MockMachines("mymachine", "SomeOS"), version=2.0)
with self.assertRaises(ParseError):
get_macros(maker, "This is not valid XML.", "Makefile")
def test_script_rejects_bad_build_system(self):
"""The macro writer rejects a bad build system string."""
maker = Compilers(MockMachines("mymachine", "SomeOS"), version=2.0)
bad_string = "argle-bargle."
with assertRaisesRegex(self,
CIMEError,
"Unrecognized build system provided to write_macros: " + bad_string):
get_macros(maker, "This string is irrelevant.", bad_string)
###############################################################################
class H_TestMakeMacros(unittest.TestCase):
###############################################################################
"""Makefile macros tests.
This class contains tests of the Makefile output of Build.
Aside from the usual setUp and test methods, this class has a utility method
(xml_to_tester) that converts XML input directly to a MakefileTester object.
"""
def setUp(self):
self.test_os = "SomeOS"
self.test_machine = "mymachine"
self.test_compiler = MACHINE.get_default_compiler() if TEST_COMPILER is None else TEST_COMPILER
self.test_mpilib = MACHINE.get_default_MPIlib(attributes={"compiler":self.test_compiler}) if TEST_MPILIB is None else TEST_MPILIB
self._maker = Compilers(MockMachines(self.test_machine, self.test_os), version=2.0)
def xml_to_tester(self, xml_string):
"""Helper that directly converts an XML string to a MakefileTester."""
test_xml = _wrap_config_compilers_xml(xml_string)
return MakefileTester(self, get_macros(self._maker, test_xml, "Makefile"))
def test_generic_item(self):
"""The macro writer can write out a single generic item."""
xml_string = "<compiler><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>"
tester = self.xml_to_tester(xml_string)
tester.assert_variable_equals("SUPPORTS_CXX", "FALSE")
def test_machine_specific_item(self):
"""The macro writer can pick out a machine-specific item."""
xml1 = """<compiler MACH="{}"><SUPPORTS_CXX>TRUE</SUPPORTS_CXX></compiler>""".format(self.test_machine)
xml2 = """<compiler><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
# Do this a second time, but with elements in the reverse order, to
# ensure that the code is not "cheating" by taking the first match.
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
def test_ignore_non_match(self):
"""The macro writer ignores an entry with the wrong machine name."""
xml1 = """<compiler MACH="bad"><SUPPORTS_CXX>TRUE</SUPPORTS_CXX></compiler>"""
xml2 = """<compiler><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SUPPORTS_CXX", "FALSE")
# Again, double-check that we don't just get lucky with the order.
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("SUPPORTS_CXX", "FALSE")
def test_os_specific_item(self):
"""The macro writer can pick out an OS-specific item."""
xml1 = """<compiler OS="{}"><SUPPORTS_CXX>TRUE</SUPPORTS_CXX></compiler>""".format(self.test_os)
xml2 = """<compiler><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
def test_mach_other_compiler(self):
"""The macro writer compiler-specific logic works as expected."""
xml1 = """<compiler COMPILER="{}"><CFLAGS><base>a b c</base></CFLAGS></compiler>""".format(self.test_compiler)
xml2 = """<compiler MACH="{}" COMPILER="other"><CFLAGS><base>x y z</base></CFLAGS></compiler>""".format(self.test_machine)
xml3 = """<compiler MACH="{}" COMPILER="{}"><CFLAGS><append>x y z</append></CFLAGS></compiler>""".format(self.test_machine,self.test_compiler)
xml4 = """<compiler MACH="{}" COMPILER="{}"><CFLAGS><base>x y z</base></CFLAGS></compiler>""".format(self.test_machine,self.test_compiler)
tester = self.xml_to_tester(xml1)
tester.assert_variable_equals("CFLAGS", "a b c",var={"COMPILER":self.test_compiler})
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("CFLAGS", "a b c",var={"COMPILER":self.test_compiler})
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("CFLAGS", "a b c",var={"COMPILER":self.test_compiler})
tester = self.xml_to_tester(xml1+xml3)
tester.assert_variable_equals("CFLAGS", "a b c x y z",var={"COMPILER":self.test_compiler})
tester = self.xml_to_tester(xml1+xml4)
tester.assert_variable_equals("CFLAGS", "x y z",var={"COMPILER":self.test_compiler})
tester = self.xml_to_tester(xml4+xml1)
tester.assert_variable_equals("CFLAGS", "x y z",var={"COMPILER":self.test_compiler})
def test_mach_beats_os(self):
"""The macro writer chooses machine-specific over os-specific matches."""
xml1 = """<compiler OS="{}"><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>""".format(self.test_os)
xml2 = """<compiler MACH="{}"><SUPPORTS_CXX>TRUE</SUPPORTS_CXX></compiler>""".format(self.test_machine)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
def test_mach_and_os_beats_mach(self):
"""The macro writer chooses the most-specific match possible."""
xml1 = """<compiler MACH="{}"><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>""".format(self.test_machine)
xml2 = """<compiler MACH="{}" OS="{}"><SUPPORTS_CXX>TRUE</SUPPORTS_CXX></compiler>"""
xml2 = xml2.format(self.test_machine, self.test_os)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE")
def test_build_time_attribute(self):
"""The macro writer writes conditionals for build-time choices."""
xml1 = """<compiler><MPI_PATH MPILIB="mpich">/path/to/mpich</MPI_PATH></compiler>"""
xml2 = """<compiler><MPI_PATH MPILIB="openmpi">/path/to/openmpi</MPI_PATH></compiler>"""
xml3 = """<compiler><MPI_PATH>/path/to/default</MPI_PATH></compiler>"""
tester = self.xml_to_tester(xml1+xml2+xml3)
tester.assert_variable_equals("MPI_PATH", "/path/to/default")
tester.assert_variable_equals("MPI_PATH", "/path/to/mpich", var={"MPILIB": "mpich"})
tester.assert_variable_equals("MPI_PATH", "/path/to/openmpi", var={"MPILIB": "openmpi"})
tester = self.xml_to_tester(xml3+xml2+xml1)
tester.assert_variable_equals("MPI_PATH", "/path/to/default")
tester.assert_variable_equals("MPI_PATH", "/path/to/mpich", var={"MPILIB": "mpich"})
tester.assert_variable_equals("MPI_PATH", "/path/to/openmpi", var={"MPILIB": "openmpi"})
def test_reject_duplicate_defaults(self):
"""The macro writer dies if given many defaults."""
xml1 = """<compiler><MPI_PATH>/path/to/default</MPI_PATH></compiler>"""
xml2 = """<compiler><MPI_PATH>/path/to/other_default</MPI_PATH></compiler>"""
with assertRaisesRegex(self,
CIMEError,
"Variable MPI_PATH is set ambiguously in config_compilers.xml."):
self.xml_to_tester(xml1+xml2)
def test_reject_duplicates(self):
"""The macro writer dies if given many matches for a given configuration."""
xml1 = """<compiler><MPI_PATH MPILIB="mpich">/path/to/mpich</MPI_PATH></compiler>"""
xml2 = """<compiler><MPI_PATH MPILIB="mpich">/path/to/mpich2</MPI_PATH></compiler>"""
with assertRaisesRegex(self,
CIMEError,
"Variable MPI_PATH is set ambiguously in config_compilers.xml."):
self.xml_to_tester(xml1+xml2)
def test_reject_ambiguous(self):
"""The macro writer dies if given an ambiguous set of matches."""
xml1 = """<compiler><MPI_PATH MPILIB="mpich">/path/to/mpich</MPI_PATH></compiler>"""
xml2 = """<compiler><MPI_PATH DEBUG="FALSE">/path/to/mpi-debug</MPI_PATH></compiler>"""
with assertRaisesRegex(self,
CIMEError,
"Variable MPI_PATH is set ambiguously in config_compilers.xml."):
self.xml_to_tester(xml1+xml2)
def test_compiler_changeable_at_build_time(self):
"""The macro writer writes information for multiple compilers."""
xml1 = """<compiler><SUPPORTS_CXX>FALSE</SUPPORTS_CXX></compiler>"""
xml2 = """<compiler COMPILER="gnu"><SUPPORTS_CXX>TRUE</SUPPORTS_CXX></compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SUPPORTS_CXX", "TRUE", var={"COMPILER": "gnu"})
tester.assert_variable_equals("SUPPORTS_CXX", "FALSE")
def test_base_flags(self):
"""Test that we get "base" compiler flags."""
xml1 = """<compiler><FFLAGS><base>-O2</base></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1)
tester.assert_variable_equals("FFLAGS", "-O2")
def test_machine_specific_base_flags(self):
"""Test selection among base compiler flag sets based on machine."""
xml1 = """<compiler><FFLAGS><base>-O2</base></FFLAGS></compiler>"""
xml2 = """<compiler MACH="{}"><FFLAGS><base>-O3</base></FFLAGS></compiler>""".format(self.test_machine)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("FFLAGS", "-O3")
def test_build_time_base_flags(self):
"""Test selection of base flags based on build-time attributes."""
xml1 = """<compiler><FFLAGS><base>-O2</base></FFLAGS></compiler>"""
xml2 = """<compiler><FFLAGS><base DEBUG="TRUE">-O3</base></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("FFLAGS", "-O2")
tester.assert_variable_equals("FFLAGS", "-O3", var={"DEBUG": "TRUE"})
def test_build_time_base_flags_same_parent(self):
"""Test selection of base flags in the same parent element."""
xml1 = """<base>-O2</base>"""
xml2 = """<base DEBUG="TRUE">-O3</base>"""
tester = self.xml_to_tester("<compiler><FFLAGS>"+xml1+xml2+"</FFLAGS></compiler>")
tester.assert_variable_equals("FFLAGS", "-O2")
tester.assert_variable_equals("FFLAGS", "-O3", var={"DEBUG": "TRUE"})
# Check for order independence here, too.
tester = self.xml_to_tester("<compiler><FFLAGS>"+xml2+xml1+"</FFLAGS></compiler>")
tester.assert_variable_equals("FFLAGS", "-O2")
tester.assert_variable_equals("FFLAGS", "-O3", var={"DEBUG": "TRUE"})
def test_append_flags(self):
"""Test appending flags to a list."""
xml1 = """<compiler><FFLAGS><base>-delicious</base></FFLAGS></compiler>"""
xml2 = """<compiler><FFLAGS><append>-cake</append></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("FFLAGS", "-delicious -cake")
# Order independence, as usual.
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("FFLAGS", "-delicious -cake")
def test_machine_specific_append_flags(self):
"""Test appending flags that are either more or less machine-specific."""
xml1 = """<compiler><FFLAGS><append>-delicious</append></FFLAGS></compiler>"""
xml2 = """<compiler MACH="{}"><FFLAGS><append>-cake</append></FFLAGS></compiler>""".format(self.test_machine)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_matches("FFLAGS", "^(-delicious -cake|-cake -delicious)$")
def test_machine_specific_base_keeps_append_flags(self):
"""Test that machine-specific base flags don't override default append flags."""
xml1 = """<compiler><FFLAGS><append>-delicious</append></FFLAGS></compiler>"""
xml2 = """<compiler MACH="{}"><FFLAGS><base>-cake</base></FFLAGS></compiler>""".format(self.test_machine)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("FFLAGS", "-cake -delicious")
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("FFLAGS", "-cake -delicious")
def test_machine_specific_base_and_append_flags(self):
"""Test that machine-specific base flags coexist with machine-specific append flags."""
xml1 = """<compiler MACH="{}"><FFLAGS><append>-delicious</append></FFLAGS></compiler>""".format(self.test_machine)
xml2 = """<compiler MACH="{}"><FFLAGS><base>-cake</base></FFLAGS></compiler>""".format(self.test_machine)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("FFLAGS", "-cake -delicious")
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("FFLAGS", "-cake -delicious")
def test_append_flags_without_base(self):
"""Test appending flags to a value set before Macros is included."""
xml1 = """<compiler><FFLAGS><append>-cake</append></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1)
tester.assert_variable_equals("FFLAGS", "-delicious -cake", var={"FFLAGS": "-delicious"})
def test_build_time_append_flags(self):
"""Test build_time selection of compiler flags."""
xml1 = """<compiler><FFLAGS><append>-cake</append></FFLAGS></compiler>"""
xml2 = """<compiler><FFLAGS><append DEBUG="TRUE">-and-pie</append></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("FFLAGS", "-cake")
tester.assert_variable_matches("FFLAGS", "^(-cake -and-pie|-and-pie -cake)$", var={"DEBUG": "TRUE"})
def test_environment_variable_insertion(self):
"""Test that ENV{..} inserts environment variables."""
# DO it again with $ENV{} style
xml1 = """<compiler><LDFLAGS><append>-L$ENV{NETCDF} -lnetcdf</append></LDFLAGS></compiler>"""
tester = self.xml_to_tester(xml1)
tester.assert_variable_equals("LDFLAGS", "-L/path/to/netcdf -lnetcdf",
env={"NETCDF": "/path/to/netcdf"})
def test_shell_command_insertion(self):
"""Test that $SHELL insert shell command output."""
xml1 = """<compiler><FFLAGS><base>-O$SHELL{echo 2} -fast</base></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1)
tester.assert_variable_equals("FFLAGS", "-O2 -fast")
def test_multiple_shell_commands(self):
"""Test that more than one $SHELL element can be used."""
xml1 = """<compiler><FFLAGS><base>-O$SHELL{echo 2} -$SHELL{echo fast}</base></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1)
tester.assert_variable_equals("FFLAGS", "-O2 -fast")
def test_env_and_shell_command(self):
"""Test that $ENV works inside $SHELL elements."""
xml1 = """<compiler><FFLAGS><base>-O$SHELL{echo $ENV{OPT_LEVEL}} -fast</base></FFLAGS></compiler>"""
tester = self.xml_to_tester(xml1)
tester.assert_variable_equals("FFLAGS", "-O2 -fast", env={"OPT_LEVEL": "2"})
def test_config_variable_insertion(self):
"""Test that $VAR insert variables from config_compilers."""
# Construct an absurd chain of references just to sure that we don't
# pass by accident, e.g. outputting things in the right order just due
# to good luck in a hash somewhere.
xml1 = """<MPI_LIB_NAME>stuff-${MPI_PATH}-stuff</MPI_LIB_NAME>"""
xml2 = """<MPI_PATH>${MPICC}</MPI_PATH>"""
xml3 = """<MPICC>${MPICXX}</MPICC>"""
xml4 = """<MPICXX>${MPIFC}</MPICXX>"""
xml5 = """<MPIFC>mpicc</MPIFC>"""
tester = self.xml_to_tester("<compiler>"+xml1+xml2+xml3+xml4+xml5+"</compiler>")
tester.assert_variable_equals("MPI_LIB_NAME", "stuff-mpicc-stuff")
def test_config_reject_self_references(self):
"""Test that $VAR self-references are rejected."""
# This is a special case of the next test, which also checks circular
# references.
xml1 = """<MPI_LIB_NAME>${MPI_LIB_NAME}</MPI_LIB_NAME>"""
err_msg = r".* has bad \$VAR references. Check for circular references or variables that are used in a \$VAR but not actually defined."
with assertRaisesRegex(self,CIMEError, err_msg):
self.xml_to_tester("<compiler>"+xml1+"</compiler>")
def test_config_reject_cyclical_references(self):
"""Test that cyclical $VAR references are rejected."""
xml1 = """<MPI_LIB_NAME>${MPI_PATH}</MPI_LIB_NAME>"""
xml2 = """<MPI_PATH>${MPI_LIB_NAME}</MPI_PATH>"""
err_msg = r".* has bad \$VAR references. Check for circular references or variables that are used in a \$VAR but not actually defined."
with assertRaisesRegex(self,CIMEError, err_msg):
self.xml_to_tester("<compiler>"+xml1+xml2+"</compiler>")
def test_variable_insertion_with_machine_specific_setting(self):
"""Test that machine-specific $VAR dependencies are correct."""
xml1 = """<compiler><MPI_LIB_NAME>something</MPI_LIB_NAME></compiler>"""
xml2 = """<compiler MACH="{}"><MPI_LIB_NAME>$MPI_PATH</MPI_LIB_NAME></compiler>""".format(self.test_machine)
xml3 = """<compiler><MPI_PATH>${MPI_LIB_NAME}</MPI_PATH></compiler>"""
err_msg = r".* has bad \$VAR references. Check for circular references or variables that are used in a \$VAR but not actually defined."
with assertRaisesRegex(self,CIMEError, err_msg):
self.xml_to_tester(xml1+xml2+xml3)
def test_override_with_machine_and_new_attributes(self):
"""Test that overrides with machine-specific settings with added attributes work correctly."""
xml1 = """
<compiler COMPILER="{}">
<SCC>icc</SCC>
<MPICXX>mpicxx</MPICXX>
<MPIFC>mpif90</MPIFC>
<MPICC>mpicc</MPICC>
</compiler>""".format(self.test_compiler)
xml2 = """
<compiler COMPILER="{}" MACH="{}">
<MPICXX>mpifoo</MPICXX>
<MPIFC MPILIB="{}">mpiffoo</MPIFC>
<MPICC MPILIB="NOT_MY_MPI">mpifouc</MPICC>
</compiler>
""".format(self.test_compiler, self.test_machine, self.test_mpilib)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SCC", "icc", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester.assert_variable_equals("MPICXX", "mpifoo", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester.assert_variable_equals("MPIFC", "mpiffoo", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester.assert_variable_equals("MPICC", "mpicc", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("SCC", "icc", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester.assert_variable_equals("MPICXX", "mpifoo", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester.assert_variable_equals("MPIFC", "mpiffoo", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester.assert_variable_equals("MPICC", "mpicc", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
def test_override_with_machine_and_same_attributes(self):
"""Test that machine-specific conditional overrides with the same attribute work correctly."""
xml1 = """
<compiler COMPILER="{}">
<MPIFC MPILIB="{}">mpifc</MPIFC>
</compiler>""".format(self.test_compiler, self.test_mpilib)
xml2 = """
<compiler MACH="{}" COMPILER="{}">
<MPIFC MPILIB="{}">mpif90</MPIFC>
</compiler>
""".format(self.test_machine, self.test_compiler, self.test_mpilib)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("MPIFC", "mpif90", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("MPIFC", "mpif90", var={"COMPILER":self.test_compiler, "MPILIB":self.test_mpilib})
def test_appends_not_overriden(self):
"""Test that machine-specific base value changes don't interfere with appends."""
xml1="""
<compiler COMPILER="{}">
<FFLAGS>
<base>-base1</base>
<append DEBUG="FALSE">-debug1</append>
</FFLAGS>
</compiler>""".format(self.test_compiler)
xml2="""
<compiler MACH="{}" COMPILER="{}">
<FFLAGS>
<base>-base2</base>
<append DEBUG="TRUE">-debug2</append>
</FFLAGS>
</compiler>""".format(self.test_machine, self.test_compiler)
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("FFLAGS", "-base2", var={"COMPILER": self.test_compiler})
tester.assert_variable_equals("FFLAGS", "-base2 -debug2", var={"COMPILER": self.test_compiler, "DEBUG": "TRUE"})
tester.assert_variable_equals("FFLAGS", "-base2 -debug1", var={"COMPILER": self.test_compiler, "DEBUG": "FALSE"})
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("FFLAGS", "-base2", var={"COMPILER": self.test_compiler})
tester.assert_variable_equals("FFLAGS", "-base2 -debug2", var={"COMPILER": self.test_compiler, "DEBUG": "TRUE"})
tester.assert_variable_equals("FFLAGS", "-base2 -debug1", var={"COMPILER": self.test_compiler, "DEBUG": "FALSE"})
def test_multilevel_specificity(self):
"""Check that settings with multiple levels of machine-specificity can be resolved."""
xml1="""
<compiler>
<MPIFC DEBUG="FALSE">mpifc</MPIFC>
</compiler>"""
xml2="""
<compiler OS="{}">
<MPIFC MPILIB="{}">mpif03</MPIFC>
</compiler>""".format(self.test_os, self.test_mpilib)
xml3="""
<compiler MACH="{}">
<MPIFC DEBUG="TRUE">mpif90</MPIFC>
</compiler>""".format(self.test_machine)
# To verify order-independence, test every possible ordering of blocks.
testers = []
testers.append(self.xml_to_tester(xml1+xml2+xml3))
testers.append(self.xml_to_tester(xml1+xml3+xml2))
testers.append(self.xml_to_tester(xml2+xml1+xml3))
testers.append(self.xml_to_tester(xml2+xml3+xml1))
testers.append(self.xml_to_tester(xml3+xml1+xml2))
testers.append(self.xml_to_tester(xml3+xml2+xml1))
for tester in testers:
tester.assert_variable_equals("MPIFC", "mpif90", var={"COMPILER": self.test_compiler, "MPILIB": self.test_mpilib, "DEBUG": "TRUE"})
tester.assert_variable_equals("MPIFC", "mpif03", var={"COMPILER": self.test_compiler, "MPILIB": self.test_mpilib, "DEBUG": "FALSE"})
tester.assert_variable_equals("MPIFC", "mpifc", var={"COMPILER": self.test_compiler, "MPILIB": "NON_MATCHING_MPI", "DEBUG": "FALSE"})
def test_remove_dependency_issues(self):
"""Check that overridden settings don't cause inter-variable dependencies."""
xml1="""
<compiler>
<MPIFC>${SFC}</MPIFC>
</compiler>"""
xml2="""
<compiler MACH="{}">""".format(self.test_machine) + """
<SFC>${MPIFC}</SFC>
<MPIFC>mpif90</MPIFC>
</compiler>"""
tester = self.xml_to_tester(xml1+xml2)
tester.assert_variable_equals("SFC", "mpif90")
tester.assert_variable_equals("MPIFC", "mpif90")
tester = self.xml_to_tester(xml2+xml1)
tester.assert_variable_equals("SFC", "mpif90")
tester.assert_variable_equals("MPIFC", "mpif90")
###############################################################################
class I_TestCMakeMacros(H_TestMakeMacros):
###############################################################################
"""CMake macros tests.
This class contains tests of the CMake output of Build.
This class simply inherits all of the methods of TestMakeOutput, but changes
the definition of xml_to_tester to create a CMakeTester instead.
"""
def xml_to_tester(self, xml_string):
"""Helper that directly converts an XML string to a MakefileTester."""
test_xml = _wrap_config_compilers_xml(xml_string)
if (NO_CMAKE):
self.skipTest("Skipping cmake test")
else:
return CMakeTester(self, get_macros(self._maker, test_xml, "CMake"))
###############################################################################
class S_TestManageAndQuery(unittest.TestCase):
"""Tests various scripts to manage and query xml files"""
def _run_and_assert_query_testlist(self, extra_args=""):
"""Ensure that query_testlist runs successfully with the given extra arguments"""
files = Files()
testlist_drv = files.get_value("TESTS_SPEC_FILE", {"component":"drv"})
run_cmd_assert_result(self, "{}/query_testlists --xml-testlist {} {}".format(
SCRIPT_DIR, testlist_drv, extra_args))
def test_query_testlists_runs(self):
"""Make sure that query_testlists runs successfully
This simply makes sure that query_testlists doesn't generate any errors
when it runs. This helps ensure that changes in other utilities don't
break query_testlists.
"""
self._run_and_assert_query_testlist(extra_args="--show-options")
def test_query_testlists_define_testtypes_runs(self):
"""Make sure that query_testlists runs successfully with the --define-testtypes argument"""
self._run_and_assert_query_testlist(extra_args="--define-testtypes")
def test_query_testlists_count_runs(self):
"""Make sure that query_testlists runs successfully with the --count argument"""
self._run_and_assert_query_testlist(extra_args="--count")
def test_query_testlists_list_runs(self):
"""Make sure that query_testlists runs successfully with the --list argument"""
self._run_and_assert_query_testlist(extra_args="--list categories")
###############################################################################
class B_CheckCode(unittest.TestCase):
###############################################################################
# Tests are generated in the main loop below
longMessage = True
all_results = None
def make_pylint_test(pyfile, all_files):
def test(self):
if B_CheckCode.all_results is None:
B_CheckCode.all_results = check_code(all_files)
#pylint: disable=unsubscriptable-object
result = B_CheckCode.all_results[pyfile]
self.assertTrue(result == "", msg=result)
return test
def check_for_pylint():
#pylint: disable=import-error
from distutils.spawn import find_executable
pylint = find_executable("pylint")
if pylint is not None:
output = run_cmd_no_fail("pylint --version")
pylintver = re.search(r"pylint\s+(\d+)[.](\d+)[.](\d+)", output)
major = int(pylintver.group(1))
minor = int(pylintver.group(2))
if pylint is None or major < 1 or (major == 1 and minor < 5):
print("pylint version 1.5 or newer not found, pylint tests skipped")
return False
return True
def write_provenance_info():
curr_commit = get_current_commit(repo=LIB_DIR)
logging.info("\nTesting commit %s" % curr_commit)
cime_model = CIME.utils.get_model()
logging.info("Using cime_model = %s" % cime_model)
logging.info("Testing machine = %s" % MACHINE.get_machine_name())
if TEST_COMPILER is not None:
logging.info("Testing compiler = %s"% TEST_COMPILER)
if TEST_MPILIB is not None:
logging.info("Testing mpilib = %s"% TEST_MPILIB)
logging.info("Test root: %s" % TEST_ROOT)
logging.info("Test driver: %s\n" % CIME.utils.get_cime_default_driver())
def _main_func(description):
global MACHINE
global NO_CMAKE
global FAST_ONLY
global NO_BATCH
global TEST_COMPILER
global TEST_MPILIB
global TEST_ROOT
global GLOBAL_TIMEOUT
global NO_TEARDOWN
config = CIME.utils.get_cime_config()
help_str = \
"""
{0} [TEST] [TEST]
OR
{0} --help
\033[1mEXAMPLES:\033[0m
\033[1;32m# Run the full suite \033[0m
> {0}
\033[1;32m# Run all code checker tests \033[0m
> {0} B_CheckCode
\033[1;32m# Run test test_wait_for_test_all_pass from class M_TestWaitForTests \033[0m
> {0} M_TestWaitForTests.test_wait_for_test_all_pass
""".format(os.path.basename(sys.argv[0]))
parser = argparse.ArgumentParser(usage=help_str,
description=description,
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--fast", action="store_true",
help="Skip full system tests, which saves a lot of time")
parser.add_argument("--no-batch", action="store_true",
help="Do not submit jobs to batch system, run locally."
" If false, will default to machine setting.")
parser.add_argument("--no-cmake", action="store_true",
help="Do not run cmake tests")
parser.add_argument("--no-teardown", action="store_true",
help="Do not delete directories left behind by testing")
parser.add_argument("--machine",
help="Select a specific machine setting for cime")
parser.add_argument("--compiler",
help="Select a specific compiler setting for cime")
parser.add_argument( "--mpilib",
help="Select a specific compiler setting for cime")
parser.add_argument( "--test-root",
help="Select a specific test root for all cases created by the testing")
parser.add_argument("--timeout", type=int,
help="Select a specific timeout for all tests")
ns, args = parser.parse_known_args()
# Now set the sys.argv to the unittest_args (leaving sys.argv[0] alone)
sys.argv[1:] = args
FAST_ONLY = ns.fast
NO_BATCH = ns.no_batch
NO_CMAKE = ns.no_cmake
GLOBAL_TIMEOUT = ns.timeout
NO_TEARDOWN = ns.no_teardown
if ns.machine is not None:
MACHINE = Machines(machine=ns.machine)
os.environ["CIME_MACHINE"] = ns.machine
elif "CIME_MACHINE" in os.environ:
mach_name = os.environ["CIME_MACHINE"]
MACHINE = Machines(machine=mach_name)
elif config.has_option("create_test", "MACHINE"):
MACHINE = Machines(machine=config.get("create_test", "MACHINE"))
elif config.has_option("main", "MACHINE"):
MACHINE = Machines(machine=config.get("main", "MACHINE"))
else:
MACHINE = Machines()
if ns.compiler is not None:
TEST_COMPILER = ns.compiler
elif config.has_option("create_test", "COMPILER"):
TEST_COMPILER = config.get("create_test", "COMPILER")
elif config.has_option("main", "COMPILER"):
TEST_COMPILER = config.get("main", "COMPILER")
if ns.mpilib is not None:
TEST_MPILIB = ns.mpilib
elif config.has_option("create_test", "MPILIB"):
TEST_MPILIB = config.get("create_test", "MPILIB")
elif config.has_option("main", "MPILIB"):
TEST_MPILIB = config.get("main", "MPILIB")
if ns.test_root is not None:
TEST_ROOT = ns.test_root
elif config.has_option("create_test", "TEST_ROOT"):
TEST_ROOT = config.get("create_test", "TEST_ROOT")
else:
TEST_ROOT = os.path.join(MACHINE.get_value("CIME_OUTPUT_ROOT"),
"scripts_regression_test.%s"% CIME.utils.get_timestamp())
args = lambda: None # just something to set attrs on
for log_param in ["debug", "silent", "verbose"]:
flag = "--%s" % log_param
if flag in sys.argv:
sys.argv.remove(flag)
setattr(args, log_param, True)
else:
setattr(args, log_param, False)
args = CIME.utils.parse_args_and_handle_standard_logging_options(args, None)
write_provenance_info()
# Find all python files in repo and create a pylint test for each
if check_for_pylint():
files_to_test = get_all_checkable_files()
for file_to_test in files_to_test:
pylint_test = make_pylint_test(file_to_test, files_to_test)
testname = "test_pylint_%s" % file_to_test.replace("/", "_").replace(".", "_")
expect(not hasattr(B_CheckCode, testname), "Repeat %s" % testname)
setattr(B_CheckCode, testname, pylint_test)
try:
unittest.main(verbosity=2, catchbreak=True)
except CIMEError as e:
if e.__str__() != "False":
print("Detected failures, leaving directory:", TEST_ROOT)
else:
print("All pass, removing directory:", TEST_ROOT)
if os.path.exists(TEST_ROOT) and not NO_TEARDOWN:
shutil.rmtree(TEST_ROOT)
raise
if (__name__ == "__main__"):
_main_func(__doc__)
| 49.173697
| 242
| 0.585547
|
4a0a7ff3b6132731e48564e66d8ad61afe924423
| 721
|
py
|
Python
|
django/pokemongo/migrations/0018_auto_20181224_2312.py
|
TrainerDex/trainerdex.co.uk
|
82b029b8ac480686ec192233c5bc62521d480f88
|
[
"Apache-2.0"
] | 1
|
2021-03-04T14:46:31.000Z
|
2021-03-04T14:46:31.000Z
|
django/pokemongo/migrations/0018_auto_20181224_2312.py
|
TrainerDex/trainerdex.co.uk
|
82b029b8ac480686ec192233c5bc62521d480f88
|
[
"Apache-2.0"
] | 99
|
2020-09-10T11:00:59.000Z
|
2022-03-29T09:08:40.000Z
|
django/pokemongo/migrations/0018_auto_20181224_2312.py
|
TrainerDex/trainerdex.co.uk
|
82b029b8ac480686ec192233c5bc62521d480f88
|
[
"Apache-2.0"
] | 1
|
2021-12-21T00:54:01.000Z
|
2021-12-21T00:54:01.000Z
|
# Generated by Django 2.1.4 on 2018-12-24 23:12
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("pokemongo", "0017_auto_20181213_1025"),
]
operations = [
migrations.AlterField(
model_name="update",
name="badge_pokedex_entries_gen4",
field=models.PositiveIntegerField(
blank=True,
help_text="Register 80 Pokémon first discovered in the Sinnoh region to the Pokédex.",
null=True,
validators=[django.core.validators.MaxValueValidator(61)],
verbose_name="Sinnoh",
),
),
]
| 27.730769
| 102
| 0.599168
|
4a0a7ffa3007a6fd14a92bc73ac0201db683746f
| 172,813
|
py
|
Python
|
scalyr_agent/configuration.py
|
ArthurKamalov/scalyr-agent-2
|
8392568792fa06534ed9f9ef1892cf91577e3a62
|
[
"Apache-2.0"
] | 1
|
2021-06-17T18:20:40.000Z
|
2021-06-17T18:20:40.000Z
|
scalyr_agent/configuration.py
|
kdelph23/scalyr-agent-2
|
6b975db59367d271eeba6a614ac40c7cb4205c41
|
[
"Apache-2.0"
] | null | null | null |
scalyr_agent/configuration.py
|
kdelph23/scalyr-agent-2
|
6b975db59367d271eeba6a614ac40c7cb4205c41
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2014 Scalyr Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
# ------------------------------------------------------------------------
#
#
# author: Steven Czerwinski <czerwin@scalyr.com>
from __future__ import unicode_literals
from __future__ import absolute_import
__author__ = "czerwin@scalyr.com"
if False:
from typing import Tuple
from typing import Dict
from typing import List
import os
import re
import sys
import socket
import time
import logging
import copy
import json
import stat
import platform
import six
import six.moves.urllib.parse
from six.moves import range
try:
import win32file
except ImportError:
# Likely not running on Windows
win32file = None
import scalyr_agent.util as scalyr_util
from scalyr_agent.json_lib import JsonConversionException, JsonMissingFieldException
from scalyr_agent.json_lib.objects import (
JsonObject,
JsonArray,
ArrayOfStrings,
SpaceAndCommaSeparatedArrayOfStrings,
)
from scalyr_agent.monitor_utils.blocking_rate_limiter import BlockingRateLimiter
from scalyr_agent.config_util import BadConfiguration, get_config_from_env
from scalyr_agent.__scalyr__ import get_install_root
from scalyr_agent.compat import os_environ_unicode
from scalyr_agent import compat
FILE_WRONG_OWNER_ERROR_MSG = """
File \"%s\" is not readable by the current user (%s).
You need to make sure that the file is owned by the same account which is used to run the agent.
Original error: %s
""".strip()
MASKED_CONFIG_ITEM_VALUE = "********** MASKED **********"
# prefix for the worker session log file name.
AGENT_WORKER_SESSION_LOG_NAME_PREFIX = "agent-worker-session-"
class Configuration(object):
"""Encapsulates the results of a single read of the configuration file.
An instance of this object can be used to read and validate the configuration file. It supports
reading the main contents of the configuration, as well as configuration fragments in the 'configs.d'
directory. It handles merging the contents of the configuration files together and filling in any default
values for fields not set. You can also use the equivalent method to determine if two instances of this
object have the same configuration content.
You may also use environment variable substitution in any string value in the configuration file. You just
need to define the ``import_vars`` configuration field to be a list of variable names to import from the
shell and then use the $VAR_NAME in any string field. Each entry in ``import_vars`` may also be a dict with
two entries: ``var`` for the name of the environment variable and ``default`` for the value to use if the
the environment variable is not set or is empty.
This also handles reporting status information about the configuration state, including what time it was
read and what error (if any) was raised.
Note:
UNDOCUMENTED_CONFIG: These are undocumented config params, meaning they are not described in the public online docs
in order to simplify the mental model. In rare cases, a customer may need to tune these params under direct
guidance from support.
"""
DEFAULT_K8S_IGNORE_NAMESPACES = ["kube-system"]
DEFAULT_K8S_INCLUDE_NAMESPACES = ["*"]
def __init__(
self, file_path, default_paths, logger, extra_config_dir=None, log_warnings=True
):
# Captures all environment aware variables for testing purposes
self._environment_aware_map = {}
self.__file_path = os.path.abspath(file_path)
# Paths for additional configuration files that were read (from the config directory).
self.__additional_paths = []
# The JsonObject holding the contents of the configuration file, along with any default
# values filled in.
self.__config = None
# The number of seconds past epoch when the file was read.
self.__read_time = None
# The exception, if any, that was raised when the state was read. This will be a BadConfiguration exception.
self.__last_error = None
# The log configuration objects from the configuration file. This does not include logs required by
# the monitors.
self.__log_configs = []
# Optional configuration for journald monitor logging
self.__journald_log_configs = []
# Optional configuration for k8s monitor logging
self.__k8s_log_configs = []
# The monitor configuration objects from the configuration file. This does not include monitors that
# are created by default by the platform.
self.__monitor_configs = []
self.__worker_configs = []
# The DefaultPaths object that specifies the default paths for things like the data and log directory
# based on platform.
self.__default_paths = default_paths
# FIX THESE:
# Add documentation, verify, etc.
self.max_retry_time = 15 * 60
self.max_allowed_checkpoint_age = 15 * 60
# An additional directory to look for config snippets
self.__extra_config_directory = extra_config_dir
# True to emit warnings on parse. In some scenarios such as when parsing config for agent
# status command we don't want to emit / log warnings since they will interleve with the
# status output
self.__log_warnings = log_warnings
self.__logger = logger
def parse(self):
self.__read_time = time.time()
try:
try:
# First read the file. This makes sure it exists and can be parsed.
self.__config = scalyr_util.read_config_file_as_json(self.__file_path)
# What implicit entries do we need to add? metric monitor, agent.log, and then logs from all monitors.
except Exception as e:
# Special case - file is not readable, likely means a permission issue so return a
# more user-friendly error
msg = str(e).lower()
if (
"file is not readable" in msg
or "error reading" in msg
or "failed while reading"
):
from scalyr_agent.platform_controller import PlatformController
platform_controller = PlatformController.new_platform()
current_user = platform_controller.get_current_user()
msg = FILE_WRONG_OWNER_ERROR_MSG % (
self.__file_path,
current_user,
six.text_type(e),
)
raise BadConfiguration(msg, None, "fileParseError")
raise BadConfiguration(six.text_type(e), None, "fileParseError")
# Import any requested variables from the shell and use them for substitutions.
self.__perform_substitutions(self.__config)
self._check_config_file_permissions_and_warn(self.__file_path)
# get initial list of already seen config keys (we need to do this before
# defaults have been applied)
already_seen = {}
for k in self.__config.keys():
already_seen[k] = self.__file_path
self.__verify_main_config_and_apply_defaults(
self.__config, self.__file_path
)
api_key, api_config_file = self.__check_field(
"api_key", self.__config, self.__file_path
)
scalyr_server, scalyr_server_config_file = self.__check_field(
"scalyr_server", self.__config, self.__file_path
)
self.__verify_logs_and_monitors_configs_and_apply_defaults(
self.__config, self.__file_path
)
# these variables are allowed to appear in multiple files
allowed_multiple_keys = (
"import_vars",
"logs",
"journald_logs",
"k8s_logs",
"monitors",
"server_attributes",
"workers",
)
# map keys to their deprecated versions to replace them later.
allowed_multiple_keys_deprecated_synonyms = {"workers": ["api_keys"]}
# Get any configuration snippets in the config directory
extra_config = self.__list_files(self.config_directory)
# Plus any configuration snippets in the additional config directory
extra_config.extend(self.__list_files(self.extra_config_directory))
# Now, look for any additional configuration in the config fragment directory.
for fp in extra_config:
self.__additional_paths.append(fp)
content = scalyr_util.read_config_file_as_json(fp)
# if deprecated key names are used, then replace them with their current versions.
for k, v in list(content.items()):
for (
key,
key_synonyms,
) in allowed_multiple_keys_deprecated_synonyms.items():
if k in key_synonyms:
# replace deprecated key.
content[key] = v
del content[k]
break
for k in content.keys():
if k not in allowed_multiple_keys:
if k in already_seen:
self.__last_error = BadConfiguration(
'Configuration fragment file "%s" redefines the config key "%s", first seen in "%s". '
"The only config items that can be defined in multiple config files are: %s."
% (fp, k, already_seen[k], allowed_multiple_keys),
k,
"multipleKeys",
)
raise self.__last_error
else:
already_seen[k] = fp
self._check_config_file_permissions_and_warn(fp)
self.__perform_substitutions(content)
self.__verify_main_config(content, self.__file_path)
self.__verify_logs_and_monitors_configs_and_apply_defaults(content, fp)
for (key, value) in six.iteritems(content):
if key not in allowed_multiple_keys:
self.__config.put(key, value)
self.__add_elements_from_array("logs", content, self.__config)
self.__add_elements_from_array("journald_logs", content, self.__config)
self.__add_elements_from_array("k8s_logs", content, self.__config)
self.__add_elements_from_array("monitors", content, self.__config)
self.__add_elements_from_array(
"workers", content, self.__config, deprecated_names=["api_keys"]
)
self.__merge_server_attributes(fp, content, self.__config)
self.__set_api_key(self.__config, api_key)
if scalyr_server is not None:
self.__config.put("scalyr_server", scalyr_server)
self.__verify_or_set_optional_string(
self.__config,
"scalyr_server",
"https://agent.scalyr.com",
"configuration file %s" % self.__file_path,
env_name="SCALYR_SERVER",
)
self.__config["raw_scalyr_server"] = self.__config["scalyr_server"]
# force https unless otherwise instructed not to
if not self.__config["allow_http"]:
server = self.__config["scalyr_server"].strip()
https_server = server
parts = six.moves.urllib.parse.urlparse(server)
# use index-based addressing for 2.4 compatibility
scheme = parts[0]
if not scheme:
https_server = "https://" + server
elif scheme == "http":
https_server = re.sub("^http://", "https://", server)
if https_server != server:
self.__config["scalyr_server"] = https_server
# Set defaults based on `max_send_rate_enforcement` value
if (
not self.__config["disable_max_send_rate_enforcement_overrides"]
and not self.__config["max_send_rate_enforcement"] == "legacy"
):
self._warn_of_override_due_to_rate_enforcement(
"max_allowed_request_size", 1024 * 1024
)
self._warn_of_override_due_to_rate_enforcement(
"pipeline_threshold", 1.1
)
self._warn_of_override_due_to_rate_enforcement(
"min_request_spacing_interval", 1.0
)
self._warn_of_override_due_to_rate_enforcement(
"max_request_spacing_interval", 5.0
)
self._warn_of_override_due_to_rate_enforcement(
"max_log_offset_size", 5 * 1024 * 1024
)
self._warn_of_override_due_to_rate_enforcement(
"max_existing_log_offset_size", 100 * 1024 * 1024
)
self.__config["max_allowed_request_size"] = 5900000
self.__config["pipeline_threshold"] = 0
self.__config["min_request_spacing_interval"] = 0.0
self.__config["max_request_spacing_interval"] = 5.0
self.__config["max_log_offset_size"] = 200000000
self.__config["max_existing_log_offset_size"] = 200000000
# Parse `max_send_rate_enforcement`
if (
self.__config["max_send_rate_enforcement"] != "unlimited"
and self.__config["max_send_rate_enforcement"] != "legacy"
):
try:
self.__config[
"parsed_max_send_rate_enforcement"
] = scalyr_util.parse_data_rate_string(
self.__config["max_send_rate_enforcement"]
)
except ValueError as e:
raise BadConfiguration(
six.text_type(e), "max_send_rate_enforcement", "notDataRate"
)
# Add in 'serverHost' to server_attributes if it is not set. We must do this after merging any
# server attributes from the config fragments.
if "serverHost" not in self.server_attributes:
self.__config["server_attributes"][
"serverHost"
] = self.__get_default_hostname()
# Add in implicit entry to collect the logs generated by this agent and its worker sessions.
agent_log = None
worker_session_agent_logs = None
if self.implicit_agent_log_collection:
# set path as glob to handle log files from the multiprocess worker sessions.
config = JsonObject(
path="agent.log",
parser="scalyrAgentLog",
)
# add log config for the worker session agent log files.
worker_session_logs_config = JsonObject(
path="%s*.log" % AGENT_WORKER_SESSION_LOG_NAME_PREFIX,
# exclude debug files for the worker session debug logs.
# NOTE: the glob for the excluded files has to be restrictive enough,
# so it matches only worker session debug logs.
exclude=JsonArray(
"*%s*_debug.log" % AGENT_WORKER_SESSION_LOG_NAME_PREFIX
),
parser="scalyrAgentLog",
)
self.__verify_log_entry_and_set_defaults(
config, description="implicit rule"
)
self.__verify_log_entry_and_set_defaults(
worker_session_logs_config, description="implicit rule"
)
agent_log = config
worker_session_agent_logs = worker_session_logs_config
self.__log_configs = list(self.__config.get_json_array("logs"))
if agent_log is not None:
self.__log_configs.append(agent_log)
if worker_session_agent_logs is not None:
self.__log_configs.append(worker_session_agent_logs)
self.__journald_log_configs = list(
self.__config.get_json_array("journald_logs")
)
self.__k8s_log_configs = list(self.__config.get_json_array("k8s_logs"))
# add in the profile log if we have enabled profiling
if self.enable_profiling:
profile_config = JsonObject(
path=self.profile_log_name,
copy_from_start=True,
staleness_threshold_secs=20 * 60,
parser="scalyrAgentProfiling",
)
self.__verify_log_entry_and_set_defaults(
profile_config, description="CPU profile log config"
)
self.__log_configs.append(profile_config)
self.__monitor_configs = list(self.__config.get_json_array("monitors"))
# Perform validation for k8s_logs option
self._check_k8s_logs_config_option_and_warn()
# NOTE do this verifications only after all config fragments were added into configurations.
self.__verify_workers()
self.__verify_and_match_workers_in_logs()
self.__worker_configs = list(self.__config.get_json_array("workers"))
except BadConfiguration as e:
self.__last_error = e
raise e
def __verify_workers(self):
"""
Verify all worker config entries from the "workers" list in config.
"""
workers = list(self.__config.get_json_array("workers"))
unique_worker_ids = {}
# Apply other defaults to all worker entries
for i, worker_entry in enumerate(workers):
self.__verify_workers_entry_and_set_defaults(worker_entry, entry_index=i)
worker_id = worker_entry["id"]
if worker_id in unique_worker_ids:
raise BadConfiguration(
"There are multiple workers with the same '%s' id. Worker id's must remain unique."
% worker_id,
"workers",
"workerIdDuplication",
)
else:
unique_worker_ids[worker_id] = worker_entry
default_worker_entry = unique_worker_ids.get("default")
if default_worker_entry is None:
default_worker_entry = JsonObject(api_key=self.api_key, id="default")
self.__verify_workers_entry_and_set_defaults(default_worker_entry)
workers.insert(0, default_worker_entry)
self.__config.put("workers", JsonArray(*workers))
def __verify_and_match_workers_in_logs(self):
"""
Check if every log file entry contains a valid reference to the worker.
Each log file config entry has to have a field "worker_id" which refers to some entry in the "workers" list.
If such "worker_id" field is not specified, then the id of the default worker is used.
If "worker_id" is specified but there is no such api key, then the error is raised.
"""
# get the set of all worker ids.
worker_ids = set()
for worker_config in self.__config.get_json_array("workers"):
worker_ids.add(worker_config["id"])
# get all lists where log files entries may be defined.
log_config_lists = [
self.__log_configs,
self.__k8s_log_configs,
self.__journald_log_configs,
]
for log_config_list in log_config_lists:
for log_file_config in log_config_list:
worker_id = log_file_config.get("worker_id", none_if_missing=True)
if worker_id is None:
# set a default worker if worker_id is not specified.
log_file_config["worker_id"] = "default"
else:
# if log file entry has worker_id which is not defined in the 'workers' list, then throw an error.
if worker_id not in worker_ids:
valid_worker_ids = ", ".join(sorted(worker_ids))
raise BadConfiguration(
"The log entry '%s' refers to a non-existing worker with id '%s'. Valid worker ids: %s."
% (
six.text_type(log_file_config),
worker_id,
valid_worker_ids,
),
"logs",
"invalidWorkerReference",
)
def _check_config_file_permissions_and_warn(self, file_path):
# type: (str) -> None
"""
Check config file permissions and log a warning is it's readable or writable by "others".
"""
if not self.__log_warnings:
return None
if not os.path.isfile(file_path) or not self.__logger:
return None
st_mode = os.stat(file_path).st_mode
if bool(st_mode & stat.S_IROTH) or bool(st_mode & stat.S_IWOTH):
file_permissions = str(oct(st_mode)[4:])
if file_permissions.startswith("0") and len(file_permissions) == 4:
file_permissions = file_permissions[1:]
limit_key = "config-permissions-warn-%s" % (file_path)
self.__logger.warn(
"Config file %s is readable or writable by others (permissions=%s). Config "
"files can "
"contain secrets so you are strongly encouraged to change the config "
"file permissions so it's not readable by others."
% (file_path, file_permissions),
limit_once_per_x_secs=86400,
limit_key=limit_key,
)
def _check_k8s_logs_config_option_and_warn(self):
# type: () -> None
"""
Check if k8s_logs attribute is configured, but kubernetes monitor is not and warn.
k8s_logs is a top level config option, but it's utilized by Kubernetes monitor which means
it will have no affect if kubernetes monitor is not configured as well.
"""
if (
self.__k8s_log_configs
and not self._is_kubernetes_monitor_configured()
and self.__log_warnings
):
self.__logger.warn(
'"k8s_logs" config options is defined, but Kubernetes monitor is '
"not configured / enabled. That config option applies to "
"Kubernetes monitor so for it to have an affect, Kubernetes "
"monitor needs to be enabled and configured",
limit_once_per_x_secs=86400,
limit_key="k8s_logs_k8s_monitor_not_enabled",
)
def _is_kubernetes_monitor_configured(self):
# type: () -> bool
"""
Return true if Kubernetes monitor is configured, false otherwise.
"""
monitor_configs = self.monitor_configs or []
for monitor_config in monitor_configs:
if (
monitor_config.get("module", "")
== "scalyr_agent.builtin_monitors.kubernetes_monitor"
):
return True
return False
def _warn_of_override_due_to_rate_enforcement(self, config_option, default):
if self.__log_warnings and self.__config[config_option] != default:
self.__logger.warn(
"Configured option %s is being overridden due to max_send_rate_enforcement setting."
% config_option,
limit_once_per_x_secs=86400,
limit_key="max_send_rate_enforcement_override",
)
def apply_config(self):
"""
Apply global configuration object based on the configuration values.
At this point this only applies to the JSON library which is used and maxstdio settings on
Windows.
"""
if not self.__config:
# parse() hasn't been called yet. We should probably throw here
return
# Set json library based on the config value. If "auto" is provided this means we use
# default behavior which is try to use ujson and if that's not available fall back to
# stdlib json
json_library = self.json_library
current_json_library = scalyr_util.get_json_lib()
if json_library != "auto" and json_library != current_json_library:
self.__logger.debug(
'Changing JSON library from "%s" to "%s"'
% (current_json_library, json_library)
)
scalyr_util.set_json_lib(json_library)
# Call method which applies Windows specific global config options
self.__apply_win32_global_config_options()
def __apply_win32_global_config_options(self):
"""
Method which applies Windows specific global configuration options.
"""
if not sys.platform.startswith("win"):
# Not a Windows platformn
return
# Change the value for maxstdio process specific option
if not win32file:
# win32file module not available
return None
# TODO: We should probably use platform Windows module for this
max_open_fds = self.win32_max_open_fds
current_max_open_fds = win32file._getmaxstdio()
if (max_open_fds and current_max_open_fds) and (
max_open_fds != current_max_open_fds
):
self.__logger.debug(
'Changing limit for max open fds (maxstdio) from "%s" to "%s"'
% (current_max_open_fds, max_open_fds)
)
try:
win32file._setmaxstdio(max_open_fds)
except Exception:
self.__logger.exception("Failed to change the value of maxstdio")
def print_useful_settings(self, other_config=None):
"""
Prints various useful configuration settings to the agent log, so we have a record
in the log of the settings that are currently in use.
@param other_config: Another configuration option. If not None, this function will
only print configuration options that are different between the two objects.
"""
options = [
"verify_server_certificate",
"ca_cert_path",
"compression_type",
"compression_level",
"pipeline_threshold",
"max_send_rate_enforcement",
"disable_max_send_rate_enforcement_overrides",
"min_allowed_request_size",
"max_allowed_request_size",
"min_request_spacing_interval",
"max_request_spacing_interval",
"read_page_size",
"max_line_size",
"internal_parse_max_line_size",
"line_completion_wait_time",
"max_log_offset_size",
"max_existing_log_offset_size",
"json_library",
"use_multiprocess_workers",
"default_sessions_per_worker",
"default_worker_session_status_message_interval",
"enable_worker_session_process_metrics_gather",
# NOTE: It's important we use sanitzed_ version of this method which masks the API key
"sanitized_worker_configs",
]
# get options (if any) from the other configuration object
other_options = None
if other_config is not None:
other_options = {}
for option in options:
other_options[option] = getattr(other_config, option, None)
first = True
for option in options:
value = getattr(self, option, None)
print_value = False
# check to see if we should be printing this option which will will
# be True if other_config is None or if the other_config had a setting
# that was different from our current setting
if other_config is None:
print_value = True
elif (
other_options is not None
and option in other_options
and other_options[option] != value
):
print_value = True
# For json_library config option, we also print actual library which is being used in
# case the value is set to "auto"
if option == "json_library" and value == "auto":
json_lib = scalyr_util.get_json_lib()
value = "%s (%s)" % (value, json_lib)
if print_value:
# if this is the first option we are printing, output a header
if first:
self.__logger.info("Configuration settings")
first = False
if isinstance(value, (list, dict)):
# We remove u"" prefix to ensure consistent output between Python 2 and 3
value = six.text_type(value).replace("u'", "'")
self.__logger.info("\t%s: %s" % (option, value))
# Print additional useful Windows specific information on Windows
win32_max_open_fds_previous_value = getattr(
other_config, "win32_max_open_fds", None
)
win32_max_open_fds_current_value = getattr(self, "win32_max_open_fds", None)
if (
sys.platform.startswith("win")
and win32file
and (
win32_max_open_fds_current_value != win32_max_open_fds_previous_value
or other_config is None
)
):
try:
win32_max_open_fds_actual_value = win32file._getmaxstdio()
except Exception:
win32_max_open_fds_actual_value = "unknown"
if first:
self.__logger.info("Configuration settings")
self.__logger.info(
"\twin32_max_open_fds(maxstdio): %s (%s)"
% (win32_max_open_fds_current_value, win32_max_open_fds_actual_value)
)
# If debug level 5 is set also log the raw config JSON excluding the api_key
# This makes various troubleshooting easier.
if self.debug_level >= 5:
try:
raw_config = self.__get_sanitized_raw_config()
self.__logger.info("Raw config value: %s" % (json.dumps(raw_config)))
except Exception:
# If for some reason we fail to serialize the config, this should not be fatal
pass
def __get_sanitized_raw_config(self):
# type: () -> dict
"""
Return raw config values as a dictionary, masking any secret values such as "api_key".
"""
if not self.__config:
return {}
values_to_mask = [
"api_key",
]
raw_config = copy.deepcopy(self.__config.to_dict())
for key in values_to_mask:
if key in raw_config:
raw_config[key] = MASKED_CONFIG_ITEM_VALUE
# Ensure we also sanitize api_key values in workers dictionaries
if "workers" in raw_config:
raw_config["workers"] = self.sanitized_worker_configs
return raw_config
def __get_default_hostname(self):
"""Returns the default hostname for this host.
@return: The default hostname for this host.
@rtype: str
"""
result = six.ensure_text(socket.gethostname())
if result is not None and self.strip_domain_from_default_server_host:
result = result.split(".")[0]
return result
@staticmethod
def get_session_ids_of_the_worker(worker_config): # type: (Dict) -> List
"""
Generate the list of IDs of all sessions for the specified worker.
:param worker_config: config entry for the worker.
:return: List of worker session IDs.
"""
result = []
for i in range(worker_config["sessions"]):
# combine the id of the worker and session's position in the list to get a session id.
worker_session_id = "%s-%s" % (worker_config["id"], i)
result.append(worker_session_id)
return result
def get_session_ids_from_all_workers(self): # type: () -> List[six.text_type]
"""
Get session ids for all workers.
:return: List of worker session ids.
"""
result = []
for worker_config in self.worker_configs:
result.extend(self.get_session_ids_of_the_worker(worker_config))
return result
def get_worker_session_agent_log_path(
self, worker_session_id
): # type: (six.text_type) -> six.text_type
"""
Generate the name of the log file path for the worker session based on its id.
:param worker_session_id: ID of the worker session.
:return: path for the worker session log file.
"""
return os.path.join(
self.agent_log_path,
"%s%s.log" % (AGENT_WORKER_SESSION_LOG_NAME_PREFIX, worker_session_id),
)
def parse_log_config(
self,
log_config,
default_parser=None,
context_description="uncategorized log entry",
):
"""Parses a given configuration stanza for a log file and returns the complete config with all the
default values filled in.
This is useful for parsing a log configuration entry that was not originally included in the configuration
but whose contents still must be verified. For example, a log configuration entry from a monitor.
@param log_config: The configuration entry for the log.
@param default_parser: If the configuration entry does not have a ``parser`` entry, set this as the default.
@param context_description: The context of where this entry came from, used when creating an error message
for the user.
@type log_config: dict|JsonObject
@type default_parser: str
@type context_description: str
@return: The full configuration for the log.
@rtype: JsonObject
"""
if type(log_config) is dict:
log_config = JsonObject(content=log_config)
log_config = log_config.copy()
if default_parser is not None:
self.__verify_or_set_optional_string(
log_config, "parser", default_parser, context_description
)
self.__verify_log_entry_and_set_defaults(
log_config, description=context_description
)
return log_config
def parse_monitor_config(
self, monitor_config, context_description="uncategorized monitor entry"
):
"""Parses a given monitor configuration entry and returns the complete config with all default values
filled in.
This is useful for parsing a monitor configuration entry that was not originally included in the
configuration but whose contents still must be verified. For example, a default monitor supplied by the
platform.
@param monitor_config: The configuration entry for the monitor.
@param context_description: The context of where this entry came from, used when creating an error message
for the user.
@type monitor_config: dict|JsonObject
@type context_description: str
@return: The full configuration for the monitor.
@rtype: JsonObject
"""
if type(monitor_config) is dict:
monitor_config = JsonObject(content=monitor_config)
monitor_config = monitor_config.copy()
self.__verify_monitor_entry_and_set_defaults(
monitor_config, context_description=context_description
)
return monitor_config
# k8s cache options
@property
def k8s_ignore_namespaces(self):
return self.__get_config().get_json_array("k8s_ignore_namespaces")
@property
def k8s_include_namespaces(self):
return self.__get_config().get_json_array("k8s_include_namespaces")
@property
def k8s_api_url(self):
return self.__get_config().get_string("k8s_api_url")
@property
def k8s_verify_api_queries(self):
return self.__get_config().get_bool("k8s_verify_api_queries")
@property
def k8s_verify_kubelet_queries(self):
return self.__get_config().get_bool("k8s_verify_kubelet_queries")
@property
def k8s_kubelet_ca_cert(self):
return self.__get_config().get_string("k8s_kubelet_ca_cert")
@property
def k8s_cache_query_timeout_secs(self):
return self.__get_config().get_int("k8s_cache_query_timeout_secs")
@property
def k8s_cache_expiry_secs(self):
return self.__get_config().get_int("k8s_cache_expiry_secs")
@property
def k8s_cache_expiry_fuzz_secs(self):
return self.__get_config().get_int("k8s_cache_expiry_fuzz_secs")
@property
def k8s_cache_start_fuzz_secs(self):
return self.__get_config().get_int("k8s_cache_start_fuzz_secs")
@property
def k8s_cache_purge_secs(self):
return self.__get_config().get_int("k8s_cache_purge_secs")
@property
def k8s_service_account_cert(self):
return self.__get_config().get_string("k8s_service_account_cert")
@property
def k8s_service_account_token(self):
return self.__get_config().get_string("k8s_service_account_token")
@property
def k8s_service_account_namespace(self):
return self.__get_config().get_string("k8s_service_account_namespace")
@property
def k8s_log_api_responses(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_bool("k8s_log_api_responses")
@property
def k8s_log_api_exclude_200s(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_bool("k8s_log_api_exclude_200s")
@property
def k8s_log_api_min_response_len(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_int("k8s_log_api_min_response_len")
@property
def k8s_log_api_min_latency(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_float("k8s_log_api_min_latency")
@property
def k8s_log_api_ratelimit_interval(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_float("k8s_log_api_ratelimit_interval")
@property
def k8s_controlled_warmer_max_attempts(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_int("k8s_controlled_warmer_max_attempts")
@property
def k8s_controlled_warmer_max_query_retries(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_int("k8s_controlled_warmer_max_query_retries")
@property
def k8s_controlled_warmer_blacklist_time(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_int("k8s_controlled_warmer_blacklist_time")
@property
def k8s_events_disable(self):
return self.__get_config().get_bool("k8s_events_disable")
@property
def k8s_ratelimit_cluster_num_agents(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_int("k8s_ratelimit_cluster_num_agents")
@property
def k8s_ratelimit_cluster_rps_init(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_float("k8s_ratelimit_cluster_rps_init")
@property
def k8s_ratelimit_cluster_rps_min(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_float("k8s_ratelimit_cluster_rps_min")
@property
def k8s_ratelimit_cluster_rps_max(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_float("k8s_ratelimit_cluster_rps_max")
@property
def k8s_ratelimit_consecutive_increase_threshold(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_int(
"k8s_ratelimit_consecutive_increase_threshold"
)
@property
def k8s_ratelimit_strategy(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_string("k8s_ratelimit_strategy")
@property
def k8s_ratelimit_increase_factor(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_float("k8s_ratelimit_increase_factor")
@property
def k8s_ratelimit_backoff_factor(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_float("k8s_ratelimit_backoff_factor")
@property
def k8s_ratelimit_max_concurrency(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_int("k8s_ratelimit_max_concurrency")
@property
def enforce_monotonic_timestamps(self):
# UNDOCUMENTED_CONFIG
return self.__get_config().get_bool("enforce_monotonic_timestamps")
@property
def include_raw_timestamp_field(self):
"""If True, adds an attribute called `raw_timestamp` to all events parsed using the
parse_as_json or parse_as_cri features. This field will be set to the timestamp included in the JSON or
CRI line. When parsing Docker or K8s logs, this represents the timestamp of the log
message as recorded by those systems."""
return self.__get_config().get_bool("include_raw_timestamp_field")
@property
def enable_profiling(self):
return self.__get_config().get_bool("enable_profiling")
@property
def max_profile_interval_minutes(self):
return self.__get_config().get_int("max_profile_interval_minutes")
@property
def profile_duration_minutes(self):
return self.__get_config().get_int("profile_duration_minutes")
@property
def profile_clock(self):
return self.__get_config().get_string("profile_clock")
@property
def profile_log_name(self):
return self.__get_config().get_string("profile_log_name")
@property
def memory_profile_log_name(self):
return self.__get_config().get_string("memory_profile_log_name")
@property
def disable_logfile_addevents_format(self):
return self.__get_config().get_bool("disable_logfile_addevents_format")
@property
def json_library(self):
return self.__get_config().get_string("json_library")
# Debug leak flags
@property
def disable_send_requests(self):
return self.__get_config().get_bool("disable_send_requests")
# Debug leak flags
@property
def disable_monitor_threads(self):
return self.__get_config().get_bool("disable_leak_monitor_threads")
@property
def disable_monitors_creation(self):
return self.__get_config().get_bool("disable_leak_monitors_creation")
@property
def disable_new_file_matches(self):
return self.__get_config().get_bool("disable_leak_new_file_matches")
@property
def disable_scan_for_new_bytes(self):
return self.__get_config().get_bool("disable_leak_scan_for_new_bytes")
@property
def disable_processing_new_bytes(self):
return self.__get_config().get_bool("disable_leak_processing_new_bytes")
@property
def disable_copying_thread(self):
return self.__get_config().get_bool("disable_leak_copying_thread")
@property
def disable_overall_stats(self):
return self.__get_config().get_bool("disable_leak_overall_stats")
@property
def disable_bandwidth_stats(self):
return self.__get_config().get_bool("disable_leak_bandwidth_stats")
@property
def disable_copy_manager_stats(self):
return self.__get_config().get_bool("disable_copy_manager_stats")
@property
def disable_update_debug_log_level(self):
return self.__get_config().get_bool("disable_leak_update_debug_log_level")
@property
def enable_gc_stats(self):
return self.__get_config().get_bool("enable_gc_stats")
@property
def disable_all_config_updates(self):
return self.__get_config().get_int(
"disable_leak_all_config_updates", none_if_missing=True
)
@property
def disable_verify_config(self):
return self.__get_config().get_int(
"disable_leak_verify_config", none_if_missing=True
)
@property
def disable_config_equivalence_check(self):
return self.__get_config().get_int(
"disable_leak_config_equivalence_check", none_if_missing=True
)
@property
def disable_verify_can_write_to_logs(self):
return self.__get_config().get_int(
"disable_leak_verify_can_write_to_logs", none_if_missing=True
)
@property
def disable_config_reload(self):
return self.__get_config().get_int(
"disable_leak_config_reload", none_if_missing=True
)
@property
def config_change_check_interval(self):
return self.__get_config().get_float("config_change_check_interval")
@property
def overall_stats_log_interval(self):
return self.__get_config().get_float("overall_stats_log_interval")
@property
def copying_manager_stats_log_interval(self):
return self.__get_config().get_float("copying_manager_stats_log_interval")
@property
def bandwidth_stats_log_interval(self):
return self.__get_config().get_float("bandwidth_stats_log_interval")
@property
def user_agent_refresh_interval(self):
return self.__get_config().get_float("user_agent_refresh_interval")
@property
def garbage_collect_interval(self):
return self.__get_config().get_int("garbage_collect_interval")
@property
def disable_verify_config_create_monitors_manager(self):
return self.__get_config().get_int(
"disable_leak_verify_config_create_monitors_manager", none_if_missing=True
)
@property
def disable_verify_config_create_copying_manager(self):
return self.__get_config().get_int(
"disable_leak_verify_config_create_copying_manager", none_if_missing=True
)
@property
def disable_verify_config_cache_config(self):
return self.__get_config().get_bool("disable_leak_verify_config_cache_config")
# end Debug leak flags
@property
def read_time(self):
"""Returns the time this configuration file was read."""
return self.__read_time
@property
def file_path(self):
"""Returns the time this path of the file that was read for the configuration."""
return self.__file_path
@property
def additional_file_paths(self):
"""Returns a list of the paths for the additional files from the configuration directory that were read."""
return self.__additional_paths
@property
def last_error(self):
"""Returns the error seen (if any) while processing the configuration."""
return self.__last_error
@property
def log_configs(self):
"""Returns the list of configuration entries for all the logs specified in the configuration file.
Note, this does not include logs required by monitors. It is only logs explicitly listed in the configuration
file and possible the agent log as well.
@rtype list<JsonObject>"""
return self.__log_configs
@property
def journald_log_configs(self):
"""Returns the list of configuration entries for all the journald loggers specified in the configuration file.
@rtype list<JsonObject>"""
return self.__journald_log_configs
@property
def k8s_log_configs(self):
"""Returns the list of configuration entries for all the k8s loggers specified in the configuration file.
@rtype list<JsonObject>"""
return self.__k8s_log_configs
@property
def monitor_configs(self):
"""Returns the list of configuration entries for all monitores specified in the configuration file.
Note, this does not include default monitors for the platform. It is only monitors explicitly listed in the
configuration file.
@rtype list<JsonObject>"""
return self.__monitor_configs
@property
def agent_data_path(self):
"""Returns the configuration value for 'agent_data_path'."""
return self.__get_config().get_string("agent_data_path")
@property
def agent_log_path(self):
"""Returns the configuration value for 'agent_log_path'."""
return self.__get_config().get_string("agent_log_path")
@property
def additional_monitor_module_paths(self):
"""Returns the configuration value for 'additional_monitor_module_paths'."""
return self.__get_config().get_string("additional_monitor_module_paths")
@property
def api_key(self):
"""Returns the configuration value for 'api_key'."""
return self.__get_config().get_string("api_key")
@property
def scalyr_server(self):
"""Returns the configuration value for 'scalyr_server'."""
return self.__get_config().get_string("scalyr_server")
@property
def raw_scalyr_server(self):
"""Returns the configuration value for 'raw_scalyr_server'."""
return self.__get_config().get_string("raw_scalyr_server")
@property
def check_remote_if_no_tty(self):
"""Returns the configuration value for `check_remote_if_no_tty`"""
return self.__get_config().get_bool("check_remote_if_no_tty")
@property
def server_attributes(self):
"""Returns the configuration value for 'server_attributes'."""
return self.__get_config().get_json_object("server_attributes")
@property
def implicit_agent_log_collection(self):
"""Returns the configuration value for 'implicit_agent_log_collection'."""
return self.__get_config().get_bool("implicit_agent_log_collection")
@property
def implicit_metric_monitor(self):
"""Returns the configuration value for 'implicit_metric_monitor'."""
return self.__get_config().get_bool("implicit_metric_monitor")
@property
def implicit_agent_process_metrics_monitor(self):
"""Returns the configuration value for 'implicit_agent_process_metrics_monitor'."""
return self.__get_config().get_bool("implicit_agent_process_metrics_monitor")
@property
def use_unsafe_debugging(self):
"""Returns the configuration value for 'unsafe_debugging'.
Note, this should be used with extreme care. It allows arbitrary commands to be executed by any local
user on the system as the user running the agent."""
return self.__get_config().get_bool("use_unsafe_debugging")
@property
def copying_thread_profile_interval(self):
"""Returns the interval (in seconds) between outputs of the profiling for the copying thread.
This should be zero unless you are profiling the copying thread.
"""
return self.__get_config().get_int("copying_thread_profile_interval")
@property
def copying_thread_profile_output_path(self):
"""Returns the path prefix for writing all profiling dumps for the copying thread, when
``copying_thread_profile_interval`` is greater than zero.
@return:
@rtype:
"""
return self.__get_config().get_string("copying_thread_profile_output_path")
@property
def config_directory(self):
"""Returns the configuration value for 'config_directory', resolved to full path if necessary."""
config_directory = self.__get_config().get_string("config_directory")
# The configuration directory's path is relative to the the directory this configuration
# file is stored in.
return self.__resolve_absolute_path(
config_directory, self.__get_parent_directory(self.__file_path)
)
@property
def config_directory_raw(self):
"""Returns the configuration value for 'config_directory', as recorded in the configuration file."""
return self.__get_config().get_string("config_directory")
@property
def parsed_max_send_rate_enforcement(self):
"""Returns the configuration value for 'max_send_rate_enforcement' in bytes per second if not `unlimited` or `legacy`."""
return self.__get_config().get_float(
"parsed_max_send_rate_enforcement", none_if_missing=True
)
@property
def max_send_rate_enforcement(self):
"""Returns the raw value for 'max_send_rate_enforcement'."""
return self.__get_config().get_string("max_send_rate_enforcement")
@property
def disable_max_send_rate_enforcement_overrides(self):
"""Returns the configuration value for 'disable_max_send_rate_enforcement_overrides'."""
return self.__get_config().get_bool(
"disable_max_send_rate_enforcement_overrides"
)
@property
def extra_config_directory(self):
"""Returns the configuration value for `extra_config_directory`, resolved to full path if
necessary."""
# If `extra_config_directory` is a relative path, then it will be relative
# to the directory containing the main config file
if self.__extra_config_directory is None:
return None
return self.__resolve_absolute_path(
self.__extra_config_directory,
self.__get_parent_directory(self.__file_path),
)
@property
def extra_config_directory_raw(self):
"""Returns the configuration value for 'extra_config_directory'."""
return self.__extra_config_directory
@property
def max_allowed_request_size(self):
"""Returns the configuration value for 'max_allowed_request_size'."""
return self.__get_config().get_int("max_allowed_request_size")
@property
def min_allowed_request_size(self):
"""Returns the configuration value for 'min_allowed_request_size'."""
return self.__get_config().get_int("min_allowed_request_size")
@property
def min_request_spacing_interval(self):
"""Returns the configuration value for 'min_request_spacing_interval'."""
return self.__get_config().get_float("min_request_spacing_interval")
@property
def max_request_spacing_interval(self):
"""Returns the configuration value for 'max_request_spacing_interval'."""
return self.__get_config().get_float("max_request_spacing_interval")
@property
def max_error_request_spacing_interval(self):
"""Returns the configuration value for 'max_error_request_spacing_interval'."""
return self.__get_config().get_float("max_error_request_spacing_interval")
@property
def low_water_bytes_sent(self):
"""Returns the configuration value for 'low_water_bytes_sent'."""
return self.__get_config().get_int("low_water_bytes_sent")
@property
def low_water_request_spacing_adjustment(self):
"""Returns the configuration value for 'low_water_request_spacing_adjustment'."""
return self.__get_config().get_float("low_water_request_spacing_adjustment")
@property
def high_water_bytes_sent(self):
"""Returns the configuration value for 'high_water_bytes_sent'."""
return self.__get_config().get_int("high_water_bytes_sent")
@property
def high_water_request_spacing_adjustment(self):
"""Returns the configuration value for 'high_water_request_spacing_adjustment'."""
return self.__get_config().get_float("high_water_request_spacing_adjustment")
@property
def max_new_log_detection_time(self):
"""Returns the configuration value for 'max_new_log_detection_time'."""
return self.__get_config().get_float("max_new_log_detection_time")
@property
def failure_request_spacing_adjustment(self):
"""Returns the configuration value for 'failure_request_spacing_adjustment'."""
return self.__get_config().get_float("failure_request_spacing_adjustment")
@property
def request_too_large_adjustment(self):
"""Returns the configuration value for 'request_too_large_adjustment'."""
return self.__get_config().get_float("request_too_large_adjustment")
@property
def request_deadline(self):
"""Returns the configuration value for 'request_deadline'."""
return self.__get_config().get_float("request_deadline")
@property
def debug_level(self):
"""Returns the configuration value for 'debug_level'."""
return self.__get_config().get_int("debug_level")
@property
def stdout_severity(self):
"""Returns the configuration value for 'stdout_severity'.
Only used when running in no-fork mode.
"""
return self.__get_config().get_string("stdout_severity").upper()
@property
def ca_cert_path(self):
"""Returns the configuration value for 'ca_cert_path'."""
return self.__get_config().get_string("ca_cert_path")
@property
def use_new_ingestion(self):
"""Returns the configuration value for 'use_new_ingestion'."""
return self.__get_config().get_bool("use_new_ingestion")
@property
def new_ingestion_bootstrap_address(self):
"""Returns the configuration value for 'bootstrap_address'."""
return self.__get_config().get_string("new_ingestion_bootstrap_address")
@property
def new_ingestion_use_tls(self):
"""Returns the configuration value for 'bootstrap_address'."""
return self.__get_config().get_bool("new_ingestion_use_tls")
@property
def compression_type(self):
"""Returns the configuration value for 'compression_type'."""
return self.__get_config().get_string("compression_type", none_if_missing=True)
@property
def compression_level(self):
"""Returns the configuration value for 'compression_level'."""
return self.__get_config().get_int("compression_level", default_value=9)
@property
def use_requests_lib(self):
"""Returns the configuration value for 'use_requests_lib'."""
return self.__get_config().get_bool("use_requests_lib")
@property
def use_tlslite(self):
"""Returns the configuration value for 'use_tlslite'."""
return self.__get_config().get_bool("use_tlslite")
@property
def network_proxies(self):
"""Returns the proxy map created by the 'https_proxy' and 'http_proxy' configuration variables, or
None if neither of those is set.
"""
https_proxy = self.__get_config().get_string(
"https_proxy", none_if_missing=True
)
http_proxy = self.__get_config().get_string("http_proxy", none_if_missing=True)
if https_proxy is None and http_proxy is None:
return None
result = {}
if https_proxy is not None:
result["https"] = https_proxy
if http_proxy is not None:
result["http"] = http_proxy
return result
@property
def global_monitor_sample_interval(self):
"""Returns the configuration value for 'global_monitor_sample_interval'."""
return self.__get_config().get_float("global_monitor_sample_interval")
@property
def global_monitor_sample_interval_enable_jitter(self):
"""Returns the configuration value for 'global_monitor_sample_interval_enable_jitter'."""
return self.__get_config().get_bool(
"global_monitor_sample_interval_enable_jitter"
)
@property
def full_checkpoint_interval(self):
"""Returns the configuration value for 'full_checkpoint_interval_in_seconds'."""
return self.__get_config().get_int("full_checkpoint_interval_in_seconds")
@property
def minimum_scan_interval(self):
"""Returns the configuration value for 'minimum_scan_interval'."""
return self.__get_config().get_int(
"minimum_scan_interval", none_if_missing=True
)
@property
def close_old_files_duration_in_seconds(self):
"""Returns the configuration value for 'close_old_files_duration_in_seconds'."""
return self.__get_config().get_int("close_old_files_duration_in_seconds")
@property
def max_line_size(self):
"""Returns the configuration value for 'max_line_size'."""
return self.__get_config().get_int("max_line_size")
@property
def line_completion_wait_time(self):
"""Returns the configuration value for 'line_completion_wait_time'."""
return self.__get_config().get_float("line_completion_wait_time")
@property
def internal_parse_max_line_size(self):
"""Returns the configuration value for 'internal_parse_max_line_size'."""
return self.__get_config().get_int("internal_parse_max_line_size")
@property
def max_log_offset_size(self):
"""Returns the configuration value for 'max_log_offset_size'."""
return self.__get_config().get_int("max_log_offset_size")
@property
def max_existing_log_offset_size(self):
"""Returns the configuration value for 'max_existing_log_offset_size'."""
return self.__get_config().get_int("max_existing_log_offset_size")
@property
def max_sequence_number(self):
"""Returns the maximum sequence number"""
return self.__get_config().get_int("max_sequence_number")
@property
def read_page_size(self):
"""Returns the configuration value for 'read_page_size'."""
return self.__get_config().get_int("read_page_size")
@property
def log_deletion_delay(self):
"""Returns the configuration value for 'log_deletion_delay'."""
return self.__get_config().get_float("log_deletion_delay")
@property
def log_rotation_max_bytes(self):
"""Returns the configuration value for 'log_rotation_max_bytes'."""
return self.__get_config().get_int("log_rotation_max_bytes")
@property
def log_rotation_backup_count(self):
"""Returns the configuration value for 'log_rotation_backup_count'."""
return self.__get_config().get_int("log_rotation_backup_count")
@property
def copy_staleness_threshold(self):
"""Returns the configuration value for 'copy_staleness_threshold'."""
return self.__get_config().get_float("copy_staleness_threshold")
@property
def debug_init(self):
"""Returns the configuration value for 'debug_init'."""
return self.__get_config().get_bool("debug_init")
@property
def pidfile_advanced_reuse_guard(self):
"""Returns the configuration value for 'pidfile_advanced_reuse_guard'."""
return self.__get_config().get_bool("pidfile_advanced_reuse_guard")
@property
def verify_server_certificate(self):
"""Returns the configuration value for 'verify_server_certificate'."""
return self.__get_config().get_bool("verify_server_certificate")
@property
def pipeline_threshold(self):
"""Returns the percentage an add events request must be of the maximum allowed request size to
trigger pipelining the next add events request.
"""
return self.__get_config().get_float("pipeline_threshold")
@property
def strip_domain_from_default_server_host(self):
"""Returns whether or not we should remove the domain name from the default server host that is used to
identify the source of the logs from this agent. For example, if the hostname is `foo.scalyr.com`, setting
this field to `true` will result in `foo` being used as the reported `serverHost` name.
This only applies if you do not set an explicit `serverHost` attribute in the server attributes.
"""
return self.__get_config().get_bool("strip_domain_from_default_server_host")
@property
def healthy_max_time_since_last_copy_attempt(self):
"""Returns the max amount of time since the last copy attempt to consider the agent 'healthy' for
the purpose of a health check using `status -v` or `-H`. This copy attempt need not be successful, since this is
just to check that the agent is healthy and should not reflect server side errors.
"""
return self.__get_config().get_float("healthy_max_time_since_last_copy_attempt")
# Windows specific options below
@property
def win32_max_open_fds(self):
"""
Returns value of the win32_max_open_fds config option which is Windows specific.
"""
return self.__get_config().get_int("win32_max_open_fds")
@property
def worker_configs(self):
return self.__worker_configs
@property
def sanitized_worker_configs(self):
"""
Special version of "worker_configs" attribute which removes / masks actual API tokens
in the returned output.
"""
worker_configs = copy.deepcopy(self.__worker_configs)
result = []
for worker_config in worker_configs:
# TODO: Should we still log last 3-4 characters of the key to make troubleshooting
# easier?
worker_config["api_key"] = MASKED_CONFIG_ITEM_VALUE
result.append(dict(worker_config))
return result
def get_number_of_configured_sessions_and_api_keys(self):
# type: () -> Tuple[str, int, int]
"""
Return total number of configured sessions from all workers and a total number of unique API keys those
workers are configured with.
It returns a tuple of (worker_type, sessions_count, unique API keys count). Value for
worker_type is "threaded" and "multiprocess."
If multiple sessions / workers functionality is not enabled (*, 1, 1) is returned.
"""
sessions_count = 0
api_keys_set = set([])
for worker_config in self.__worker_configs:
api_keys_set.add(worker_config["api_key"])
sessions_count += worker_config["sessions"]
api_keys_count = len(api_keys_set)
del api_keys_set
if self.use_multiprocess_workers:
worker_type = "multiprocess"
else:
worker_type = "threaded"
return worker_type, sessions_count, api_keys_count
@property
def use_multiprocess_workers(self):
"""
Return whether or not copying manager workers are in the multiprocessing mode.
"""
return self.__get_config().get_bool("use_multiprocess_workers")
@property
def default_sessions_per_worker(self):
"""
The default number of sessions which should be created for each worker if no value is explicitly set
"""
return self.__get_config().get_int("default_sessions_per_worker")
@property
def default_worker_session_status_message_interval(self):
return self.__get_config().get_float(
"default_worker_session_status_message_interval"
)
@property
def enable_worker_session_process_metrics_gather(self):
"""
If it True and multi-process workers are used, then the instance of the linux process monitor
is created for each worker session process.
"""
return self.__get_config().get_bool("enable_worker_process_metrics_gather")
@property
def enable_copy_truncate_log_rotation_support(self):
"""
Return whether copy truncate log rotation support is enabled.
"""
return self.__get_config().get_bool("enable_copy_truncate_log_rotation_support")
def equivalent(self, other, exclude_debug_level=False):
"""Returns true if other contains the same configuration information as this object.
This is different than an '_eq_' method because this comparison ignores some of the fields
such as what times the files were read at. Also, it compares the final results of the configuration,
after defaults have been applied.
@param exclude_debug_level: If True, will also ignore the values for 'debug_level' when doing comparison.
"""
if self.__last_error != other.__last_error:
return False
original_debug_level = None
try:
# If we are ignoring debug level, then we do a little hack here where we just put the value for
# this config into other's config.. and then just put the original value back after we've done the
# comparison.
if exclude_debug_level:
original_debug_level = other.__config.get("debug_level")
other.__config.put("debug_level", self.__config.get("debug_level"))
if self.__config != other.__config:
return False
return True
finally:
if original_debug_level is not None:
other.__config.put("debug_level", original_debug_level)
@staticmethod
def get_extra_config_dir(extra_config_dir):
"""
Returns the value for the additional config directory - either from the value passed
in, or from the environment variable `SCALYR_EXTRA_CONFIG_DIR`.
@param extra_config_dir: the additinal configuration directory. If this value is
None, then the environment variable `SCALYR_EXTRA_CONFIG_DIR` is read for the result
"""
result = extra_config_dir
if extra_config_dir is None:
result = compat.os_getenv_unicode("SCALYR_EXTRA_CONFIG_DIR")
return result
@staticmethod
def default_ca_cert_path():
"""Returns the default configuration file path for the agent."""
# TODO: Support more platforms.
return Configuration.__resolve_to_install_location("certs", "ca_certs.crt")
@property
def intermediate_certs_path(self):
"""Returns the intermediate certs path."""
return Configuration.__resolve_to_install_location(
"certs", "intermediate_certs.pem"
)
@staticmethod
def __resolve_to_install_location(*paths):
"""Returns the absolute path created by joining the specified intermediate paths to
the install location for this package.
@param paths: The file components of the desired path. There can be multiple, starting with the outer directory
first and finishing with the last file.
"""
result = get_install_root()
for path in paths:
result = os.path.join(result, path)
return result
def __get_parent_directory(self, file_path):
"""Returns the directory containing the specified file.
@param file_path: The absolute file path.
@return: The absolute path for the parent directory."""
return os.path.dirname(file_path)
def __resolve_absolute_path(self, file_path, working_directory):
"""Returns the full path for the specified file.
If the specified file path is relative, then working_directory is used to resolve the relative path.
This function does not do any existence checks on either file_path or working_directory.
@param file_path: The path of the file.
@param working_directory: The directory to use to resolve relative file paths.
@return: The absolute path for the specified file.
"""
if os.path.isabs(file_path):
return file_path
return os.path.join(working_directory, file_path)
def __list_files(self, directory_path):
"""Returns a list of the files ending in .json for the specified directory.
This only returns files in the directory. Also, if the directory does not exist
or cannot be read, an empty list is returned.
@param directory_path: The path of the directory.
@return: If the directory exists and can be read, the list of files ending in .json (not directories).
"""
result = []
if directory_path is None:
return result
if not os.path.isdir(directory_path):
return result
if not os.access(directory_path, os.R_OK):
return result
for f in sorted(os.listdir(directory_path)):
if f.endswith(".json"):
full_path = os.path.join(directory_path, f)
if os.path.isfile(full_path):
result.append(full_path)
return result
def __add_elements_from_array(
self, field, source_json, destination_json, deprecated_names=None
):
"""Appends any elements in the JsonArray in source_json to destination_json.
@param field: The name of the field containing the JsonArray.
@param source_json: The JsonObject containing the JsonArray from which to retrieve elements.
@param destination_json: The JsonObject to which the elements should be added (in the JsonArray named field.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
destination_array = destination_json.get_json_array(field, none_if_missing=True)
if destination_array is None and deprecated_names is not None:
for name in deprecated_names:
destination_array = destination_json.get_json_array(
name, none_if_missing=True
)
for element in source_json.get_json_array(field):
destination_array.add(element)
def __set_api_key(self, config, api_key):
"""
Sets the api_key of the config, and throws errors if there are any problems
"""
if api_key:
config.put("api_key", api_key)
if "api_key" not in config:
raise BadConfiguration(
'The configuration file is missing the required field "api_key" that '
"sets the authentication key to use when writing logs to Scalyr. Please update "
"the config file with a Write Logs key from https://www.scalyr.com/keys",
"api_key",
"missingApiKey",
)
if config.get_string("api_key") == "":
raise BadConfiguration(
"The configuration file contains an empty string for the required field "
'"api_key" that sets the authentication key to use when writing logs to Scalyr. '
"Please update the config file with a Write Logs key from https://www.scalyr.com/keys",
"api_key",
"emptyApiKey",
)
def __check_field(
self,
field,
config,
file_path,
previous_value=None,
previous_config_file=None,
error_code=None,
):
"""
Checks to see if the config contains a value for `field` , and if so verifies that it is a valid string.
@param field: The name of the field to check.
@param config: The contents of the config.
@param file_path: The file path to the config.
@param previous_value: If this field has been already defined in another config, the value it was given.
@param previous_config_file: If not None, the path to a config file that has already set this field. If this
is not None and this config does define the field, a `BadConfiguration` exception is raised.
@param error_code: The error code to return if it is detected the field has been set in multiple config files.
@return the field's value and file_path if the field is found, else return None and None
"""
description = 'configuration file "%s"' % file_path
if field in config:
self.__verify_required_string(config, field, description)
result_key = config.get_string(field)
result_file = file_path
if previous_config_file is not None:
raise BadConfiguration(
'The configuration file "%s" contains an "%s" value, but that field has already been set in '
'"%s". Please ensure that the "%s" value is set only once'
% (file_path, field, previous_config_file, field),
field,
error_code,
)
return result_key, result_file
return previous_value, previous_config_file
def __verify_main_config(self, config, file_path):
self.__verify_main_config_and_apply_defaults(
config, file_path, apply_defaults=False
)
def __verify_main_config_and_apply_defaults(
self, config, file_path, apply_defaults=True
):
"""Verifies the contents of the configuration object and updates missing fields with defaults.
This will verify and possibly update all the fields in the configuration file except for
the 'logs' and 'monitors' json arrays. If any of the fields do not meet their type requirement,
an exception will be raised. If any of the fields are not present, then config will be updated with
the appropriate default value.
@param config: The main JsonObject configuration object.
@param file_path: The file that was read to retrieve the config object. This is used in error reporting.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
"""
description = 'configuration file "%s"' % file_path
self.__verify_or_set_optional_string(
config, "api_key", "", description, apply_defaults, env_aware=True
)
self.__verify_or_set_optional_bool(
config, "allow_http", False, description, apply_defaults, env_aware=True
)
self.__verify_or_set_optional_bool(
config,
"check_remote_if_no_tty",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"compression_type",
"deflate",
description,
apply_defaults,
env_aware=True,
valid_values=scalyr_util.SUPPORTED_COMPRESSION_ALGORITHMS,
)
self.__verify_compression_type(self.compression_type)
# NOTE: If not explicitly specified by the user, we use compression algorithm specific
# default value
default_compression_level = scalyr_util.COMPRESSION_TYPE_TO_DEFAULT_LEVEL[
self.compression_type
]
self.__verify_or_set_optional_int(
config,
"compression_level",
default_compression_level,
description,
apply_defaults,
env_aware=True,
)
self.__verify_compression_level(self.compression_level)
self.__verify_or_set_optional_attributes(
config,
"server_attributes",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"agent_log_path",
self.__default_paths.agent_log_path,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"agent_data_path",
self.__default_paths.agent_data_path,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"additional_monitor_module_paths",
"",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"config_directory",
"agent.d",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"json_library",
"auto",
"JSON serialization and deserializarion library to use. Valid options are auto, json, ujson and orjson",
apply_defaults,
env_aware=True,
valid_values=["auto", "json", "ujson", "orjson"],
)
self.__verify_or_set_optional_bool(
config,
"implicit_agent_log_collection",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"implicit_metric_monitor",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"implicit_agent_process_metrics_monitor",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"use_unsafe_debugging",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"copying_thread_profile_interval",
0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"copying_thread_profile_output_path",
"/tmp/copying_thread_profiles_",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"global_monitor_sample_interval",
30.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"global_monitor_sample_interval_enable_jitter",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"close_old_files_duration_in_seconds",
60 * 60 * 1,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"full_checkpoint_interval_in_seconds",
60,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"max_send_rate_enforcement",
"unlimited",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"disable_max_send_rate_enforcement_overrides",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"max_allowed_request_size",
1 * 1024 * 1024,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"min_allowed_request_size",
100 * 1024,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"min_request_spacing_interval",
1.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"max_request_spacing_interval",
5.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"max_error_request_spacing_interval",
30.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"minimum_scan_interval",
None,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"low_water_bytes_sent",
20 * 1024,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"low_water_request_spacing_adjustment",
1.5,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"high_water_bytes_sent",
100 * 1024,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"high_water_request_spacing_adjustment",
0.6,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"failure_request_spacing_adjustment",
1.5,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"request_too_large_adjustment",
0.5,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"max_new_log_detection_time",
60.0,
description,
apply_defaults,
env_aware=True,
)
# These parameters are used in log_processing.py to govern how logs are copied.
# The maximum allowed size for a line when reading from a log file.
# We do not strictly enforce this -- some lines returned by LogFileIterator may be
# longer than this due to some edge cases.
self.__verify_or_set_optional_int(
config, "max_line_size", 49900, description, apply_defaults, env_aware=True
)
# The number of seconds we are willing to wait when encountering a log line at the end of a log file that does
# not currently end in a new line (referred to as a partial line). It could be that the full line just hasn't
# made it all the way to disk yet. After this time though, we will just return the bytes as a line
self.__verify_or_set_optional_float(
config,
"line_completion_wait_time",
5,
description,
apply_defaults,
env_aware=True,
)
# The maximum negative offset relative to the end of a previously unseen log the log file
# iterator is allowed to become. If bytes are not being read quickly enough, then
# the iterator will automatically advance so that it is no more than this length
# to the end of the file. This is essentially the maximum bytes a new log file
# is allowed to be caught up when used in copying logs to Scalyr.
self.__verify_or_set_optional_int(
config,
"max_log_offset_size",
5 * 1024 * 1024,
description,
apply_defaults,
env_aware=True,
)
# The maximum negative offset relative to the end of an existing log the log file
# iterator is allowed to become. If bytes are not being read quickly enough, then
# the iterator will automatically advance so that it is no more than this length
# to the end of the file. This is essentially the maximum bytes an existing log file
# is allowed to be caught up when used in copying logs to Scalyr.
self.__verify_or_set_optional_int(
config,
"max_existing_log_offset_size",
100 * 1024 * 1024,
description,
apply_defaults,
env_aware=True,
)
# The maximum sequence number for a given sequence
# The sequence number is typically the total number of bytes read from a given file
# (across restarts and log rotations), and it resets to zero (and begins a new sequence)
# for each file once the current sequence_number exceeds this value
# defaults to 1 TB
self.__verify_or_set_optional_int(
config,
"max_sequence_number",
1024 ** 4,
description,
apply_defaults,
env_aware=True,
)
# The number of bytes to read from a file at a time into the buffer. This must
# always be greater than the MAX_LINE_SIZE
self.__verify_or_set_optional_int(
config,
"read_page_size",
64 * 1024,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"internal_parse_max_line_size",
config.get_int("read_page_size", 64 * 1024),
description,
apply_defaults,
env_aware=True,
)
# The minimum time we wait for a log file to reappear on a file system after it has been removed before
# we consider it deleted.
self.__verify_or_set_optional_float(
config,
"log_deletion_delay",
10 * 60,
description,
apply_defaults,
env_aware=True,
)
# How many log rotations to do
self.__verify_or_set_optional_int(
config,
"log_rotation_backup_count",
2,
description,
apply_defaults,
env_aware=True,
)
# The size of each log rotation file
self.__verify_or_set_optional_int(
config,
"log_rotation_max_bytes",
20 * 1024 * 1024,
description,
apply_defaults,
env_aware=True,
)
# The percentage of the maximum message size a message (max_allowed_request_size) has to be to trigger
# pipelining the next add events request. This intentionally set to 110% to prevent it from being used unless
# explicitly requested.
self.__verify_or_set_optional_float(
config,
"pipeline_threshold",
1.1,
description,
apply_defaults,
env_aware=True,
)
# If we have noticed that new bytes have appeared in a file but we do not read them before this threshold
# is exceeded, then we consider those bytes to be stale and just skip to reading from the end to get the
# freshest bytes.
self.__verify_or_set_optional_float(
config,
"copy_staleness_threshold",
15 * 60,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config, "debug_init", False, description, apply_defaults, env_aware=True
)
self.__verify_or_set_optional_bool(
config,
"pidfile_advanced_reuse_guard",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"strip_domain_from_default_server_host",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"healthy_max_time_since_last_copy_attempt",
60.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"win32_max_open_fds",
# We default it to 512 which is also the default value for Python processes on Windows.
# Max is 2048.
512,
description,
apply_defaults,
env_aware=True,
min_value=512,
max_value=2048,
)
self.__verify_or_set_optional_int(
config, "debug_level", 0, description, apply_defaults, env_aware=True
)
debug_level = config.get_int("debug_level", apply_defaults)
if debug_level < 0 or debug_level > 5:
raise BadConfiguration(
"The debug level must be between 0 and 5 inclusive",
"debug_level",
"badDebugLevel",
)
self.__verify_or_set_optional_string(
config,
"stdout_severity",
"NOTSET",
description,
apply_defaults,
env_aware=True,
)
stdout_severity = config.get_string("stdout_severity", default_value="NOTSET")
if not hasattr(logging, stdout_severity.upper()):
raise BadConfiguration(
"The stdout severity must be a valid logging level name",
"stdout_severity",
"badStdoutSeverity",
)
self.__verify_or_set_optional_float(
config,
"request_deadline",
60.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"ca_cert_path",
Configuration.default_ca_cert_path(),
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"new_ca_cert_path",
Configuration.default_ca_cert_path(),
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"use_new_ingestion",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"new_ingestion_bootstrap_address",
"127.0.0.1:4772",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"new_ingestion_use_tls",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"use_requests_lib",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config, "use_tlslite", False, description, apply_defaults, env_aware=True
)
self.__verify_or_set_optional_bool(
config,
"verify_server_certificate",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config, "http_proxy", None, description, apply_defaults, env_aware=True
)
self.__verify_or_set_optional_string(
config, "https_proxy", None, description, apply_defaults, env_aware=True
)
self.__verify_or_set_optional_array_of_strings(
config,
"k8s_ignore_namespaces",
Configuration.DEFAULT_K8S_IGNORE_NAMESPACES,
description,
apply_defaults,
separators=[None, ","],
env_aware=True,
)
self.__verify_or_set_optional_array_of_strings(
config,
"k8s_include_namespaces",
Configuration.DEFAULT_K8S_INCLUDE_NAMESPACES,
description,
apply_defaults,
separators=[None, ","],
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"k8s_api_url",
"https://kubernetes.default",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"k8s_verify_api_queries",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"k8s_verify_kubelet_queries",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"k8s_kubelet_ca_cert",
"/run/secrets/kubernetes.io/serviceaccount/ca.crt",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"k8s_cache_query_timeout_secs",
20,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"k8s_cache_expiry_secs",
30,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"k8s_cache_expiry_fuzz_secs",
0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"k8s_cache_start_fuzz_secs",
0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"k8s_cache_purge_secs",
300,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"k8s_service_account_cert",
"/run/secrets/kubernetes.io/serviceaccount/ca.crt",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"k8s_service_account_token",
"/var/run/secrets/kubernetes.io/serviceaccount/token",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"k8s_service_account_namespace",
"/var/run/secrets/kubernetes.io/serviceaccount/namespace",
description,
apply_defaults,
env_aware=True,
)
# Whether to log api responses to agent_debug.log
self.__verify_or_set_optional_bool(
config,
"k8s_log_api_responses",
False,
description,
apply_defaults,
env_aware=True,
)
# If set to True, do not log successes (response code 2xx)
self.__verify_or_set_optional_bool(
config,
"k8s_log_api_exclude_200s",
False,
description,
apply_defaults,
env_aware=True,
)
# Minimum response length of api responses to be logged. Responses smaller than this limit are not logged.
self.__verify_or_set_optional_int(
config,
"k8s_log_api_min_response_len",
0,
description,
apply_defaults,
env_aware=True,
)
# Minimum latency of responses to be logged. Responses faster than this limit are not logged.
self.__verify_or_set_optional_float(
config,
"k8s_log_api_min_latency",
0.0,
description,
apply_defaults,
env_aware=True,
)
# If positive, api calls with the same path will be rate-limited to a message every interval seconds
self.__verify_or_set_optional_int(
config,
"k8s_log_api_ratelimit_interval",
0,
description,
apply_defaults,
env_aware=True,
)
# TODO-163 : make other settings more aggressive
# Optional (defaults to 3). The number of times the warmer will retry a query to warm a pod before giving up and
# classifying it as a Temporary Error
self.__verify_or_set_optional_int(
config,
"k8s_controlled_warmer_max_query_retries",
3,
description,
apply_defaults,
env_aware=True,
)
# Optional (defaults to 5). The maximum number of Temporary Errors that may occur when warming a pod's entry,
# before the warmer blacklists it.
self.__verify_or_set_optional_int(
config,
"k8s_controlled_warmer_max_attempts",
5,
description,
apply_defaults,
env_aware=True,
)
# Optional (defaults to 300). When a pod is blacklisted, how many secs it must wait until it is
# tried again for warming.
self.__verify_or_set_optional_int(
config,
"k8s_controlled_warmer_blacklist_time",
300,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"k8s_events_disable",
False,
description,
apply_defaults,
env_aware=True,
)
# Agent-wide k8s rate limiter settings
self.__verify_or_set_optional_string(
config,
"k8s_ratelimit_cluster_num_agents",
1,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"k8s_ratelimit_cluster_rps_init",
1000.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"k8s_ratelimit_cluster_rps_min",
1.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"k8s_ratelimit_cluster_rps_max",
1e9,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"k8s_ratelimit_consecutive_increase_threshold",
5,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"k8s_ratelimit_strategy",
BlockingRateLimiter.STRATEGY_MULTIPLY,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"k8s_ratelimit_increase_factor",
2.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_float(
config,
"k8s_ratelimit_backoff_factor",
0.5,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"k8s_ratelimit_max_concurrency",
1,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"disable_send_requests",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"enforce_monotonic_timestamps",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"include_raw_timestamp_field",
True,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"enable_profiling",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"max_profile_interval_minutes",
60,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"profile_duration_minutes",
2,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"profile_clock",
"random",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"profile_log_name",
"agent.callgrind",
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_string(
config,
"memory_profile_log_name",
"agent.meminfo",
description,
apply_defaults,
env_aware=True,
)
# AGENT-263: controls sending in the new format or not as a safety in case it is broken somewhere in the chain
# TODO: Remove this in a future release once we are more certain that it works
self.__verify_or_set_optional_bool(
config,
"disable_logfile_addevents_format",
False,
description,
apply_defaults,
env_aware=True,
)
# Debug leak flags
self.__verify_or_set_optional_bool(
config, "disable_leak_monitor_threads", False, description, apply_defaults
)
self.__verify_or_set_optional_bool(
config, "disable_leak_monitors_creation", False, description, apply_defaults
)
self.__verify_or_set_optional_bool(
config, "disable_leak_new_file_matches", False, description, apply_defaults
)
self.__verify_or_set_optional_bool(
config,
"disable_leak_scan_for_new_bytes",
False,
description,
apply_defaults,
)
self.__verify_or_set_optional_bool(
config,
"disable_leak_processing_new_bytes",
False,
description,
apply_defaults,
)
self.__verify_or_set_optional_bool(
config, "disable_leak_copying_thread", False, description, apply_defaults
)
self.__verify_or_set_optional_bool(
config, "disable_leak_overall_stats", False, description, apply_defaults
)
self.__verify_or_set_optional_bool(
config, "disable_leak_bandwidth_stats", False, description, apply_defaults
)
self.__verify_or_set_optional_bool(
config,
"disable_copy_manager_stats",
False,
description,
apply_defaults,
)
self.__verify_or_set_optional_bool(
config,
"disable_leak_update_debug_log_level",
False,
description,
apply_defaults,
)
self.__verify_or_set_optional_bool(
config, "enable_gc_stats", False, description, apply_defaults
)
self.__verify_or_set_optional_int(
config, "disable_leak_all_config_updates", None, description, apply_defaults
)
self.__verify_or_set_optional_int(
config, "disable_leak_verify_config", None, description, apply_defaults
)
self.__verify_or_set_optional_int(
config,
"disable_leak_config_equivalence_check",
None,
description,
apply_defaults,
)
self.__verify_or_set_optional_int(
config,
"disable_leak_verify_can_write_to_logs",
None,
description,
apply_defaults,
)
self.__verify_or_set_optional_int(
config, "disable_leak_config_reload", None, description, apply_defaults
)
self.__verify_or_set_optional_float(
config,
"config_change_check_interval",
30,
description,
apply_defaults,
env_aware=True,
)
# How often to capture and log overall agent stats (in seconds).
# NOTE: This values must be >= config_change_check_interval.
self.__verify_or_set_optional_float(
config,
"overall_stats_log_interval",
600,
description,
apply_defaults,
env_aware=True,
)
# How often to capture and log copying manager agent stats (in seconds).
# NOTE: This values must be >= config_change_check_interval.
self.__verify_or_set_optional_float(
config,
"copying_manager_stats_log_interval",
300,
description,
apply_defaults,
env_aware=True,
)
# How often to capture and log bandwidth related stats (in seconds).
# NOTE: This values must be >= config_change_check_interval.
self.__verify_or_set_optional_float(
config,
"bandwidth_stats_log_interval",
60,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"user_agent_refresh_interval",
60,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"garbage_collect_interval",
300,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_int(
config,
"disable_leak_verify_config_create_monitors_manager",
None,
description,
apply_defaults,
)
self.__verify_or_set_optional_int(
config,
"disable_leak_verify_config_create_copying_manager",
None,
description,
apply_defaults,
)
self.__verify_or_set_optional_bool(
config,
"disable_leak_verify_config_cache_config",
False,
description,
apply_defaults,
)
# if true, the copying manager creates each session of its workers in a separate process.
self.__verify_or_set_optional_bool(
config,
"use_multiprocess_workers",
False,
description,
apply_defaults,
env_aware=True,
deprecated_names=["use_multiprocess_copying_workers"],
)
# the default number of sessions per worker.
self.__verify_or_set_optional_int(
config,
"default_sessions_per_worker",
1,
description,
apply_defaults,
env_aware=True,
min_value=1,
deprecated_names=["default_workers_per_api_key"],
)
self.__verify_or_set_optional_float(
config,
"default_worker_session_status_message_interval",
600.0,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"enable_worker_process_metrics_gather",
False,
description,
apply_defaults,
env_aware=True,
)
self.__verify_or_set_optional_bool(
config,
"enable_copy_truncate_log_rotation_support",
True,
description,
apply_defaults,
)
# windows does not support copying manager backed with multiprocessing workers.
if config.get_bool("use_multiprocess_workers", none_if_missing=True):
if platform.system() == "Windows":
raise BadConfiguration(
"The 'use_multiprocess_workers' option is not supported on windows machines.",
"use_multiprocess_workers",
error_code="invalidValue",
)
elif sys.version_info < (2, 7):
raise BadConfiguration(
"The 'use_multiprocess_workers' option is supported only for Python version higher than 2.6.",
"use_multiprocess_workers",
error_code="invalidValue",
)
def __verify_compression_type(self, compression_type):
"""
Verify that the library for the specified compression type (algorithm) is available.
"""
library_name = scalyr_util.COMPRESSION_TYPE_TO_PYTHON_LIBRARY.get(
compression_type, "unknown"
)
try:
_, _ = scalyr_util.get_compress_and_decompress_func(compression_type)
except (ImportError, ValueError) as e:
msg = (
'Failed to set compression type to "%s". Make sure that the corresponding Python '
"library is available. You can install it using this command:\n\npip install %s\n\n "
"Original error: %s" % (compression_type, library_name, str(e))
)
raise BadConfiguration(msg, "compression_type", "invalidCompressionType")
if compression_type == "none":
self.__logger.warn(
"No compression will be used for outgoing requests. In most scenarios this will "
"result in larger data egress traffic which may incur additional charges on your "
"side (depending on your infrastructure provider, location, pricing model, etc.).",
limit_once_per_x_secs=86400,
limit_key="compression_type_none",
)
def __verify_compression_level(self, compression_level):
"""
Verify that the provided compression level is valid for the configured compression type.
If it's not, we use a default value for that compression algorithm. Keep in mind that this
behavior is there for backward compatibility reasons, otherwise it would be better to just
throw in such scenario
"""
compression_type = self.compression_type
valid_level_min, valid_level_max = scalyr_util.COMPRESSION_TYPE_TO_VALID_LEVELS[
compression_type
]
if compression_level < valid_level_min or compression_level > valid_level_max:
self.__config.put(
"compression_level",
scalyr_util.COMPRESSION_TYPE_TO_DEFAULT_LEVEL[compression_type],
)
def __get_config_val(self, config_object, param_name, param_type):
"""
Get parameter with a given type from the config object.
@param config_object: The JsonObject config containing the field as a key
@param param_name: Parameter name
@param param_type: Parameter type
:return:
"""
if param_type == int:
config_val = config_object.get_int(param_name, none_if_missing=True)
elif param_type == bool:
config_val = config_object.get_bool(param_name, none_if_missing=True)
elif param_type == float:
config_val = config_object.get_float(param_name, none_if_missing=True)
elif param_type == six.text_type:
config_val = config_object.get_string(param_name, none_if_missing=True)
elif param_type == JsonObject:
config_val = config_object.get_json_object(param_name, none_if_missing=True)
elif param_type == JsonArray:
config_val = config_object.get_json_array(param_name, none_if_missing=True)
elif param_type in (ArrayOfStrings, SpaceAndCommaSeparatedArrayOfStrings):
# ArrayOfStrings are extracted from config file as JsonArray
# (but extracted from the environment different from JsonArray)
config_val = config_object.get_json_array(param_name, none_if_missing=True)
else:
raise TypeError(
"Unsupported environment variable conversion type %s (param name = %s)"
% (param_type, param_name)
)
return config_val
def __get_config_or_environment_val(
self,
config_object,
param_name,
param_type,
env_aware,
custom_env_name,
deprecated_names=None,
):
"""Returns a type-converted config param value or if not found, a matching environment value.
If the environment value is returned, it is also written into the config_object.
Currently only handles the following types (str, int, bool, float, JsonObject, JsonArray).
Also validates that environment variables can be correctly converted into the primitive type.
Both upper-case and lower-case versions of the environment variable will be checked.
@param config_object: The JsonObject config containing the field as a key
@param param_name: Parameter name
@param param_type: Parameter type
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param custom_env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name. Both upper and lower case versions are tried.
Note: A non-empty value also automatically implies env_aware as True, regardless of it's value.
@param deprecated_names: List of synonym names for the *param_name* that were used in previous version but now
are deprecated. If the current *param_name* is not presented, then we also look for the deprecated names for
backward compatibility.
@return A python object representing the config param (or environment) value or None
@raises
JsonConversionException: if the config value or env value cannot be correctly converted.
TypeError: if the param_type is not supported.
"""
config_val = self.__get_config_val(config_object, param_name, param_type)
# the config param is not presented by its current name, look for a deprecated name.
if config_val is None and deprecated_names is not None:
for name in deprecated_names:
config_val = self.__get_config_val(config_object, name, param_type)
if config_val is not None:
config_object.put(param_name, config_val)
del config_object[name]
if self.__logger and self.__log_warnings:
self.__logger.warning(
"The configuration option {0} is deprecated, use {1} instead.".format(
name, param_name
),
limit_once_per_x_secs=86400,
limit_key="deprecatedConfigOption",
)
break
if not env_aware:
if not custom_env_name:
return config_val
self._environment_aware_map[param_name] = custom_env_name or (
"SCALYR_%s" % param_name.upper()
)
env_val = get_config_from_env(
param_name,
custom_env_name=custom_env_name,
convert_to=param_type,
logger=self.__logger,
param_val=config_val,
)
# the config param environment variable is not presented by its current name, look for a deprecated name.
if env_val is None and deprecated_names is not None:
for name in deprecated_names:
env_val = get_config_from_env(
name,
convert_to=param_type,
logger=self.__logger,
param_val=config_val,
)
if env_val is not None:
break
# Not set in environment
if env_val is None:
return config_val
# Config file value wins if set
if config_val is not None:
return config_val
config_object.update({param_name: env_val})
return env_val
def __verify_logs_and_monitors_configs_and_apply_defaults(self, config, file_path):
"""Verifies the contents of the 'logs' and 'monitors' fields and updates missing fields with defaults.
This will verify and possible update the json arrays holding the 'logs' and 'monitor's configuration.
If any of the fields in those arrays or their contained elements do not meet their type requirement,
an exception will be raised. If any of the fields are not present, then config will be updated with
the appropriate default values.
@param config: The main JsonObject configuration object.
@param file_path: The file that was read to retrieve the config object. This is used in error reporting.
"""
description = 'in configuration file "%s"' % file_path
self.__verify_or_set_optional_array(config, "logs", description)
self.__verify_or_set_optional_array(config, "journald_logs", description)
self.__verify_or_set_optional_array(config, "k8s_logs", description)
self.__verify_or_set_optional_array(config, "monitors", description)
self.__verify_or_set_optional_array(
config, "workers", description, deprecated_names=["api_keys"]
)
i = 0
for log_entry in config.get_json_array("logs"):
self.__verify_log_entry_and_set_defaults(
log_entry, config_file_path=file_path, entry_index=i
)
i += 1
i = 0
for log_entry in config.get_json_array("journald_logs"):
bad_config = False
try:
self.__verify_log_entry_with_key_and_set_defaults(
log_entry,
key="journald_unit",
config_file_path=file_path,
entry_index=i,
logs_field="journald_logs",
)
except BadConfiguration as e:
if self.__logger and self.__log_warnings:
self.__logger.warn(
"Failed to parse journald_logs.journald_unit config "
"option, falling back to journald_logs.journald_globs: %s"
% str(e)
)
bad_config = True
if bad_config:
self.__verify_log_entry_with_key_and_set_defaults(
log_entry,
key="journald_globs",
config_file_path=file_path,
entry_index=i,
key_type="object",
logs_field="journald_logs",
)
i += 1
i = 0
for log_entry in config.get_json_array("k8s_logs"):
self.__verify_k8s_log_entry_and_set_defaults(
log_entry,
config_file_path=file_path,
entry_index=i,
)
i += 1
i = 0
for monitor_entry in config.get_json_array("monitors"):
self.__verify_monitor_entry_and_set_defaults(
monitor_entry, file_path=file_path, entry_index=i
)
i += 1
def __verify_k8s_log_entry_and_set_defaults(
self,
log_entry,
description=None,
config_file_path=None,
entry_index=None,
):
"""Verifies that the configuration for the specified k8s log entry.
A "k8s_log" entry can have one of multiple keys defined `k8s_pod_glob`, `k8s_namespace_glob`,
or `k8s_container_glob` which is a string containing a glob pattern to match against.
By default each of these values is `*` which matches against everything. Users can
set these fields to limit the log configuration to specific pods, namespaces and containers.
Only the first matching config will be applied to any give log. Users should make sure to
place more specific matching rules before more general ones.
Also verify the rest of the log config meets the required log config criteria and sets any defaults.
Raises an exception if it does not.
@param log_entry: The JsonObject holding the configuration for a log.
@param description: A human-readable description of where the log entry came from to use in error messages. If
none is given, then both file_path and entry_index must be set.
@param config_file_path: The path for the file from where the configuration was read. Used to generate the
description if none was given.
@param entry_index: The index of the entry in the 'logs' json array. Used to generate the description if none
was given.
"""
self.__verify_or_set_optional_string(
log_entry, "k8s_pod_glob", "*", description
)
self.__verify_or_set_optional_string(
log_entry, "k8s_namespace_glob", "*", description
)
self.__verify_or_set_optional_string(
log_entry, "k8s_container_glob", "*", description
)
self.__verify_log_entry_with_key_and_set_defaults(
log_entry,
None,
description=description,
config_file_path=config_file_path,
entry_index=entry_index,
# k8s log config defaults are applied later when adding containers to the copying manager
# so don't set them here
apply_defaults=False,
logs_field="k8s_logs",
)
def __verify_log_entry_and_set_defaults(
self, log_entry, description=None, config_file_path=None, entry_index=None
):
"""Verifies that the configuration for the specified log has a key called 'path' and meets all
the required criteria and sets any defaults.
Raises an exception if it does not.
@param log_entry: The JsonObject holding the configuration for a log.
@param description: A human-readable description of where the log entry came from to use in error messages. If
none is given, then both file_path and entry_index must be set.
@param config_file_path: The path for the file from where the configuration was read. Used to generate the
description if none was given.
@param entry_index: The index of the entry in the 'logs' json array. Used to generate the description if none
was given.
"""
# Make sure the log_entry has a path and the path is absolute.
path = log_entry.get_string("path", none_if_missing=True)
if path and not os.path.isabs(path):
log_entry.put("path", os.path.join(self.agent_log_path, path))
self.__verify_log_entry_with_key_and_set_defaults(
log_entry,
"path",
description=description,
config_file_path=config_file_path,
entry_index=entry_index,
)
# set default worker if it is not specified.
self.__verify_or_set_optional_string(
log_entry,
"worker_id",
"default",
description,
)
def __verify_log_entry_with_key_and_set_defaults(
self,
log_entry,
key=None,
description=None,
config_file_path=None,
entry_index=None,
apply_defaults=True,
logs_field="logs",
key_type="string",
):
"""Verifies that the configuration for the specified log meets all the required criteria and sets any defaults.
Raises an exception if it does not.
@param log_entry: The JsonObject holding the configuration for a log.
@param key: A key that must exist in the log entry. The key is used to identify logs e.g. by path, container name etc
If `None` then no checking is done
@param description: A human-readable description of where the log entry came from to use in error messages. If
none is given, then both file_path and entry_index must be set.
@param config_file_path: The path for the file from where the configuration was read. Used to generate the
description if none was given.
@param entry_index: The index of the entry in the 'logs' json array. Used to generate the description if none
was given.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param logs_field: The name of the field used for log configs
@param key_type: The type of key - defaults to string, but can also be `object` if the value is supposed to
be a json object
"""
no_description_given = description is None
if no_description_given:
description = (
'the entry with index=%i in the "%s" array in configuration file "%s"'
% (entry_index, logs_field, config_file_path)
)
log = None
if key is not None:
if key_type == "object":
self.__verify_required_attributes(log_entry, key, description)
log = key
else:
# Verify it has a `key` entry that is a string.
self.__verify_required_string(log_entry, key, description)
log = log_entry.get_string(key)
if log is not None and no_description_given:
description = (
'the entry for "%s" in the "%s" array in configuration file "%s"'
% (log, logs_field, config_file_path)
)
self.__verify_or_set_optional_array_of_strings(
log_entry,
"exclude",
[],
description,
apply_defaults=apply_defaults,
)
# If a parser was specified, make sure it is a string.
if "parser" in log_entry:
self.__verify_or_set_optional_string(
log_entry,
"parser",
"ignored",
description,
apply_defaults=apply_defaults,
)
self.__verify_or_set_optional_attributes(log_entry, "attributes", description)
self.__verify_or_set_optional_array(log_entry, "lineGroupers", description)
i = 0
for element in log_entry.get_json_array("lineGroupers"):
element_description = (
'the entry with index=%i in the "lineGroupers" array in ' % i
)
element_description += description
self.__verify_required_string(element, "start", element_description)
self.__verify_contains_exactly_one_string_out_of(
element,
["continueThrough", "continuePast", "haltBefore", "haltWith"],
description,
)
i += 1
self.__verify_or_set_optional_bool(
log_entry,
"copy_from_start",
False,
description,
apply_defaults=apply_defaults,
)
self.__verify_or_set_optional_bool(
log_entry, "parse_lines_as_json", None, description, apply_defaults=False
)
self.__verify_or_set_optional_string(
log_entry,
"parse_format",
"raw",
description,
apply_defaults=apply_defaults,
)
self.__verify_or_set_optional_string(
log_entry,
"json_message_field",
"log",
description,
apply_defaults=apply_defaults,
)
self.__verify_or_set_optional_string(
log_entry,
"json_timestamp_field",
"time",
description,
apply_defaults=apply_defaults,
)
self.__verify_or_set_optional_bool(
log_entry,
"ignore_stale_files",
False,
description,
apply_defaults=apply_defaults,
)
self.__verify_or_set_optional_float(
log_entry,
"staleness_threshold_secs",
5 * 60,
description,
apply_defaults=apply_defaults,
)
self.__verify_or_set_optional_int(
log_entry,
"minimum_scan_interval",
None,
description,
apply_defaults=apply_defaults,
)
# Verify that if it has a sampling_rules array, then it is an array of json objects.
self.__verify_or_set_optional_array(log_entry, "sampling_rules", description)
i = 0
for element in log_entry.get_json_array("sampling_rules"):
element_description = (
'the entry with index=%i in the "sampling_rules" array in ' % i
)
element_description += description
self.__verify_required_regexp(
element, "match_expression", element_description
)
self.__verify_required_percentage(
element, "sampling_rate", element_description
)
i += 1
# Verify that if it has a redaction_rules array, then it is an array of json objects.
self.__verify_or_set_optional_array(log_entry, "redaction_rules", description)
i = 0
for element in log_entry.get_json_array("redaction_rules"):
element_description = (
'the entry with index=%i in the "redaction_rules" array in ' % i
)
element_description += description
self.__verify_required_regexp(
element, "match_expression", element_description
)
self.__verify_or_set_optional_string(
element, "replacement", "", element_description
)
i += 1
# We support the parser definition being at the top-level of the log config object, but we really need to
# put it in the attributes.
if "parser" in log_entry:
# noinspection PyTypeChecker
log_entry["attributes"]["parser"] = log_entry["parser"]
def __verify_monitor_entry_and_set_defaults(
self, monitor_entry, context_description=None, file_path=None, entry_index=None
):
"""Verifies that the config for the specified monitor meets all the required criteria and sets any defaults.
Raises an exception if it does not.
@param monitor_entry: The JsonObject holding the configuration for a monitor.
@param file_path: The path for the file from where the configuration was read. Used to report errors to user.
@param entry_index: The index of the entry in the 'monitors' json array. Used to report errors to user.
"""
# Verify that it has a module name
if context_description is None:
description = (
'the entry with index=%i in the "monitors" array in configuration file "%s"'
% (entry_index, file_path)
)
else:
description = context_description
self.__verify_required_string(monitor_entry, "module", description)
module_name = monitor_entry.get_string("module")
if context_description is None:
description = (
'the entry for module "%s" in the "monitors" array in configuration file "%s"'
% (module_name, file_path)
)
else:
description = context_description
# Verify that if it has a log_name field, it is a string.
self.__verify_or_set_optional_string(
monitor_entry, "log_path", module_name + ".log", description
)
def __verify_workers_entry_and_set_defaults(self, worker_entry, entry_index=None):
"""
Verify the copying manager workers entry. and set defaults.
"""
description = "the #%s entry of the 'workers' list."
# the 'id' field is required, raise an error if it is not specified.
self.__verify_required_string(worker_entry, "id", description)
# the 'api_key' field is required, raise an error if it is not specified,
# but we make an exception for the "default" worker.
# The worker entry with "default" id may not have a "api_key" field and it will be the same as main api_key.
worker_id = worker_entry.get("id")
if worker_id == "default":
api_key = worker_entry.get("api_key", none_if_missing=True)
if api_key is not None and api_key != self.api_key:
raise BadConfiguration(
"The API key of the default worker has to match the main API key of the configuration",
"workers",
"wrongDefaultWorker",
)
self.__verify_or_set_optional_string(
worker_entry, "api_key", self.api_key, description % entry_index
)
else:
# validate the worker id. It should consist only from this set of characters.
allowed_worker_id_characters_pattern = "a-zA-Z0-9_"
if re.search(
r"[^{0}]+".format(allowed_worker_id_characters_pattern), worker_id
):
raise BadConfiguration(
"The worker id '{0}' contains an invalid character. Please use only '{1}'".format(
worker_id, allowed_worker_id_characters_pattern
),
"workers",
"invalidWorkerId",
)
self.__verify_required_string(
worker_entry, "api_key", description % entry_index
)
sessions_number = self.__config.get_int("default_sessions_per_worker")
self.__verify_or_set_optional_int(
worker_entry,
"sessions",
sessions_number,
description,
min_value=1,
deprecated_names=["workers"],
)
def __merge_server_attributes(self, fragment_file_path, config_fragment, config):
"""Merges the contents of the server attribute read from a configuration fragment to the main config object.
@param fragment_file_path: The path of the file from which the fragment was read. Used for error messages.
@param config_fragment: The JsonObject in the fragment file containing the 'server_attributes' field.
@param config: The main config object also containing a server_attributes field. The contents of the one from
config_fragment will be merged into this one.
"""
self.__verify_or_set_optional_attributes(
config_fragment,
"server_attributes",
'the configuration fragment at "%s"' % fragment_file_path,
)
source = config_fragment["server_attributes"]
destination = config["server_attributes"]
for k in source:
destination[k] = source[k]
def __verify_required_string(self, config_object, field, config_description):
"""Verifies that config_object has the required field and it can be converted to a string.
Raises an exception otherwise.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
"""
try:
config_object.get_string(field)
except JsonConversionException:
raise BadConfiguration(
'The field "%s" is not a string. Error is in %s'
% (field, config_description),
field,
"notString",
)
except JsonMissingFieldException:
raise BadConfiguration(
'The required field "%s" is missing. Error is in %s'
% (field, config_description),
field,
"missingRequired",
)
def __verify_contains_exactly_one_string_out_of(
self, config_object, fields, config_description
):
"""Verifies that config_object has exactly one of the named fields and it can be converted to a string.
Raises an exception otherwise.
@param config_object: The JsonObject containing the configuration information.
@param fields: A list of field names to check in the config_object.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@return: The name of the found key, or None
"""
count = 0
result = None
for field in fields:
try:
value = config_object.get_string(field, none_if_missing=True)
if value is not None:
result = field
count += 1
except JsonConversionException:
raise BadConfiguration(
'The field "%s" is not a string. Error is in %s'
% (field, config_description),
field,
"notString",
)
if count == 0:
raise BadConfiguration(
'A required field is missing. Object must contain one of "%s". Error is in %s'
% (six.text_type(fields), config_description),
field,
"missingRequired",
)
elif count > 1:
raise BadConfiguration(
'A required field has too many options. Object must contain only one of "%s". Error is in %s'
% (six.text_type(fields), config_description),
field,
"missingRequired",
)
return result
def __verify_or_set_optional_string(
self,
config_object,
field,
default_value,
config_description,
apply_defaults=True,
env_aware=False,
env_name=None,
valid_values=None,
deprecated_names=None,
):
"""Verifies that the specified field in config_object is a string if present, otherwise sets default.
Raises an exception if the existing field cannot be converted to a string.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param default_value: The value to set in config_object for field if it currently has no value.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name.
@param valid_values: Optional list with valid values for this string.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
try:
value = self.__get_config_or_environment_val(
config_object,
field,
six.text_type,
env_aware,
env_name,
deprecated_names=deprecated_names,
)
if value is None:
if apply_defaults:
config_object.put(field, default_value)
return
except JsonConversionException:
raise BadConfiguration(
'The value for field "%s" is not a string. Error is in %s'
% (field, config_description),
field,
"notString",
)
if value is not None and valid_values and value not in valid_values:
raise BadConfiguration(
'Got invalid value "%s" for field "%s". Valid values are: %s'
% (value, field, ", ".join(valid_values)),
field,
"invalidValue",
)
def __verify_or_set_optional_int(
self,
config_object,
field,
default_value,
config_description,
apply_defaults=True,
env_aware=False,
env_name=None,
min_value=None,
max_value=None,
deprecated_names=None,
):
"""Verifies that the specified field in config_object can be converted to an int if present, otherwise
sets default.
Raises an exception if the existing field cannot be converted to an int.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param default_value: The value to set in config_object for field if it currently has no value.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name.
@param min_value: Optional minimum value for this configuration value.
@param max_value: Optional maximum value for this configuration value.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
try:
value = self.__get_config_or_environment_val(
config_object,
field,
int,
env_aware,
env_name,
deprecated_names=deprecated_names,
)
if value is None:
if apply_defaults:
config_object.put(field, default_value)
return
except JsonConversionException:
raise BadConfiguration(
'The value for field "%s" is not an int. Error is in %s'
% (field, config_description),
field,
"notInt",
)
if value is not None and min_value is not None and value < min_value:
raise BadConfiguration(
'Got invalid value "%s" for field "%s". Value must be greater than or equal to %s'
% (value, field, min_value),
field,
"invalidValue",
)
if value is not None and max_value is not None and value > max_value:
raise BadConfiguration(
'Got invalid value "%s" for field "%s". Value must be less than or equal to %s'
% (value, field, max_value),
field,
"invalidValue",
)
def __verify_or_set_optional_float(
self,
config_object,
field,
default_value,
config_description,
apply_defaults=True,
env_aware=False,
env_name=None,
deprecated_names=None,
):
"""Verifies that the specified field in config_object can be converted to a float if present, otherwise
sets default.
Raises an exception if the existing field cannot be converted to a float.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param default_value: The value to set in config_object for field if it currently has no value.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
try:
value = self.__get_config_or_environment_val(
config_object,
field,
float,
env_aware,
env_name,
deprecated_names=deprecated_names,
)
if value is None:
if apply_defaults:
config_object.put(field, default_value)
return
except JsonConversionException:
raise BadConfiguration(
'The value for field "%s" is not an float. Error is in %s'
% (field, config_description),
field,
"notFloat",
)
def __verify_or_set_optional_attributes(
self,
config_object,
field,
config_description,
apply_defaults=True,
env_aware=False,
env_name=None,
deprecated_names=None,
):
"""Verifies that the specified field in config_object is a json object if present, otherwise sets to empty
object.
Raises an exception if the existing field is not a json object or if any of its values cannot be converted
to a string.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
try:
json_object = self.__get_config_or_environment_val(
config_object,
field,
JsonObject,
env_aware,
env_name,
deprecated_names=deprecated_names,
)
if json_object is None:
if apply_defaults:
config_object.put(field, JsonObject())
return
for key in json_object.keys():
try:
json_object.get_string(key)
except JsonConversionException:
raise BadConfiguration(
'The value for field "%s" in the json object for "%s" is not a '
"string. Error is in %s" % (key, field, config_description),
field,
"notString",
)
except JsonConversionException:
raise BadConfiguration(
'The value for the field "%s" is not a json object. '
"Error is in %s" % (field, config_description),
field,
"notJsonObject",
)
def __verify_or_set_optional_bool(
self,
config_object,
field,
default_value,
config_description,
apply_defaults=True,
env_aware=False,
env_name=None,
deprecated_names=None,
):
"""Verifies that the specified field in config_object is a boolean if present, otherwise sets default.
Raises an exception if the existing field cannot be converted to a boolean.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param default_value: The value to set in config_object for field if it currently has no value.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
try:
value = self.__get_config_or_environment_val(
config_object,
field,
bool,
env_aware,
env_name,
deprecated_names=deprecated_names,
)
if value is None:
if apply_defaults:
config_object.put(field, default_value)
return
except JsonConversionException:
raise BadConfiguration(
'The value for the required field "%s" is not a boolean. '
"Error is in %s" % (field, config_description),
field,
"notBoolean",
)
def __verify_or_set_optional_array(
self,
config_object,
field,
config_description,
apply_defaults=True,
env_aware=False,
env_name=None,
deprecated_names=None,
):
"""Verifies that the specified field in config_object is an array of json objects if present, otherwise sets
to empty array.
Raises an exception if the existing field is not a json array or if any of its elements are not json objects.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
try:
json_array = self.__get_config_or_environment_val(
config_object,
field,
JsonArray,
env_aware,
env_name,
deprecated_names=deprecated_names,
)
if json_array is None:
if apply_defaults:
config_object.put(field, JsonArray())
return
index = 0
for x in json_array:
if not isinstance(x, JsonObject):
raise BadConfiguration(
"The element at index=%i is not a json object as required in the array "
'field "%s (%s, %s)". Error is in %s'
% (index, field, type(x), six.text_type(x), config_description),
field,
"notJsonObject",
)
index += 1
except JsonConversionException:
raise BadConfiguration(
'The value for the required field "%s" is not an array. '
"Error is in %s" % (field, config_description),
field,
"notJsonArray",
)
def __verify_or_set_optional_array_of_strings(
self,
config_object,
field,
default_value,
config_description,
apply_defaults=True,
separators=[","],
env_aware=False,
env_name=None,
deprecated_names=None,
):
"""Verifies that the specified field in config_object is an array of strings if present, otherwise sets
to empty array.
Raises an exception if the existing field is not a json array or if any of its elements are not strings/unicode.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param default_value: Default values (array of strings)
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
@param apply_defaults: If true, apply default values for any missing fields. If false do not set values
for any fields missing from the config.
@param separators: list of allowed separators (An entry of None represents "any whitespace")
@param env_aware: If True and not defined in config file, look for presence of environment variable.
@param env_name: If provided, will use this name to lookup the environment variable. Otherwise, use
scalyr_<field> as the environment variable name.
@param deprecated_names: List of synonym names for the *field* that were used in previous version but now
are deprecated. If the current *field* is not presented, then we also look for the deprecated names for
backward compatibility.
"""
# 2->TODO Python3 can not sort None values
separators.sort(key=lambda s: s if s is not None else "")
# For legacy reasons, must support space-separated array of strings
cls = ArrayOfStrings
if separators == [None, ","]:
cls = SpaceAndCommaSeparatedArrayOfStrings
try:
array_of_strings = self.__get_config_or_environment_val(
config_object,
field,
cls,
env_aware,
env_name,
deprecated_names=deprecated_names,
)
if array_of_strings is None:
if apply_defaults:
config_object.put(field, cls(values=default_value))
return
index = 0
for x in array_of_strings:
if not isinstance(x, six.string_types):
raise BadConfiguration(
"The element at index=%i is not a string or unicode object as required in the array "
'field "%s". Error is in %s'
% (index, field, config_description),
field,
"notStringOrUnicode",
)
index += 1
except JsonConversionException:
raise BadConfiguration(
'The value for the required field "%s" is not an array. '
"Error is in %s" % (field, config_description),
field,
"notJsonArray",
)
def __verify_required_attributes(
self,
config_object,
field,
config_description,
):
"""Verifies that the specified field in config_object is a json object if present, otherwise sets to empty
object.
Raises an exception if the existing field is not a json object or if any of its values cannot be converted
to a string.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
"""
try:
value = config_object.get_json_object(field, none_if_missing=True) or {}
for key in value.keys():
try:
value.get_string(key)
except JsonConversionException:
raise BadConfiguration(
'The value for field "%s" in the json object for "%s" is not a '
"string. Error is in %s" % (key, field, config_description),
field,
"notString",
)
except JsonConversionException:
raise BadConfiguration(
'The value for the field "%s" is not a json object. '
"Error is in %s" % (field, config_description),
field,
"notJsonObject",
)
def __verify_required_regexp(self, config_object, field, config_description):
"""Verifies that config_object has the specified field and it can be parsed as a regular expression, otherwise
raises an exception.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
"""
try:
value = config_object.get_string(field, none_if_missing=True)
if value is not None:
re.compile(value)
return
except Exception:
raise BadConfiguration(
'The value for required field "%s" has a value that cannot be parsed as '
"string regular expression (using python syntax). "
"Error is in %s" % (field, config_description),
field,
"notRegexp",
)
raise BadConfiguration(
'The required regular expression field "%s" is missing. Error is in %s'
% (field, config_description),
field,
"missingRequired",
)
def __verify_required_percentage(self, config_object, field, config_description):
"""Verifies that config_object has the specified field and it can be it is a number between 0 and 1, otherwise
raises an exception.
@param config_object: The JsonObject containing the configuration information.
@param field: The name of the field to check in config_object.
@param config_description: A description of where the configuration object was sourced from to be used in the
error reporting to the user.
"""
try:
value = config_object.get_float(field, none_if_missing=True)
if value is None:
raise BadConfiguration(
'The required percentage field "%s" is missing. Error is in %s'
% (field, config_description),
field,
"missingRequired",
)
elif value < 0 or value > 1:
raise BadConfiguration(
'The required percentage field "%s" has a value "%s" that is not a number '
"between 0 and 1 inclusive. Error is in %s"
% (field, value, config_description),
field,
"notPercentage",
)
except JsonConversionException:
raise BadConfiguration(
'The required field "%s" has a value that cannot be parsed as a number between 0 '
"and 1 inclusive. Error is in %s" % (field, config_description),
field,
"notNumber",
)
def __get_config(self):
if self.__last_error is not None:
raise BadConfiguration(self.__last_error, "fake", "fake")
return self.__config
def __perform_substitutions(self, source_config):
"""Rewrites the content of the source_config to reflect the values in the `import_vars` array.
@param source_config: The configuration to rewrite, represented as key/value pairs.
@type source_config: JsonObject
"""
substitutions = import_shell_variables(source_config=source_config)
if len(substitutions) > 0:
perform_object_substitution(
object_value=source_config, substitutions=substitutions
)
def __getstate__(self):
"""
Remove unpicklable fields from the configuration instance.
The configuration object need to be picklable because its instances may be passed
to the multi-process copying manager worker sessions.
"""
state = self.__dict__.copy()
state.pop("_Configuration__logger", None)
return state
"""
Utility functions related to shell variable handling and substition.
NOTE: Those functions are intentionally not defined inside "__perform_substitutions" to avoid memory
leaks.
"""
def import_shell_variables(source_config):
"""Creates a dict mapping variables listed in the `import_vars` field of `source_config` to their
values from the environment.
"""
result = dict()
if "import_vars" in source_config:
for entry in source_config.get_json_array("import_vars"):
# Allow for an entry of the form { var: "foo", default: "bar"}
if isinstance(entry, JsonObject):
var_name = entry["var"]
default_value = entry["default"]
else:
var_name = entry
default_value = ""
# 2->TODO in python2 os.environ returns 'str' type. Convert it to unicode.
var_value = os_environ_unicode.get(var_name)
if var_value:
result[var_name] = var_value
else:
result[var_name] = default_value
return result
def perform_generic_substitution(value, substitutions):
"""Takes a given JSON value and performs the appropriate substitution.
This method will return a non-None value if the value has to be replaced with the returned value.
Otherwise, this will attempt to perform in-place substitutions.
For str, unicode, it substitutes the variables and returns the result. For
container objects, it does the recursive substitution.
@param value: The JSON value
@type value: Any valid element of a JsonObject
@return: The value that should replace the original, if any. If no replacement is necessary, returns None
"""
result = None
value_type = type(value)
if value_type is six.text_type and "$" in value:
result = perform_str_substitution(value, substitutions=substitutions)
elif isinstance(value, JsonObject):
perform_object_substitution(value, substitutions=substitutions)
elif isinstance(value, JsonArray):
perform_array_substitution(value, substitutions=substitutions)
return result
def perform_object_substitution(object_value, substitutions):
"""Performs the in-place substitution for a JsonObject.
@param object_value: The object to perform substitutions on.
@type object_value: JsonObject
"""
# We collect the new values and apply them later to avoid messing up the iteration.
new_values = {}
for (key, value) in six.iteritems(object_value):
replace_value = perform_generic_substitution(value, substitutions=substitutions)
if replace_value is not None:
new_values[key] = replace_value
for (key, value) in six.iteritems(new_values):
object_value[key] = value
def perform_str_substitution(str_value, substitutions):
"""Performs substitutions on the given string.
@param str_value: The input string.
@type str_value: str or unicode
@return: The resulting value after substitution.
@rtype: str or unicode
"""
result = str_value
for (var_name, value) in six.iteritems(substitutions):
result = result.replace("$%s" % var_name, value)
return result
def perform_array_substitution(array_value, substitutions):
"""Perform substitutions on the JsonArray.
@param array_value: The array
@type array_value: JsonArray
"""
for i in range(len(array_value)):
replace_value = perform_generic_substitution(
array_value[i], substitutions=substitutions
)
if replace_value is not None:
array_value[i] = replace_value
| 38.309244
| 129
| 0.617535
|
4a0a7ffd0430ca7a9b6876665f1a5b83daf9db0d
| 81,479
|
py
|
Python
|
tencentcloud/dcdb/v20180411/models.py
|
zhaopufeng/tencentcloud-sdk-python
|
1f96db68a8aff9e4104600c7dc8ab69796e35e24
|
[
"Apache-2.0"
] | 1
|
2020-01-03T06:18:22.000Z
|
2020-01-03T06:18:22.000Z
|
tencentcloud/dcdb/v20180411/models.py
|
zhaopufeng/tencentcloud-sdk-python
|
1f96db68a8aff9e4104600c7dc8ab69796e35e24
|
[
"Apache-2.0"
] | null | null | null |
tencentcloud/dcdb/v20180411/models.py
|
zhaopufeng/tencentcloud-sdk-python
|
1f96db68a8aff9e4104600c7dc8ab69796e35e24
|
[
"Apache-2.0"
] | null | null | null |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
from tencentcloud.common.abstract_model import AbstractModel
class AddShardConfig(AbstractModel):
"""升级实例 -- 新增分片类型
"""
def __init__(self):
"""
:param ShardCount: 新增分片的数量
:type ShardCount: int
:param ShardMemory: 分片内存大小,单位 GB
:type ShardMemory: int
:param ShardStorage: 分片存储大小,单位 GB
:type ShardStorage: int
"""
self.ShardCount = None
self.ShardMemory = None
self.ShardStorage = None
def _deserialize(self, params):
self.ShardCount = params.get("ShardCount")
self.ShardMemory = params.get("ShardMemory")
self.ShardStorage = params.get("ShardStorage")
class CloneAccountRequest(AbstractModel):
"""CloneAccount请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例ID
:type InstanceId: str
:param SrcUser: 源用户账户名
:type SrcUser: str
:param SrcHost: 源用户HOST
:type SrcHost: str
:param DstUser: 目的用户账户名
:type DstUser: str
:param DstHost: 目的用户HOST
:type DstHost: str
:param DstDesc: 目的用户账户描述
:type DstDesc: str
"""
self.InstanceId = None
self.SrcUser = None
self.SrcHost = None
self.DstUser = None
self.DstHost = None
self.DstDesc = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.SrcUser = params.get("SrcUser")
self.SrcHost = params.get("SrcHost")
self.DstUser = params.get("DstUser")
self.DstHost = params.get("DstHost")
self.DstDesc = params.get("DstDesc")
class CloneAccountResponse(AbstractModel):
"""CloneAccount返回参数结构体
"""
def __init__(self):
"""
:param FlowId: 异步任务流程ID
:type FlowId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.FlowId = None
self.RequestId = None
def _deserialize(self, params):
self.FlowId = params.get("FlowId")
self.RequestId = params.get("RequestId")
class CloseDBExtranetAccessRequest(AbstractModel):
"""CloseDBExtranetAccess请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待关闭外网访问的实例ID。形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
"""
self.InstanceId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
class CloseDBExtranetAccessResponse(AbstractModel):
"""CloseDBExtranetAccess返回参数结构体
"""
def __init__(self):
"""
:param FlowId: 异步任务Id,可通过 DescribeFlow 查询任务状态。
:type FlowId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.FlowId = None
self.RequestId = None
def _deserialize(self, params):
self.FlowId = params.get("FlowId")
self.RequestId = params.get("RequestId")
class ConstraintRange(AbstractModel):
"""约束类型值的范围
"""
def __init__(self):
"""
:param Min: 约束类型为section时的最小值
:type Min: str
:param Max: 约束类型为section时的最大值
:type Max: str
"""
self.Min = None
self.Max = None
def _deserialize(self, params):
self.Min = params.get("Min")
self.Max = params.get("Max")
class CopyAccountPrivilegesRequest(AbstractModel):
"""CopyAccountPrivileges请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param SrcUserName: 源用户名
:type SrcUserName: str
:param SrcHost: 源用户允许的访问 host
:type SrcHost: str
:param DstUserName: 目的用户名
:type DstUserName: str
:param DstHost: 目的用户允许的访问 host
:type DstHost: str
:param SrcReadOnly: 源账号的 ReadOnly 属性
:type SrcReadOnly: str
:param DstReadOnly: 目的账号的 ReadOnly 属性
:type DstReadOnly: str
"""
self.InstanceId = None
self.SrcUserName = None
self.SrcHost = None
self.DstUserName = None
self.DstHost = None
self.SrcReadOnly = None
self.DstReadOnly = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.SrcUserName = params.get("SrcUserName")
self.SrcHost = params.get("SrcHost")
self.DstUserName = params.get("DstUserName")
self.DstHost = params.get("DstHost")
self.SrcReadOnly = params.get("SrcReadOnly")
self.DstReadOnly = params.get("DstReadOnly")
class CopyAccountPrivilegesResponse(AbstractModel):
"""CopyAccountPrivileges返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class CreateAccountRequest(AbstractModel):
"""CreateAccount请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
:param UserName: AccountName
:type UserName: str
:param Host: 可以登录的主机,与mysql 账号的 host 格式一致,可以支持通配符,例如 %,10.%,10.20.%。
:type Host: str
:param Password: 账号密码,由字母、数字或常见符号组成,不能包含分号、单引号和双引号,长度为6~32位。
:type Password: str
:param ReadOnly: 是否创建为只读账号,0:否, 1:该账号的sql请求优先选择备机执行,备机不可用时选择主机执行,2:优先选择备机执行,备机不可用时操作失败,3:只从备机读取。
:type ReadOnly: int
:param Description: 账号备注,可以包含中文、英文字符、常见符号和数字,长度为0~256字符
:type Description: str
:param DelayThresh: 如果备机延迟超过本参数设置值,系统将认为备机发生故障
建议该参数值大于10。当ReadOnly选择1、2时该参数生效。
:type DelayThresh: int
"""
self.InstanceId = None
self.UserName = None
self.Host = None
self.Password = None
self.ReadOnly = None
self.Description = None
self.DelayThresh = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.Password = params.get("Password")
self.ReadOnly = params.get("ReadOnly")
self.Description = params.get("Description")
self.DelayThresh = params.get("DelayThresh")
class CreateAccountResponse(AbstractModel):
"""CreateAccount返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例Id,透传入参。
:type InstanceId: str
:param UserName: 用户名,透传入参。
:type UserName: str
:param Host: 允许访问的 host,透传入参。
:type Host: str
:param ReadOnly: 透传入参。
:type ReadOnly: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.UserName = None
self.Host = None
self.ReadOnly = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.ReadOnly = params.get("ReadOnly")
self.RequestId = params.get("RequestId")
class CreateDCDBInstanceRequest(AbstractModel):
"""CreateDCDBInstance请求参数结构体
"""
def __init__(self):
"""
:param Zones: 分片节点可用区分布,最多可填两个可用区。当分片规格为一主两从时,其中两个节点在第一个可用区。
:type Zones: list of str
:param Period: 欲购买的时长,单位:月。
:type Period: int
:param ShardMemory: 分片内存大小,单位:GB,可以通过 DescribeShardSpec
查询实例规格获得。
:type ShardMemory: int
:param ShardStorage: 分片存储空间大小,单位:GB,可以通过 DescribeShardSpec
查询实例规格获得。
:type ShardStorage: int
:param ShardNodeCount: 单个分片节点个数,可以通过 DescribeShardSpec
查询实例规格获得。
:type ShardNodeCount: int
:param ShardCount: 实例分片个数,可选范围2-8,可以通过升级实例进行新增分片到最多64个分片。
:type ShardCount: int
:param Count: 欲购买实例的数量,目前只支持购买1个实例
:type Count: int
:param ProjectId: 项目 ID,可以通过查看项目列表获取,不传则关联到默认项目
:type ProjectId: int
:param VpcId: 虚拟私有网络 ID,不传或传空表示创建为基础网络
:type VpcId: str
:param SubnetId: 虚拟私有网络子网 ID,VpcId不为空时必填
:type SubnetId: str
:param DbVersionId: 数据库引擎版本,当前可选:10.0.10,10.1.9,5.7.17。
10.0.10 - Mariadb 10.0.10;
10.1.9 - Mariadb 10.1.9;
5.7.17 - Percona 5.7.17。
如果不填的话,默认为10.1.9,表示Mariadb 10.1.9。
:type DbVersionId: str
:param AutoVoucher: 是否自动使用代金券进行支付,默认不使用。
:type AutoVoucher: bool
:param VoucherIds: 代金券ID列表,目前仅支持指定一张代金券。
:type VoucherIds: list of str
"""
self.Zones = None
self.Period = None
self.ShardMemory = None
self.ShardStorage = None
self.ShardNodeCount = None
self.ShardCount = None
self.Count = None
self.ProjectId = None
self.VpcId = None
self.SubnetId = None
self.DbVersionId = None
self.AutoVoucher = None
self.VoucherIds = None
def _deserialize(self, params):
self.Zones = params.get("Zones")
self.Period = params.get("Period")
self.ShardMemory = params.get("ShardMemory")
self.ShardStorage = params.get("ShardStorage")
self.ShardNodeCount = params.get("ShardNodeCount")
self.ShardCount = params.get("ShardCount")
self.Count = params.get("Count")
self.ProjectId = params.get("ProjectId")
self.VpcId = params.get("VpcId")
self.SubnetId = params.get("SubnetId")
self.DbVersionId = params.get("DbVersionId")
self.AutoVoucher = params.get("AutoVoucher")
self.VoucherIds = params.get("VoucherIds")
class CreateDCDBInstanceResponse(AbstractModel):
"""CreateDCDBInstance返回参数结构体
"""
def __init__(self):
"""
:param DealName: 长订单号。可以据此调用 DescribeOrders
查询订单详细信息,或在支付失败时调用用户账号相关接口进行支付。
:type DealName: str
:param InstanceIds: 订单对应的实例 ID 列表,如果此处没有返回实例 ID,可以通过订单查询接口获取。还可通过实例查询接口查询实例是否创建完成。
注意:此字段可能返回 null,表示取不到有效值。
:type InstanceIds: list of str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DealName = None
self.InstanceIds = None
self.RequestId = None
def _deserialize(self, params):
self.DealName = params.get("DealName")
self.InstanceIds = params.get("InstanceIds")
self.RequestId = params.get("RequestId")
class DBAccount(AbstractModel):
"""云数据库账号信息
"""
def __init__(self):
"""
:param UserName: 用户名
:type UserName: str
:param Host: 用户可以从哪台主机登录(对应 MySQL 用户的 host 字段,UserName + Host 唯一标识一个用户,IP形式,IP段以%结尾;支持填入%;为空默认等于%)
:type Host: str
:param Description: 用户备注信息
:type Description: str
:param CreateTime: 创建时间
:type CreateTime: str
:param UpdateTime: 最后更新时间
:type UpdateTime: str
:param ReadOnly: 只读标记,0:否, 1:该账号的sql请求优先选择备机执行,备机不可用时选择主机执行,2:优先选择备机执行,备机不可用时操作失败。
:type ReadOnly: int
:param DelayThresh: 如果备机延迟超过本参数设置值,系统将认为备机发生故障
建议该参数值大于10。当ReadOnly选择1、2时该参数生效。
:type DelayThresh: int
"""
self.UserName = None
self.Host = None
self.Description = None
self.CreateTime = None
self.UpdateTime = None
self.ReadOnly = None
self.DelayThresh = None
def _deserialize(self, params):
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.Description = params.get("Description")
self.CreateTime = params.get("CreateTime")
self.UpdateTime = params.get("UpdateTime")
self.ReadOnly = params.get("ReadOnly")
self.DelayThresh = params.get("DelayThresh")
class DBParamValue(AbstractModel):
"""云数据库参数信息。
"""
def __init__(self):
"""
:param Param: 参数名称
:type Param: str
:param Value: 参数值
:type Value: str
"""
self.Param = None
self.Value = None
def _deserialize(self, params):
self.Param = params.get("Param")
self.Value = params.get("Value")
class DCDBInstanceInfo(AbstractModel):
"""分布式数据库实例信息
"""
def __init__(self):
"""
:param InstanceId: 实例ID
:type InstanceId: str
:param InstanceName: 实例名称
:type InstanceName: str
:param AppId: APPID
:type AppId: int
:param ProjectId: 项目ID
:type ProjectId: int
:param Region: 地域
:type Region: str
:param Zone: 可用区
:type Zone: str
:param VpcId: VPC数字ID
:type VpcId: int
:param SubnetId: Subnet数字ID
:type SubnetId: int
:param StatusDesc: 状态中文描述
:type StatusDesc: str
:param Status: 状态
:type Status: int
:param Vip: 内网IP
:type Vip: str
:param Vport: 内网端口
:type Vport: int
:param CreateTime: 创建时间
:type CreateTime: str
:param AutoRenewFlag: 自动续费标志
:type AutoRenewFlag: int
:param Memory: 内存大小,单位 GB
:type Memory: int
:param Storage: 存储大小,单位 GB
:type Storage: int
:param ShardCount: 分片个数
:type ShardCount: int
:param PeriodEndTime: 到期时间
:type PeriodEndTime: str
:param IsolatedTimestamp: 隔离时间
:type IsolatedTimestamp: str
:param Uin: UIN
:type Uin: str
:param ShardDetail: 分片详情
:type ShardDetail: list of ShardInfo
:param NodeCount: 节点数,2 为一主一从, 3 为一主二从
:type NodeCount: int
:param IsTmp: 临时实例标记,0 为非临时实例
:type IsTmp: int
:param ExclusterId: 独享集群Id,为空表示非独享集群实例
:type ExclusterId: str
:param UniqueVpcId: 字符串型的私有网络Id
:type UniqueVpcId: str
:param UniqueSubnetId: 字符串型的私有网络子网Id
:type UniqueSubnetId: str
:param Id: 数字实例Id(过时字段,请勿依赖该值)
:type Id: int
:param WanDomain: 外网访问的域名,公网可解析
:type WanDomain: str
:param WanVip: 外网 IP 地址,公网可访问
:type WanVip: str
:param WanPort: 外网端口
:type WanPort: int
:param Pid: 产品类型 Id(过时字段,请勿依赖该值)
:type Pid: int
:param UpdateTime: 实例最后更新时间,格式为 2006-01-02 15:04:05
:type UpdateTime: str
:param DbEngine: 数据库引擎
:type DbEngine: str
:param DbVersion: 数据库引擎版本
:type DbVersion: str
:param Paymode: 付费模式
:type Paymode: str
:param Locker: 实例处于异步任务状态时,表示异步任务流程ID
注意:此字段可能返回 null,表示取不到有效值。
:type Locker: int
:param WanStatus: 外网状态,0-未开通;1-已开通;2-关闭;3-开通中
:type WanStatus: int
:param IsAuditSupported: 该实例是否支持审计。1-支持;0-不支持
:type IsAuditSupported: int
"""
self.InstanceId = None
self.InstanceName = None
self.AppId = None
self.ProjectId = None
self.Region = None
self.Zone = None
self.VpcId = None
self.SubnetId = None
self.StatusDesc = None
self.Status = None
self.Vip = None
self.Vport = None
self.CreateTime = None
self.AutoRenewFlag = None
self.Memory = None
self.Storage = None
self.ShardCount = None
self.PeriodEndTime = None
self.IsolatedTimestamp = None
self.Uin = None
self.ShardDetail = None
self.NodeCount = None
self.IsTmp = None
self.ExclusterId = None
self.UniqueVpcId = None
self.UniqueSubnetId = None
self.Id = None
self.WanDomain = None
self.WanVip = None
self.WanPort = None
self.Pid = None
self.UpdateTime = None
self.DbEngine = None
self.DbVersion = None
self.Paymode = None
self.Locker = None
self.WanStatus = None
self.IsAuditSupported = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.InstanceName = params.get("InstanceName")
self.AppId = params.get("AppId")
self.ProjectId = params.get("ProjectId")
self.Region = params.get("Region")
self.Zone = params.get("Zone")
self.VpcId = params.get("VpcId")
self.SubnetId = params.get("SubnetId")
self.StatusDesc = params.get("StatusDesc")
self.Status = params.get("Status")
self.Vip = params.get("Vip")
self.Vport = params.get("Vport")
self.CreateTime = params.get("CreateTime")
self.AutoRenewFlag = params.get("AutoRenewFlag")
self.Memory = params.get("Memory")
self.Storage = params.get("Storage")
self.ShardCount = params.get("ShardCount")
self.PeriodEndTime = params.get("PeriodEndTime")
self.IsolatedTimestamp = params.get("IsolatedTimestamp")
self.Uin = params.get("Uin")
if params.get("ShardDetail") is not None:
self.ShardDetail = []
for item in params.get("ShardDetail"):
obj = ShardInfo()
obj._deserialize(item)
self.ShardDetail.append(obj)
self.NodeCount = params.get("NodeCount")
self.IsTmp = params.get("IsTmp")
self.ExclusterId = params.get("ExclusterId")
self.UniqueVpcId = params.get("UniqueVpcId")
self.UniqueSubnetId = params.get("UniqueSubnetId")
self.Id = params.get("Id")
self.WanDomain = params.get("WanDomain")
self.WanVip = params.get("WanVip")
self.WanPort = params.get("WanPort")
self.Pid = params.get("Pid")
self.UpdateTime = params.get("UpdateTime")
self.DbEngine = params.get("DbEngine")
self.DbVersion = params.get("DbVersion")
self.Paymode = params.get("Paymode")
self.Locker = params.get("Locker")
self.WanStatus = params.get("WanStatus")
self.IsAuditSupported = params.get("IsAuditSupported")
class DCDBShardInfo(AbstractModel):
"""描述分布式数据库分片信息。
"""
def __init__(self):
"""
:param InstanceId: 所属实例Id
:type InstanceId: str
:param ShardSerialId: 分片SQL透传Id,用于将sql透传到指定分片执行
:type ShardSerialId: str
:param ShardInstanceId: 全局唯一的分片Id
:type ShardInstanceId: str
:param Status: 状态:0 创建中,1 流程处理中, 2 运行中,3 分片未初始化
:type Status: int
:param StatusDesc: 状态中文描述
:type StatusDesc: str
:param CreateTime: 创建时间
:type CreateTime: str
:param VpcId: 字符串格式的私有网络Id
:type VpcId: str
:param SubnetId: 字符串格式的私有网络子网Id
:type SubnetId: str
:param ProjectId: 项目ID
:type ProjectId: int
:param Region: 地域
:type Region: str
:param Zone: 可用区
:type Zone: str
:param Memory: 内存大小,单位 GB
:type Memory: int
:param Storage: 存储大小,单位 GB
:type Storage: int
:param PeriodEndTime: 到期时间
:type PeriodEndTime: str
:param NodeCount: 节点数,2 为一主一从, 3 为一主二从
:type NodeCount: int
:param StorageUsage: 存储使用率,单位为 %
:type StorageUsage: float
:param MemoryUsage: 内存使用率,单位为 %
:type MemoryUsage: float
:param ShardId: 数字分片Id(过时字段,请勿依赖该值)
:type ShardId: int
:param Pid: 产品ProductID
:type Pid: int
:param ProxyVersion: Proxy版本
:type ProxyVersion: str
"""
self.InstanceId = None
self.ShardSerialId = None
self.ShardInstanceId = None
self.Status = None
self.StatusDesc = None
self.CreateTime = None
self.VpcId = None
self.SubnetId = None
self.ProjectId = None
self.Region = None
self.Zone = None
self.Memory = None
self.Storage = None
self.PeriodEndTime = None
self.NodeCount = None
self.StorageUsage = None
self.MemoryUsage = None
self.ShardId = None
self.Pid = None
self.ProxyVersion = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.ShardSerialId = params.get("ShardSerialId")
self.ShardInstanceId = params.get("ShardInstanceId")
self.Status = params.get("Status")
self.StatusDesc = params.get("StatusDesc")
self.CreateTime = params.get("CreateTime")
self.VpcId = params.get("VpcId")
self.SubnetId = params.get("SubnetId")
self.ProjectId = params.get("ProjectId")
self.Region = params.get("Region")
self.Zone = params.get("Zone")
self.Memory = params.get("Memory")
self.Storage = params.get("Storage")
self.PeriodEndTime = params.get("PeriodEndTime")
self.NodeCount = params.get("NodeCount")
self.StorageUsage = params.get("StorageUsage")
self.MemoryUsage = params.get("MemoryUsage")
self.ShardId = params.get("ShardId")
self.Pid = params.get("Pid")
self.ProxyVersion = params.get("ProxyVersion")
class Database(AbstractModel):
"""数据库信息
"""
def __init__(self):
"""
:param DbName: 数据库名称
:type DbName: str
"""
self.DbName = None
def _deserialize(self, params):
self.DbName = params.get("DbName")
class DatabaseFunction(AbstractModel):
"""数据库函数信息
"""
def __init__(self):
"""
:param Func: 函数名称
:type Func: str
"""
self.Func = None
def _deserialize(self, params):
self.Func = params.get("Func")
class DatabaseProcedure(AbstractModel):
"""数据库存储过程信息
"""
def __init__(self):
"""
:param Proc: 存储过程名称
:type Proc: str
"""
self.Proc = None
def _deserialize(self, params):
self.Proc = params.get("Proc")
class DatabaseTable(AbstractModel):
"""数据库表信息
"""
def __init__(self):
"""
:param Table: 表名
:type Table: str
"""
self.Table = None
def _deserialize(self, params):
self.Table = params.get("Table")
class DatabaseView(AbstractModel):
"""数据库视图信息
"""
def __init__(self):
"""
:param View: 视图名称
:type View: str
"""
self.View = None
def _deserialize(self, params):
self.View = params.get("View")
class Deal(AbstractModel):
"""订单信息
"""
def __init__(self):
"""
:param DealName: 订单号
:type DealName: str
:param OwnerUin: 所属账号
:type OwnerUin: str
:param Count: 商品数量
:type Count: int
:param FlowId: 关联的流程 Id,可用于查询流程执行状态
:type FlowId: int
:param InstanceIds: 只有创建实例的订单会填充该字段,表示该订单创建的实例的 ID。
注意:此字段可能返回 null,表示取不到有效值。
:type InstanceIds: list of str
:param PayMode: 付费模式,0后付费/1预付费
:type PayMode: int
"""
self.DealName = None
self.OwnerUin = None
self.Count = None
self.FlowId = None
self.InstanceIds = None
self.PayMode = None
def _deserialize(self, params):
self.DealName = params.get("DealName")
self.OwnerUin = params.get("OwnerUin")
self.Count = params.get("Count")
self.FlowId = params.get("FlowId")
self.InstanceIds = params.get("InstanceIds")
self.PayMode = params.get("PayMode")
class DeleteAccountRequest(AbstractModel):
"""DeleteAccount请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
:param UserName: 用户名
:type UserName: str
:param Host: 用户允许的访问 host
:type Host: str
"""
self.InstanceId = None
self.UserName = None
self.Host = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
class DeleteAccountResponse(AbstractModel):
"""DeleteAccount返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class DescribeAccountPrivilegesRequest(AbstractModel):
"""DescribeAccountPrivileges请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow7t8lmc。
:type InstanceId: str
:param UserName: 登录用户名。
:type UserName: str
:param Host: 用户允许的访问 host,用户名+host唯一确定一个账号。
:type Host: str
:param DbName: 数据库名。如果为 \*,表示查询全局权限(即 \*.\*),此时忽略 Type 和 Object 参数
:type DbName: str
:param Type: 类型,可以填入 table 、 view 、 proc 、 func 和 \*。当 DbName 为具体数据库名,Type为 \* 时,表示查询该数据库权限(即db.\*),此时忽略 Object 参数
:type Type: str
:param Object: 具体的 Type 的名称,比如 Type 为 table 时就是具体的表名。DbName 和 Type 都为具体名称,则 Object 表示具体对象名,不能为 \* 或者为空
:type Object: str
:param ColName: 当 Type=table 时,ColName 为 \* 表示查询表的权限,如果为具体字段名,表示查询对应字段的权限
:type ColName: str
"""
self.InstanceId = None
self.UserName = None
self.Host = None
self.DbName = None
self.Type = None
self.Object = None
self.ColName = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.DbName = params.get("DbName")
self.Type = params.get("Type")
self.Object = params.get("Object")
self.ColName = params.get("ColName")
class DescribeAccountPrivilegesResponse(AbstractModel):
"""DescribeAccountPrivileges返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例Id
:type InstanceId: str
:param Privileges: 权限列表。
:type Privileges: list of str
:param UserName: 数据库账号用户名
:type UserName: str
:param Host: 数据库账号Host
:type Host: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.Privileges = None
self.UserName = None
self.Host = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.Privileges = params.get("Privileges")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.RequestId = params.get("RequestId")
class DescribeAccountsRequest(AbstractModel):
"""DescribeAccounts请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
"""
self.InstanceId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
class DescribeAccountsResponse(AbstractModel):
"""DescribeAccounts返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例ID,透传入参。
:type InstanceId: str
:param Users: 实例用户列表。
注意:此字段可能返回 null,表示取不到有效值。
:type Users: list of DBAccount
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.Users = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
if params.get("Users") is not None:
self.Users = []
for item in params.get("Users"):
obj = DBAccount()
obj._deserialize(item)
self.Users.append(obj)
self.RequestId = params.get("RequestId")
class DescribeDBLogFilesRequest(AbstractModel):
"""DescribeDBLogFiles请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow7t8lmc。
:type InstanceId: str
:param ShardId: 分片 ID,形如:shard-7noic7tv
:type ShardId: str
:param Type: 请求日志类型,取值只能为1、2、3或者4。1-binlog,2-冷备,3-errlog,4-slowlog。
:type Type: int
"""
self.InstanceId = None
self.ShardId = None
self.Type = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.ShardId = params.get("ShardId")
self.Type = params.get("Type")
class DescribeDBLogFilesResponse(AbstractModel):
"""DescribeDBLogFiles返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param Type: 请求日志类型。1-binlog,2-冷备,3-errlog,4-slowlog。
:type Type: int
:param Total: 请求日志总数
:type Total: int
:param Files: 日志文件列表
:type Files: list of LogFileInfo
:param VpcPrefix: 如果是VPC网络的实例,做用本前缀加上URI为下载地址
:type VpcPrefix: str
:param NormalPrefix: 如果是普通网络的实例,做用本前缀加上URI为下载地址
:type NormalPrefix: str
:param ShardId: 分片 ID,形如:shard-7noic7tv
:type ShardId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.Type = None
self.Total = None
self.Files = None
self.VpcPrefix = None
self.NormalPrefix = None
self.ShardId = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.Type = params.get("Type")
self.Total = params.get("Total")
if params.get("Files") is not None:
self.Files = []
for item in params.get("Files"):
obj = LogFileInfo()
obj._deserialize(item)
self.Files.append(obj)
self.VpcPrefix = params.get("VpcPrefix")
self.NormalPrefix = params.get("NormalPrefix")
self.ShardId = params.get("ShardId")
self.RequestId = params.get("RequestId")
class DescribeDBParametersRequest(AbstractModel):
"""DescribeDBParameters请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow7t8lmc。
:type InstanceId: str
"""
self.InstanceId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
class DescribeDBParametersResponse(AbstractModel):
"""DescribeDBParameters返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow7t8lmc。
:type InstanceId: str
:param Params: 请求DB的当前参数值
:type Params: list of ParamDesc
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.Params = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
if params.get("Params") is not None:
self.Params = []
for item in params.get("Params"):
obj = ParamDesc()
obj._deserialize(item)
self.Params.append(obj)
self.RequestId = params.get("RequestId")
class DescribeDBSyncModeRequest(AbstractModel):
"""DescribeDBSyncMode请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待修改同步模式的实例ID。形如:dcdbt-ow728lmc。
:type InstanceId: str
"""
self.InstanceId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
class DescribeDBSyncModeResponse(AbstractModel):
"""DescribeDBSyncMode返回参数结构体
"""
def __init__(self):
"""
:param SyncMode: 同步模式:0 异步,1 强同步, 2 强同步可退化
:type SyncMode: int
:param IsModifying: 是否有修改流程在执行中:1 是, 0 否。
:type IsModifying: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.SyncMode = None
self.IsModifying = None
self.RequestId = None
def _deserialize(self, params):
self.SyncMode = params.get("SyncMode")
self.IsModifying = params.get("IsModifying")
self.RequestId = params.get("RequestId")
class DescribeDCDBInstancesRequest(AbstractModel):
"""DescribeDCDBInstances请求参数结构体
"""
def __init__(self):
"""
:param InstanceIds: 按照一个或者多个实例 ID 查询。实例 ID 形如:dcdbt-2t4cf98d
:type InstanceIds: list of str
:param SearchName: 搜索的字段名,当前支持的值有:instancename、vip、all。传 instancename 表示按实例名进行搜索;传 vip 表示按内网IP进行搜索;传 all 将会按实例ID、实例名和内网IP进行搜索。
:type SearchName: str
:param SearchKey: 搜索的关键字,支持模糊搜索。多个关键字使用换行符('\n')分割。
:type SearchKey: str
:param ProjectIds: 按项目 ID 查询
:type ProjectIds: list of int
:param IsFilterVpc: 是否根据 VPC 网络来搜索
:type IsFilterVpc: bool
:param VpcId: 私有网络 ID, IsFilterVpc 为 1 时有效
:type VpcId: str
:param SubnetId: 私有网络的子网 ID, IsFilterVpc 为 1 时有效
:type SubnetId: str
:param OrderBy: 排序字段, projectId, createtime, instancename 三者之一
:type OrderBy: str
:param OrderByType: 排序类型, desc 或者 asc
:type OrderByType: str
:param Offset: 偏移量,默认为 0
:type Offset: int
:param Limit: 返回数量,默认为 10,最大值为 100。
:type Limit: int
:param ExclusterType: 1非独享集群,2独享集群, 0全部
:type ExclusterType: int
:param IsFilterExcluster: 标识是否使用ExclusterType字段, false不使用,true使用
:type IsFilterExcluster: bool
:param ExclusterIds: 独享集群ID
:type ExclusterIds: list of str
"""
self.InstanceIds = None
self.SearchName = None
self.SearchKey = None
self.ProjectIds = None
self.IsFilterVpc = None
self.VpcId = None
self.SubnetId = None
self.OrderBy = None
self.OrderByType = None
self.Offset = None
self.Limit = None
self.ExclusterType = None
self.IsFilterExcluster = None
self.ExclusterIds = None
def _deserialize(self, params):
self.InstanceIds = params.get("InstanceIds")
self.SearchName = params.get("SearchName")
self.SearchKey = params.get("SearchKey")
self.ProjectIds = params.get("ProjectIds")
self.IsFilterVpc = params.get("IsFilterVpc")
self.VpcId = params.get("VpcId")
self.SubnetId = params.get("SubnetId")
self.OrderBy = params.get("OrderBy")
self.OrderByType = params.get("OrderByType")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
self.ExclusterType = params.get("ExclusterType")
self.IsFilterExcluster = params.get("IsFilterExcluster")
self.ExclusterIds = params.get("ExclusterIds")
class DescribeDCDBInstancesResponse(AbstractModel):
"""DescribeDCDBInstances返回参数结构体
"""
def __init__(self):
"""
:param TotalCount: 符合条件的实例数量
:type TotalCount: int
:param Instances: 实例详细信息列表
:type Instances: list of DCDBInstanceInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.Instances = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("Instances") is not None:
self.Instances = []
for item in params.get("Instances"):
obj = DCDBInstanceInfo()
obj._deserialize(item)
self.Instances.append(obj)
self.RequestId = params.get("RequestId")
class DescribeDCDBPriceRequest(AbstractModel):
"""DescribeDCDBPrice请求参数结构体
"""
def __init__(self):
"""
:param Zone: 欲新购实例的可用区ID。
:type Zone: str
:param Count: 欲购买实例的数量,目前只支持购买1个实例
:type Count: int
:param Period: 欲购买的时长,单位:月。
:type Period: int
:param ShardNodeCount: 单个分片节点个数大小,可以通过 DescribeShardSpec
查询实例规格获得。
:type ShardNodeCount: int
:param ShardMemory: 分片内存大小,单位:GB,可以通过 DescribeShardSpec
查询实例规格获得。
:type ShardMemory: int
:param ShardStorage: 分片存储空间大小,单位:GB,可以通过 DescribeShardSpec
查询实例规格获得。
:type ShardStorage: int
:param ShardCount: 实例分片个数,可选范围2-8,可以通过升级实例进行新增分片到最多64个分片。
:type ShardCount: int
"""
self.Zone = None
self.Count = None
self.Period = None
self.ShardNodeCount = None
self.ShardMemory = None
self.ShardStorage = None
self.ShardCount = None
def _deserialize(self, params):
self.Zone = params.get("Zone")
self.Count = params.get("Count")
self.Period = params.get("Period")
self.ShardNodeCount = params.get("ShardNodeCount")
self.ShardMemory = params.get("ShardMemory")
self.ShardStorage = params.get("ShardStorage")
self.ShardCount = params.get("ShardCount")
class DescribeDCDBPriceResponse(AbstractModel):
"""DescribeDCDBPrice返回参数结构体
"""
def __init__(self):
"""
:param OriginalPrice: 原价,单位:分
:type OriginalPrice: int
:param Price: 实际价格,单位:分。受折扣等影响,可能和原价不同。
:type Price: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.OriginalPrice = None
self.Price = None
self.RequestId = None
def _deserialize(self, params):
self.OriginalPrice = params.get("OriginalPrice")
self.Price = params.get("Price")
self.RequestId = params.get("RequestId")
class DescribeDCDBRenewalPriceRequest(AbstractModel):
"""DescribeDCDBRenewalPrice请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待续费的实例ID。形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
:param Period: 续费时长,单位:月。不传则默认为1个月。
:type Period: int
"""
self.InstanceId = None
self.Period = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.Period = params.get("Period")
class DescribeDCDBRenewalPriceResponse(AbstractModel):
"""DescribeDCDBRenewalPrice返回参数结构体
"""
def __init__(self):
"""
:param OriginalPrice: 原价,单位:分
:type OriginalPrice: int
:param Price: 实际价格,单位:分。受折扣等影响,可能和原价不同。
:type Price: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.OriginalPrice = None
self.Price = None
self.RequestId = None
def _deserialize(self, params):
self.OriginalPrice = params.get("OriginalPrice")
self.Price = params.get("Price")
self.RequestId = params.get("RequestId")
class DescribeDCDBSaleInfoRequest(AbstractModel):
"""DescribeDCDBSaleInfo请求参数结构体
"""
class DescribeDCDBSaleInfoResponse(AbstractModel):
"""DescribeDCDBSaleInfo返回参数结构体
"""
def __init__(self):
"""
:param RegionList: 可售卖地域信息列表
:type RegionList: list of RegionInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RegionList = None
self.RequestId = None
def _deserialize(self, params):
if params.get("RegionList") is not None:
self.RegionList = []
for item in params.get("RegionList"):
obj = RegionInfo()
obj._deserialize(item)
self.RegionList.append(obj)
self.RequestId = params.get("RequestId")
class DescribeDCDBShardsRequest(AbstractModel):
"""DescribeDCDBShards请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param ShardInstanceIds: 分片Id列表。
:type ShardInstanceIds: list of str
:param Offset: 偏移量,默认为 0
:type Offset: int
:param Limit: 返回数量,默认为 20,最大值为 100。
:type Limit: int
:param OrderBy: 排序字段, 目前仅支持 createtime
:type OrderBy: str
:param OrderByType: 排序类型, desc 或者 asc
:type OrderByType: str
"""
self.InstanceId = None
self.ShardInstanceIds = None
self.Offset = None
self.Limit = None
self.OrderBy = None
self.OrderByType = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.ShardInstanceIds = params.get("ShardInstanceIds")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
self.OrderBy = params.get("OrderBy")
self.OrderByType = params.get("OrderByType")
class DescribeDCDBShardsResponse(AbstractModel):
"""DescribeDCDBShards返回参数结构体
"""
def __init__(self):
"""
:param TotalCount: 符合条件的分片数量
:type TotalCount: int
:param Shards: 分片信息列表
:type Shards: list of DCDBShardInfo
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.Shards = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("Shards") is not None:
self.Shards = []
for item in params.get("Shards"):
obj = DCDBShardInfo()
obj._deserialize(item)
self.Shards.append(obj)
self.RequestId = params.get("RequestId")
class DescribeDCDBUpgradePriceRequest(AbstractModel):
"""DescribeDCDBUpgradePrice请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待升级的实例ID。形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
:param UpgradeType: 升级类型,取值范围:
<li> ADD: 新增分片 </li>
<li> EXPAND: 升级实例中的已有分片 </li>
<li> SPLIT: 将已有分片中的数据切分到新增分片上</li>
:type UpgradeType: str
:param AddShardConfig: 新增分片配置,当UpgradeType为ADD时生效。
:type AddShardConfig: :class:`tencentcloud.dcdb.v20180411.models.AddShardConfig`
:param ExpandShardConfig: 扩容分片配置,当UpgradeType为EXPAND时生效。
:type ExpandShardConfig: :class:`tencentcloud.dcdb.v20180411.models.ExpandShardConfig`
:param SplitShardConfig: 切分分片配置,当UpgradeType为SPLIT时生效。
:type SplitShardConfig: :class:`tencentcloud.dcdb.v20180411.models.SplitShardConfig`
"""
self.InstanceId = None
self.UpgradeType = None
self.AddShardConfig = None
self.ExpandShardConfig = None
self.SplitShardConfig = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UpgradeType = params.get("UpgradeType")
if params.get("AddShardConfig") is not None:
self.AddShardConfig = AddShardConfig()
self.AddShardConfig._deserialize(params.get("AddShardConfig"))
if params.get("ExpandShardConfig") is not None:
self.ExpandShardConfig = ExpandShardConfig()
self.ExpandShardConfig._deserialize(params.get("ExpandShardConfig"))
if params.get("SplitShardConfig") is not None:
self.SplitShardConfig = SplitShardConfig()
self.SplitShardConfig._deserialize(params.get("SplitShardConfig"))
class DescribeDCDBUpgradePriceResponse(AbstractModel):
"""DescribeDCDBUpgradePrice返回参数结构体
"""
def __init__(self):
"""
:param OriginalPrice: 原价,单位:分
:type OriginalPrice: int
:param Price: 实际价格,单位:分。受折扣等影响,可能和原价不同。
:type Price: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.OriginalPrice = None
self.Price = None
self.RequestId = None
def _deserialize(self, params):
self.OriginalPrice = params.get("OriginalPrice")
self.Price = params.get("Price")
self.RequestId = params.get("RequestId")
class DescribeDatabaseObjectsRequest(AbstractModel):
"""DescribeDatabaseObjects请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow7t8lmc。
:type InstanceId: str
:param DbName: 数据库名称,通过 DescribeDatabases 接口获取。
:type DbName: str
"""
self.InstanceId = None
self.DbName = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.DbName = params.get("DbName")
class DescribeDatabaseObjectsResponse(AbstractModel):
"""DescribeDatabaseObjects返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 透传入参。
:type InstanceId: str
:param DbName: 数据库名称。
:type DbName: str
:param Tables: 表列表。
:type Tables: list of DatabaseTable
:param Views: 视图列表。
:type Views: list of DatabaseView
:param Procs: 存储过程列表。
:type Procs: list of DatabaseProcedure
:param Funcs: 函数列表。
:type Funcs: list of DatabaseFunction
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.DbName = None
self.Tables = None
self.Views = None
self.Procs = None
self.Funcs = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.DbName = params.get("DbName")
if params.get("Tables") is not None:
self.Tables = []
for item in params.get("Tables"):
obj = DatabaseTable()
obj._deserialize(item)
self.Tables.append(obj)
if params.get("Views") is not None:
self.Views = []
for item in params.get("Views"):
obj = DatabaseView()
obj._deserialize(item)
self.Views.append(obj)
if params.get("Procs") is not None:
self.Procs = []
for item in params.get("Procs"):
obj = DatabaseProcedure()
obj._deserialize(item)
self.Procs.append(obj)
if params.get("Funcs") is not None:
self.Funcs = []
for item in params.get("Funcs"):
obj = DatabaseFunction()
obj._deserialize(item)
self.Funcs.append(obj)
self.RequestId = params.get("RequestId")
class DescribeDatabaseTableRequest(AbstractModel):
"""DescribeDatabaseTable请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow7t8lmc。
:type InstanceId: str
:param DbName: 数据库名称,通过 DescribeDatabases 接口获取。
:type DbName: str
:param Table: 表名称,通过 DescribeDatabaseObjects 接口获取。
:type Table: str
"""
self.InstanceId = None
self.DbName = None
self.Table = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.DbName = params.get("DbName")
self.Table = params.get("Table")
class DescribeDatabaseTableResponse(AbstractModel):
"""DescribeDatabaseTable返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例名称。
:type InstanceId: str
:param DbName: 数据库名称。
:type DbName: str
:param Table: 表名称。
:type Table: str
:param Cols: 列信息。
:type Cols: list of TableColumn
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.DbName = None
self.Table = None
self.Cols = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.DbName = params.get("DbName")
self.Table = params.get("Table")
if params.get("Cols") is not None:
self.Cols = []
for item in params.get("Cols"):
obj = TableColumn()
obj._deserialize(item)
self.Cols.append(obj)
self.RequestId = params.get("RequestId")
class DescribeDatabasesRequest(AbstractModel):
"""DescribeDatabases请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow7t8lmc。
:type InstanceId: str
"""
self.InstanceId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
class DescribeDatabasesResponse(AbstractModel):
"""DescribeDatabases返回参数结构体
"""
def __init__(self):
"""
:param Databases: 该实例上的数据库列表。
:type Databases: list of Database
:param InstanceId: 透传入参。
:type InstanceId: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.Databases = None
self.InstanceId = None
self.RequestId = None
def _deserialize(self, params):
if params.get("Databases") is not None:
self.Databases = []
for item in params.get("Databases"):
obj = Database()
obj._deserialize(item)
self.Databases.append(obj)
self.InstanceId = params.get("InstanceId")
self.RequestId = params.get("RequestId")
class DescribeOrdersRequest(AbstractModel):
"""DescribeOrders请求参数结构体
"""
def __init__(self):
"""
:param DealNames: 待查询的长订单号列表,创建实例、续费实例、扩容实例接口返回。
:type DealNames: list of str
"""
self.DealNames = None
def _deserialize(self, params):
self.DealNames = params.get("DealNames")
class DescribeOrdersResponse(AbstractModel):
"""DescribeOrders返回参数结构体
"""
def __init__(self):
"""
:param TotalCount: 返回的订单数量。
:type TotalCount: list of int
:param Deals: 订单信息列表。
:type Deals: list of Deal
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.Deals = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
if params.get("Deals") is not None:
self.Deals = []
for item in params.get("Deals"):
obj = Deal()
obj._deserialize(item)
self.Deals.append(obj)
self.RequestId = params.get("RequestId")
class DescribeShardSpecRequest(AbstractModel):
"""DescribeShardSpec请求参数结构体
"""
class DescribeShardSpecResponse(AbstractModel):
"""DescribeShardSpec返回参数结构体
"""
def __init__(self):
"""
:param SpecConfig: 按机型分类的可售卖规格列表
:type SpecConfig: list of SpecConfig
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.SpecConfig = None
self.RequestId = None
def _deserialize(self, params):
if params.get("SpecConfig") is not None:
self.SpecConfig = []
for item in params.get("SpecConfig"):
obj = SpecConfig()
obj._deserialize(item)
self.SpecConfig.append(obj)
self.RequestId = params.get("RequestId")
class DescribeSqlLogsRequest(AbstractModel):
"""DescribeSqlLogs请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
:param Offset: SQL日志偏移。
:type Offset: int
:param Limit: 拉取数量(0-10000,为0时拉取总数信息)。
:type Limit: int
"""
self.InstanceId = None
self.Offset = None
self.Limit = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.Offset = params.get("Offset")
self.Limit = params.get("Limit")
class DescribeSqlLogsResponse(AbstractModel):
"""DescribeSqlLogs返回参数结构体
"""
def __init__(self):
"""
:param TotalCount: 当前消息队列中的sql日志条目数。
:type TotalCount: int
:param StartOffset: 消息队列中的sql日志起始偏移。
:type StartOffset: int
:param EndOffset: 消息队列中的sql日志结束偏移。
:type EndOffset: int
:param Offset: 返回的第一条sql日志的偏移。
:type Offset: int
:param Count: 返回的sql日志数量。
:type Count: int
:param SqlItems: Sql日志列表。
:type SqlItems: list of SqlLogItem
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.TotalCount = None
self.StartOffset = None
self.EndOffset = None
self.Offset = None
self.Count = None
self.SqlItems = None
self.RequestId = None
def _deserialize(self, params):
self.TotalCount = params.get("TotalCount")
self.StartOffset = params.get("StartOffset")
self.EndOffset = params.get("EndOffset")
self.Offset = params.get("Offset")
self.Count = params.get("Count")
if params.get("SqlItems") is not None:
self.SqlItems = []
for item in params.get("SqlItems"):
obj = SqlLogItem()
obj._deserialize(item)
self.SqlItems.append(obj)
self.RequestId = params.get("RequestId")
class ExpandShardConfig(AbstractModel):
"""升级实例 -- 扩容分片类型
"""
def __init__(self):
"""
:param ShardInstanceIds: 分片ID数组
:type ShardInstanceIds: list of str
:param ShardMemory: 分片内存大小,单位 GB
:type ShardMemory: int
:param ShardStorage: 分片存储大小,单位 GB
:type ShardStorage: int
"""
self.ShardInstanceIds = None
self.ShardMemory = None
self.ShardStorage = None
def _deserialize(self, params):
self.ShardInstanceIds = params.get("ShardInstanceIds")
self.ShardMemory = params.get("ShardMemory")
self.ShardStorage = params.get("ShardStorage")
class GrantAccountPrivilegesRequest(AbstractModel):
"""GrantAccountPrivileges请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param UserName: 登录用户名。
:type UserName: str
:param Host: 用户允许的访问 host,用户名+host唯一确定一个账号。
:type Host: str
:param DbName: 数据库名。如果为 \*,表示查询全局权限(即 \*.\*),此时忽略 Type 和 Object 参数
:type DbName: str
:param Privileges: 全局权限: SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,REFERENCES,INDEX,ALTER,CREATE TEMPORARY TABLES,LOCK TABLES,EXECUTE,CREATE VIEW,SHOW VIEW,CREATE ROUTINE,ALTER ROUTINE,EVENT,TRIGGER,SHOW DATABASES
库权限: SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,REFERENCES,INDEX,ALTER,CREATE TEMPORARY TABLES,LOCK TABLES,EXECUTE,CREATE VIEW,SHOW VIEW,CREATE ROUTINE,ALTER ROUTINE,EVENT,TRIGGER
表/视图权限: SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,REFERENCES,INDEX,ALTER,CREATE VIEW,SHOW VIEW,TRIGGER
存储过程/函数权限: ALTER ROUTINE,EXECUTE
字段权限: INSERT,REFERENCES,SELECT,UPDATE
:type Privileges: list of str
:param Type: 类型,可以填入 table 、 view 、 proc 、 func 和 \*。当 DbName 为具体数据库名,Type为 \* 时,表示设置该数据库权限(即db.\*),此时忽略 Object 参数
:type Type: str
:param Object: 具体的 Type 的名称,比如 Type 为 table 时就是具体的表名。DbName 和 Type 都为具体名称,则 Object 表示具体对象名,不能为 \* 或者为空
:type Object: str
:param ColName: 当 Type=table 时,ColName 为 \* 表示对表授权,如果为具体字段名,表示对字段授权
:type ColName: str
"""
self.InstanceId = None
self.UserName = None
self.Host = None
self.DbName = None
self.Privileges = None
self.Type = None
self.Object = None
self.ColName = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.DbName = params.get("DbName")
self.Privileges = params.get("Privileges")
self.Type = params.get("Type")
self.Object = params.get("Object")
self.ColName = params.get("ColName")
class GrantAccountPrivilegesResponse(AbstractModel):
"""GrantAccountPrivileges返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class InitDCDBInstancesRequest(AbstractModel):
"""InitDCDBInstances请求参数结构体
"""
def __init__(self):
"""
:param InstanceIds: 待初始化的实例Id列表,形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceIds: list of str
:param Params: 参数列表。本接口的可选值为:character_set_server(字符集,必传),lower_case_table_names(表名大小写敏感,必传,0 - 敏感;1-不敏感),innodb_page_size(innodb数据页,默认16K),sync_mode(同步模式:0 - 异步; 1 - 强同步;2 - 强同步可退化。默认为强同步)。
:type Params: list of DBParamValue
"""
self.InstanceIds = None
self.Params = None
def _deserialize(self, params):
self.InstanceIds = params.get("InstanceIds")
if params.get("Params") is not None:
self.Params = []
for item in params.get("Params"):
obj = DBParamValue()
obj._deserialize(item)
self.Params.append(obj)
class InitDCDBInstancesResponse(AbstractModel):
"""InitDCDBInstances返回参数结构体
"""
def __init__(self):
"""
:param FlowIds: 异步任务Id,可通过 DescribeFlow 查询任务状态。
:type FlowIds: list of int non-negative
:param InstanceIds: 透传入参。
:type InstanceIds: list of str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.FlowIds = None
self.InstanceIds = None
self.RequestId = None
def _deserialize(self, params):
self.FlowIds = params.get("FlowIds")
self.InstanceIds = params.get("InstanceIds")
self.RequestId = params.get("RequestId")
class LogFileInfo(AbstractModel):
"""拉取的日志信息
"""
def __init__(self):
"""
:param Mtime: Log最后修改时间
:type Mtime: int
:param Length: 文件长度
:type Length: int
:param Uri: 下载Log时用到的统一资源标识符
:type Uri: str
:param FileName: 文件名
:type FileName: str
"""
self.Mtime = None
self.Length = None
self.Uri = None
self.FileName = None
def _deserialize(self, params):
self.Mtime = params.get("Mtime")
self.Length = params.get("Length")
self.Uri = params.get("Uri")
self.FileName = params.get("FileName")
class ModifyAccountDescriptionRequest(AbstractModel):
"""ModifyAccountDescription请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param UserName: 登录用户名。
:type UserName: str
:param Host: 用户允许的访问 host,用户名+host唯一确定一个账号。
:type Host: str
:param Description: 新的账号备注,长度 0~256。
:type Description: str
"""
self.InstanceId = None
self.UserName = None
self.Host = None
self.Description = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.Description = params.get("Description")
class ModifyAccountDescriptionResponse(AbstractModel):
"""ModifyAccountDescription返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyDBInstancesProjectRequest(AbstractModel):
"""ModifyDBInstancesProject请求参数结构体
"""
def __init__(self):
"""
:param InstanceIds: 待修改的实例ID列表。实例 ID 形如:dcdbt-ow728lmc。
:type InstanceIds: list of str
:param ProjectId: 要分配的项目 ID,可以通过 DescribeProjects 查询项目列表接口获取。
:type ProjectId: int
"""
self.InstanceIds = None
self.ProjectId = None
def _deserialize(self, params):
self.InstanceIds = params.get("InstanceIds")
self.ProjectId = params.get("ProjectId")
class ModifyDBInstancesProjectResponse(AbstractModel):
"""ModifyDBInstancesProject返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ModifyDBParametersRequest(AbstractModel):
"""ModifyDBParameters请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param Params: 参数列表,每一个元素是Param和Value的组合
:type Params: list of DBParamValue
"""
self.InstanceId = None
self.Params = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
if params.get("Params") is not None:
self.Params = []
for item in params.get("Params"):
obj = DBParamValue()
obj._deserialize(item)
self.Params.append(obj)
class ModifyDBParametersResponse(AbstractModel):
"""ModifyDBParameters返回参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param Result: 各参数修改结果
:type Result: list of ParamModifyResult
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.InstanceId = None
self.Result = None
self.RequestId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
if params.get("Result") is not None:
self.Result = []
for item in params.get("Result"):
obj = ParamModifyResult()
obj._deserialize(item)
self.Result.append(obj)
self.RequestId = params.get("RequestId")
class ModifyDBSyncModeRequest(AbstractModel):
"""ModifyDBSyncMode请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待修改同步模式的实例ID。形如:dcdbt-ow728lmc。
:type InstanceId: str
:param SyncMode: 同步模式:0 异步,1 强同步, 2 强同步可退化
:type SyncMode: int
"""
self.InstanceId = None
self.SyncMode = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.SyncMode = params.get("SyncMode")
class ModifyDBSyncModeResponse(AbstractModel):
"""ModifyDBSyncMode返回参数结构体
"""
def __init__(self):
"""
:param FlowId: 异步任务Id,可通过 DescribeFlow 查询任务状态。
:type FlowId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.FlowId = None
self.RequestId = None
def _deserialize(self, params):
self.FlowId = params.get("FlowId")
self.RequestId = params.get("RequestId")
class OpenDBExtranetAccessRequest(AbstractModel):
"""OpenDBExtranetAccess请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待开放外网访问的实例ID。形如:dcdbt-ow728lmc。
:type InstanceId: str
"""
self.InstanceId = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
class OpenDBExtranetAccessResponse(AbstractModel):
"""OpenDBExtranetAccess返回参数结构体
"""
def __init__(self):
"""
:param FlowId: 异步任务Id,可通过 DescribeFlow 查询任务状态。
:type FlowId: int
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.FlowId = None
self.RequestId = None
def _deserialize(self, params):
self.FlowId = params.get("FlowId")
self.RequestId = params.get("RequestId")
class ParamConstraint(AbstractModel):
"""参数约束
"""
def __init__(self):
"""
:param Type: 约束类型,如枚举enum,区间section
:type Type: str
:param Enum: 约束类型为enum时的可选值列表
:type Enum: str
:param Range: 约束类型为section时的范围
注意:此字段可能返回 null,表示取不到有效值。
:type Range: :class:`tencentcloud.dcdb.v20180411.models.ConstraintRange`
:param String: 约束类型为string时的可选值列表
:type String: str
"""
self.Type = None
self.Enum = None
self.Range = None
self.String = None
def _deserialize(self, params):
self.Type = params.get("Type")
self.Enum = params.get("Enum")
if params.get("Range") is not None:
self.Range = ConstraintRange()
self.Range._deserialize(params.get("Range"))
self.String = params.get("String")
class ParamDesc(AbstractModel):
"""DB参数描述
"""
def __init__(self):
"""
:param Param: 参数名字
:type Param: str
:param Value: 当前参数值
:type Value: str
:param SetValue: 设置过的值,参数生效后,该值和value一样。未设置过就不返回该字段。
注意:此字段可能返回 null,表示取不到有效值。
:type SetValue: str
:param Default: 系统默认值
:type Default: str
:param Constraint: 参数限制
:type Constraint: :class:`tencentcloud.dcdb.v20180411.models.ParamConstraint`
"""
self.Param = None
self.Value = None
self.SetValue = None
self.Default = None
self.Constraint = None
def _deserialize(self, params):
self.Param = params.get("Param")
self.Value = params.get("Value")
self.SetValue = params.get("SetValue")
self.Default = params.get("Default")
if params.get("Constraint") is not None:
self.Constraint = ParamConstraint()
self.Constraint._deserialize(params.get("Constraint"))
class ParamModifyResult(AbstractModel):
"""修改参数结果
"""
def __init__(self):
"""
:param Param: 修改参数名字
:type Param: str
:param Code: 参数修改结果。0表示修改成功;-1表示修改失败;-2表示该参数值非法
:type Code: int
"""
self.Param = None
self.Code = None
def _deserialize(self, params):
self.Param = params.get("Param")
self.Code = params.get("Code")
class RegionInfo(AbstractModel):
"""售卖可用区信息
"""
def __init__(self):
"""
:param Region: 地域英文ID
:type Region: str
:param RegionId: 地域数字ID
:type RegionId: int
:param RegionName: 地域中文名
:type RegionName: str
:param ZoneList: 可用区列表
:type ZoneList: list of ZonesInfo
:param AvailableChoice: 可选择的主可用区和从可用区
:type AvailableChoice: list of ShardZoneChooseInfo
"""
self.Region = None
self.RegionId = None
self.RegionName = None
self.ZoneList = None
self.AvailableChoice = None
def _deserialize(self, params):
self.Region = params.get("Region")
self.RegionId = params.get("RegionId")
self.RegionName = params.get("RegionName")
if params.get("ZoneList") is not None:
self.ZoneList = []
for item in params.get("ZoneList"):
obj = ZonesInfo()
obj._deserialize(item)
self.ZoneList.append(obj)
if params.get("AvailableChoice") is not None:
self.AvailableChoice = []
for item in params.get("AvailableChoice"):
obj = ShardZoneChooseInfo()
obj._deserialize(item)
self.AvailableChoice.append(obj)
class RenewDCDBInstanceRequest(AbstractModel):
"""RenewDCDBInstance请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待续费的实例ID。形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
:param Period: 续费时长,单位:月。
:type Period: int
:param AutoVoucher: 是否自动使用代金券进行支付,默认不使用。
:type AutoVoucher: bool
:param VoucherIds: 代金券ID列表,目前仅支持指定一张代金券。
:type VoucherIds: list of str
"""
self.InstanceId = None
self.Period = None
self.AutoVoucher = None
self.VoucherIds = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.Period = params.get("Period")
self.AutoVoucher = params.get("AutoVoucher")
self.VoucherIds = params.get("VoucherIds")
class RenewDCDBInstanceResponse(AbstractModel):
"""RenewDCDBInstance返回参数结构体
"""
def __init__(self):
"""
:param DealName: 长订单号。可以据此调用 DescribeOrders
查询订单详细信息,或在支付失败时调用用户账号相关接口进行支付。
:type DealName: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DealName = None
self.RequestId = None
def _deserialize(self, params):
self.DealName = params.get("DealName")
self.RequestId = params.get("RequestId")
class ResetAccountPasswordRequest(AbstractModel):
"""ResetAccountPassword请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 实例 ID,形如:dcdbt-ow728lmc。
:type InstanceId: str
:param UserName: 登录用户名。
:type UserName: str
:param Host: 用户允许的访问 host,用户名+host唯一确定一个账号。
:type Host: str
:param Password: 新密码,由字母、数字或常见符号组成,不能包含分号、单引号和双引号,长度为6~32位。
:type Password: str
"""
self.InstanceId = None
self.UserName = None
self.Host = None
self.Password = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UserName = params.get("UserName")
self.Host = params.get("Host")
self.Password = params.get("Password")
class ResetAccountPasswordResponse(AbstractModel):
"""ResetAccountPassword返回参数结构体
"""
def __init__(self):
"""
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.RequestId = None
def _deserialize(self, params):
self.RequestId = params.get("RequestId")
class ShardInfo(AbstractModel):
"""分片信息
"""
def __init__(self):
"""
:param ShardInstanceId: 分片ID
:type ShardInstanceId: str
:param ShardSerialId: 分片Set ID
:type ShardSerialId: str
:param Status: 状态:0 创建中,1 流程处理中, 2 运行中,3 分片未初始化,-2 分片已删除
:type Status: int
:param Createtime: 创建时间
:type Createtime: str
:param Memory: 内存大小,单位 GB
:type Memory: int
:param Storage: 存储大小,单位 GB
:type Storage: int
:param ShardId: 分片数字ID
:type ShardId: int
:param NodeCount: 节点数,2 为一主一从, 3 为一主二从
:type NodeCount: int
:param Pid: 产品类型 Id(过时字段,请勿依赖该值)
:type Pid: int
"""
self.ShardInstanceId = None
self.ShardSerialId = None
self.Status = None
self.Createtime = None
self.Memory = None
self.Storage = None
self.ShardId = None
self.NodeCount = None
self.Pid = None
def _deserialize(self, params):
self.ShardInstanceId = params.get("ShardInstanceId")
self.ShardSerialId = params.get("ShardSerialId")
self.Status = params.get("Status")
self.Createtime = params.get("Createtime")
self.Memory = params.get("Memory")
self.Storage = params.get("Storage")
self.ShardId = params.get("ShardId")
self.NodeCount = params.get("NodeCount")
self.Pid = params.get("Pid")
class ShardZoneChooseInfo(AbstractModel):
"""分片节点可用区选择
"""
def __init__(self):
"""
:param MasterZone: 主可用区
:type MasterZone: :class:`tencentcloud.dcdb.v20180411.models.ZonesInfo`
:param SlaveZones: 可选的从可用区
:type SlaveZones: list of ZonesInfo
"""
self.MasterZone = None
self.SlaveZones = None
def _deserialize(self, params):
if params.get("MasterZone") is not None:
self.MasterZone = ZonesInfo()
self.MasterZone._deserialize(params.get("MasterZone"))
if params.get("SlaveZones") is not None:
self.SlaveZones = []
for item in params.get("SlaveZones"):
obj = ZonesInfo()
obj._deserialize(item)
self.SlaveZones.append(obj)
class SpecConfig(AbstractModel):
"""按机型分类的规格配置
"""
def __init__(self):
"""
:param Machine: 规格机型
:type Machine: str
:param SpecConfigInfos: 规格列表
:type SpecConfigInfos: list of SpecConfigInfo
"""
self.Machine = None
self.SpecConfigInfos = None
def _deserialize(self, params):
self.Machine = params.get("Machine")
if params.get("SpecConfigInfos") is not None:
self.SpecConfigInfos = []
for item in params.get("SpecConfigInfos"):
obj = SpecConfigInfo()
obj._deserialize(item)
self.SpecConfigInfos.append(obj)
class SpecConfigInfo(AbstractModel):
"""实例可售卖规格详细信息,创建实例和扩容实例时 NodeCount、Memory 确定售卖规格,硬盘大小可用区间为[MinStorage,MaxStorage]
"""
def __init__(self):
"""
:param NodeCount: 节点个数,2 表示一主一从,3 表示一主二从
:type NodeCount: int
:param Memory: 内存大小,单位 GB
:type Memory: int
:param MinStorage: 数据盘规格最小值,单位 GB
:type MinStorage: int
:param MaxStorage: 数据盘规格最大值,单位 GB
:type MaxStorage: int
:param SuitInfo: 推荐的使用场景
:type SuitInfo: str
:param Pid: 产品类型 Id
:type Pid: int
:param Qps: 最大 Qps 值
:type Qps: int
"""
self.NodeCount = None
self.Memory = None
self.MinStorage = None
self.MaxStorage = None
self.SuitInfo = None
self.Pid = None
self.Qps = None
def _deserialize(self, params):
self.NodeCount = params.get("NodeCount")
self.Memory = params.get("Memory")
self.MinStorage = params.get("MinStorage")
self.MaxStorage = params.get("MaxStorage")
self.SuitInfo = params.get("SuitInfo")
self.Pid = params.get("Pid")
self.Qps = params.get("Qps")
class SplitShardConfig(AbstractModel):
"""升级实例 -- 切分分片类型
"""
def __init__(self):
"""
:param ShardInstanceIds: 分片ID数组
:type ShardInstanceIds: list of str
:param SplitRate: 数据切分比例
:type SplitRate: int
:param ShardMemory: 分片内存大小,单位 GB
:type ShardMemory: int
:param ShardStorage: 分片存储大小,单位 GB
:type ShardStorage: int
"""
self.ShardInstanceIds = None
self.SplitRate = None
self.ShardMemory = None
self.ShardStorage = None
def _deserialize(self, params):
self.ShardInstanceIds = params.get("ShardInstanceIds")
self.SplitRate = params.get("SplitRate")
self.ShardMemory = params.get("ShardMemory")
self.ShardStorage = params.get("ShardStorage")
class SqlLogItem(AbstractModel):
"""描述一条sql日志的详细信息。
"""
def __init__(self):
"""
:param Offset: 本条日志在消息队列中的偏移量。
:type Offset: int
:param User: 执行本条sql的用户。
:type User: str
:param Client: 执行本条sql的客户端IP+端口。
:type Client: str
:param DbName: 数据库名称。
:type DbName: str
:param Sql: 执行的sql语句。
:type Sql: str
:param SelectRowNum: 返回的数据行数。
:type SelectRowNum: int
:param AffectRowNum: 影响行数。
:type AffectRowNum: int
:param Timestamp: Sql执行时间戳。
:type Timestamp: int
:param TimeCostMs: Sql耗时,单位为毫秒。
:type TimeCostMs: int
:param ResultCode: Sql返回码,0为成功。
:type ResultCode: int
"""
self.Offset = None
self.User = None
self.Client = None
self.DbName = None
self.Sql = None
self.SelectRowNum = None
self.AffectRowNum = None
self.Timestamp = None
self.TimeCostMs = None
self.ResultCode = None
def _deserialize(self, params):
self.Offset = params.get("Offset")
self.User = params.get("User")
self.Client = params.get("Client")
self.DbName = params.get("DbName")
self.Sql = params.get("Sql")
self.SelectRowNum = params.get("SelectRowNum")
self.AffectRowNum = params.get("AffectRowNum")
self.Timestamp = params.get("Timestamp")
self.TimeCostMs = params.get("TimeCostMs")
self.ResultCode = params.get("ResultCode")
class TableColumn(AbstractModel):
"""数据库列信息
"""
def __init__(self):
"""
:param Col: 列名称
:type Col: str
:param Type: 列类型
:type Type: str
"""
self.Col = None
self.Type = None
def _deserialize(self, params):
self.Col = params.get("Col")
self.Type = params.get("Type")
class UpgradeDCDBInstanceRequest(AbstractModel):
"""UpgradeDCDBInstance请求参数结构体
"""
def __init__(self):
"""
:param InstanceId: 待升级的实例ID。形如:dcdbt-ow728lmc,可以通过 DescribeDCDBInstances 查询实例详情获得。
:type InstanceId: str
:param UpgradeType: 升级类型,取值范围:
<li> ADD: 新增分片 </li>
<li> EXPAND: 升级实例中的已有分片 </li>
<li> SPLIT: 将已有分片中的数据切分到新增分片上</li>
:type UpgradeType: str
:param AddShardConfig: 新增分片配置,当UpgradeType为ADD时生效。
:type AddShardConfig: :class:`tencentcloud.dcdb.v20180411.models.AddShardConfig`
:param ExpandShardConfig: 扩容分片配置,当UpgradeType为EXPAND时生效。
:type ExpandShardConfig: :class:`tencentcloud.dcdb.v20180411.models.ExpandShardConfig`
:param SplitShardConfig: 切分分片配置,当UpgradeType为SPLIT时生效。
:type SplitShardConfig: :class:`tencentcloud.dcdb.v20180411.models.SplitShardConfig`
:param AutoVoucher: 是否自动使用代金券进行支付,默认不使用。
:type AutoVoucher: bool
:param VoucherIds: 代金券ID列表,目前仅支持指定一张代金券。
:type VoucherIds: list of str
"""
self.InstanceId = None
self.UpgradeType = None
self.AddShardConfig = None
self.ExpandShardConfig = None
self.SplitShardConfig = None
self.AutoVoucher = None
self.VoucherIds = None
def _deserialize(self, params):
self.InstanceId = params.get("InstanceId")
self.UpgradeType = params.get("UpgradeType")
if params.get("AddShardConfig") is not None:
self.AddShardConfig = AddShardConfig()
self.AddShardConfig._deserialize(params.get("AddShardConfig"))
if params.get("ExpandShardConfig") is not None:
self.ExpandShardConfig = ExpandShardConfig()
self.ExpandShardConfig._deserialize(params.get("ExpandShardConfig"))
if params.get("SplitShardConfig") is not None:
self.SplitShardConfig = SplitShardConfig()
self.SplitShardConfig._deserialize(params.get("SplitShardConfig"))
self.AutoVoucher = params.get("AutoVoucher")
self.VoucherIds = params.get("VoucherIds")
class UpgradeDCDBInstanceResponse(AbstractModel):
"""UpgradeDCDBInstance返回参数结构体
"""
def __init__(self):
"""
:param DealName: 长订单号。可以据此调用 DescribeOrders
查询订单详细信息,或在支付失败时调用用户账号相关接口进行支付。
:type DealName: str
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。
:type RequestId: str
"""
self.DealName = None
self.RequestId = None
def _deserialize(self, params):
self.DealName = params.get("DealName")
self.RequestId = params.get("RequestId")
class ZonesInfo(AbstractModel):
"""可用区信息
"""
def __init__(self):
"""
:param Zone: 可用区英文ID
:type Zone: str
:param ZoneId: 可用区数字ID
:type ZoneId: int
:param ZoneName: 可用区中文名
:type ZoneName: str
"""
self.Zone = None
self.ZoneId = None
self.ZoneName = None
def _deserialize(self, params):
self.Zone = params.get("Zone")
self.ZoneId = params.get("ZoneId")
self.ZoneName = params.get("ZoneName")
| 28.549054
| 220
| 0.604426
|
4a0a800c4a1499ac4aaad12249fceb5a281cec43
| 28
|
py
|
Python
|
src/zig/utilities.py
|
rx-gan/zig
|
5bdbbbda85ff3ac85a0c7a91dc54d995602f9a96
|
[
"MIT"
] | null | null | null |
src/zig/utilities.py
|
rx-gan/zig
|
5bdbbbda85ff3ac85a0c7a91dc54d995602f9a96
|
[
"MIT"
] | null | null | null |
src/zig/utilities.py
|
rx-gan/zig
|
5bdbbbda85ff3ac85a0c7a91dc54d995602f9a96
|
[
"MIT"
] | 1
|
2021-07-14T15:37:38.000Z
|
2021-07-14T15:37:38.000Z
|
def generate_id():
pass
| 9.333333
| 18
| 0.642857
|
4a0a80694b3bdb69bd3c878708199e8db58e7aed
| 2,226
|
py
|
Python
|
openerp/addons/membership/__openerp__.py
|
ntiufalara/openerp7
|
903800da0644ec0dd9c1dcd34205541f84d45fe4
|
[
"MIT"
] | 3
|
2016-01-29T14:39:49.000Z
|
2018-12-29T22:42:00.000Z
|
openerp/addons/membership/__openerp__.py
|
ntiufalara/openerp7
|
903800da0644ec0dd9c1dcd34205541f84d45fe4
|
[
"MIT"
] | 2
|
2016-03-23T14:29:41.000Z
|
2017-02-20T17:11:30.000Z
|
openerp/addons/membership/__openerp__.py
|
ntiufalara/openerp7
|
903800da0644ec0dd9c1dcd34205541f84d45fe4
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Membership Management',
'version': '0.1',
'category': 'Association',
'description': """
This module allows you to manage all operations for managing memberships.
=========================================================================
It supports different kind of members:
--------------------------------------
* Free member
* Associated member (e.g.: a group subscribes to a membership for all subsidiaries)
* Paid members
* Special member prices
It is integrated with sales and accounting to allow you to automatically
invoice and send propositions for membership renewal.
""",
'author': 'OpenERP SA',
'depends': ['base', 'product', 'account', 'process'],
'data': [
'security/ir.model.access.csv',
'wizard/membership_invoice_view.xml',
'membership_view.xml',
'report/report_membership_view.xml',
'process/membership_process.xml',
],
'demo': ['membership_demo.xml'],
'test': ['test/test_membership.yml'],
'installable': True,
'auto_install': False,
'images': ['images/members.jpeg','images/membership_list.jpeg', 'images/membership_products.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| 39.052632
| 103
| 0.60602
|
4a0a8091969929c142f1852c849f706a15229c69
| 268
|
py
|
Python
|
homzhub_customization/homzhub_customization/doctype/bhk_multi_selecting_field/bhk_multi_selecting_field.py
|
HPL-ERP/homzhub_customization
|
311364116aa61fc00b263c78ffbb6d3946cff154
|
[
"MIT"
] | null | null | null |
homzhub_customization/homzhub_customization/doctype/bhk_multi_selecting_field/bhk_multi_selecting_field.py
|
HPL-ERP/homzhub_customization
|
311364116aa61fc00b263c78ffbb6d3946cff154
|
[
"MIT"
] | null | null | null |
homzhub_customization/homzhub_customization/doctype/bhk_multi_selecting_field/bhk_multi_selecting_field.py
|
HPL-ERP/homzhub_customization
|
311364116aa61fc00b263c78ffbb6d3946cff154
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Homzhub and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
# import frappe
from frappe.model.document import Document
class BHKMultiSelectingField(Document):
pass
| 24.363636
| 49
| 0.783582
|
4a0a8222a76b0b8d3d7b5d018c15c9c84f3388d6
| 1,818
|
py
|
Python
|
tests/src/conf/test_settings_class.py
|
lxbrvr/alfred-keepassxc-workflow
|
ae05c675cd762cd841e40f19795137eea58a2764
|
[
"MIT"
] | 8
|
2021-08-17T00:44:54.000Z
|
2022-02-09T13:43:15.000Z
|
tests/src/conf/test_settings_class.py
|
lxbrvr/alfred-keepassxc-workflow
|
ae05c675cd762cd841e40f19795137eea58a2764
|
[
"MIT"
] | 7
|
2021-12-05T02:59:10.000Z
|
2022-03-27T18:03:47.000Z
|
tests/src/conf/test_settings_class.py
|
lxbrvr/alfred-keepassxc-workflow
|
ae05c675cd762cd841e40f19795137eea58a2764
|
[
"MIT"
] | null | null | null |
import pytest
from contextlib2 import ExitStack
from conf import RequiredFieldException
class TestIsValidMethod(object):
@pytest.mark.parametrize(
"raised_exception, expected_result",
[
(RequiredFieldException, False),
(lambda: None, True),
]
)
def test(self, raised_exception, expected_result, settings_factory, mocker):
settings = settings_factory()
mocker.patch.object(settings, "validate", side_effect=raised_exception)
assert settings.is_valid() == expected_result
class TestValidateMethod(object):
@pytest.mark.parametrize(
"alfred_keyword, keepassxc_cli_path, keepassxc_db_path, keychain_account, keychain_service, expected_exception",
[
(None, None, None, None, None, pytest.raises(RequiredFieldException)),
("1", None, None, None, None, pytest.raises(RequiredFieldException)),
("1", "1", None, None, None, pytest.raises(RequiredFieldException)),
("1", "1", "1", None, None, pytest.raises(RequiredFieldException)),
("1", "1", "1", "1", None, pytest.raises(RequiredFieldException)),
("1", "1", "1", "1", "1", ExitStack()),
]
)
def test_required_attributes(
self,
settings_factory,
alfred_keyword,
keepassxc_db_path,
keepassxc_cli_path,
keychain_account,
keychain_service,
expected_exception,
):
settings = settings_factory(
alfred_keyword=alfred_keyword,
keepassxc_cli_path=keepassxc_cli_path,
keepassxc_db_path=keepassxc_db_path,
keychain_service=keychain_service,
keychain_account=keychain_account,
)
with expected_exception:
settings.validate()
| 33.666667
| 120
| 0.636414
|
4a0a84f13ff12576a86c24c0a120cab93dc0afe5
| 719
|
py
|
Python
|
apps/materials/forms.py
|
JuanJoseStone/shoe-app
|
b9eb10e59877d6eb0582b65cf1b91cdd47bdcdb0
|
[
"MIT"
] | null | null | null |
apps/materials/forms.py
|
JuanJoseStone/shoe-app
|
b9eb10e59877d6eb0582b65cf1b91cdd47bdcdb0
|
[
"MIT"
] | null | null | null |
apps/materials/forms.py
|
JuanJoseStone/shoe-app
|
b9eb10e59877d6eb0582b65cf1b91cdd47bdcdb0
|
[
"MIT"
] | null | null | null |
from django import forms
from .models import Material
class MaterialForm(forms.ModelForm):
def clean_name(self):
try:
model = Material.objects.get(
name__iexact=self.cleaned_data['name'].strip())
if not self.instance.pk:
raise forms.ValidationError('Ya existe un material con este nombre')
elif self.instance.pk != model.pk:
raise forms.ValidationError(
'Cambio no permitido un material con este nombre ya existe')
except Material.DoesNotExist:
pass
return self.cleaned_data['name']
class Meta:
model = Material
fields = '__all__'
| 32.681818
| 85
| 0.584145
|
4a0a851e99f681e6178d000e4c21c3cc6e088671
| 879
|
py
|
Python
|
modules/call_back_query_module.py
|
WhereIsTheExit/HeinzBot
|
1e35f1706d03b47dddfa8b8a04cede6a7c4be301
|
[
"Apache-2.0"
] | 6
|
2019-05-12T13:30:48.000Z
|
2020-07-30T08:58:10.000Z
|
modules/call_back_query_module.py
|
WhereIsTheExit/HeinzBot
|
1e35f1706d03b47dddfa8b8a04cede6a7c4be301
|
[
"Apache-2.0"
] | 16
|
2019-05-11T14:07:06.000Z
|
2021-11-29T22:13:35.000Z
|
modules/call_back_query_module.py
|
WhereIsTheExit/HeinzBot
|
1e35f1706d03b47dddfa8b8a04cede6a7c4be301
|
[
"Apache-2.0"
] | 5
|
2019-05-11T13:29:47.000Z
|
2020-01-15T12:18:40.000Z
|
from telegram import Update
from telegram.ext import CallbackContext, DispatcherHandlerStop
from modules.abstract_module import AbstractModule
from utils.decorators import register_module, register_callback_query_handler
@register_module()
class CallBackModule(AbstractModule):
@register_callback_query_handler(command="master", master=True)
def check_callbacks(self, update: Update, context: CallbackContext):
group = 3 # CallBackQueryHandler Queue
handlers = context.dispatcher.handlers
for handler in handlers[group]:
check = handler.check_update(update)
if check is not None and check is not False:
handler.handle_update(update, context.dispatcher, check, context)
raise DispatcherHandlerStop()
update.callback_query.message.reply_text("Herst Lorent, hab i mid dia gredt?")
| 41.857143
| 86
| 0.74289
|
4a0a85b5dbc5aca1746070a5604dfcc072ef2469
| 1,298
|
py
|
Python
|
teamcat_service/docker_build/target/one_step_build/teamcat/gatesidelib/filehelper.py
|
zhangyin2088/Teamcat
|
be9be8d7c1e58c8d2d22ab78d25783d9aee4de71
|
[
"Apache-2.0"
] | 6
|
2018-11-26T08:42:52.000Z
|
2020-06-01T08:33:48.000Z
|
teamcat_service/docker_build/target/one_step_build/teamcat/gatesidelib/filehelper.py
|
zhangyin2088/Teamcat
|
be9be8d7c1e58c8d2d22ab78d25783d9aee4de71
|
[
"Apache-2.0"
] | null | null | null |
teamcat_service/docker_build/target/one_step_build/teamcat/gatesidelib/filehelper.py
|
zhangyin2088/Teamcat
|
be9be8d7c1e58c8d2d22ab78d25783d9aee4de71
|
[
"Apache-2.0"
] | 1
|
2019-01-22T06:45:36.000Z
|
2019-01-22T06:45:36.000Z
|
#coding=utf-8
#coding=utf-8
'''
Created on 2014-12-10
@author: Devuser
'''
from gatesidelib.common.simplelogger import SimpleLogger
import os
import stat
import shutil
class FileHelper(object):
@staticmethod
def write_lines(filename,linelist):
filehandler=open(filename,'w')
filehandler.writelines(linelist)
filehandler.close()
@staticmethod
def read_lines(filename):
filehandler=open(filename,'r')
result=filehandler.readlines()
filehandler.close()
return result
@staticmethod
def get_linecounts(filename):
count=0
filehandler=open(filename,'rb')
while True:
buffer=filehandler.read(1024*8192)
if not buffer:
break
count +=buffer.count('\n')
filehandler.close()
return count
@staticmethod
def delete_file(filename):
if os.path.isfile(filename):
os.remove(filename)
@staticmethod
def delete_dir_all(dirpath):
try:
shutil.rmtree(dirpath)
except Exception as ex:
SimpleLogger.error(ex)
@staticmethod
def delete_empty_dir(dirpath):
if os.path.exists(dirpath):
os.rmdir(dirpath)
| 22.37931
| 56
| 0.601695
|
4a0a85d475a1769a8ae50f636d22f4d5f46d8201
| 1,360
|
py
|
Python
|
split_data_legacy.py
|
googleinterns/gail-dyn
|
31c93b12d068dede0dbe69547f0b2e500374f260
|
[
"Apache-2.0"
] | null | null | null |
split_data_legacy.py
|
googleinterns/gail-dyn
|
31c93b12d068dede0dbe69547f0b2e500374f260
|
[
"Apache-2.0"
] | null | null | null |
split_data_legacy.py
|
googleinterns/gail-dyn
|
31c93b12d068dede0dbe69547f0b2e500374f260
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://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 language governing permissions and
# limitations under the License.
import gzip, pickle, pickletools
all_trajs_split = {}
with open("./laika_23_softfloor_n200.pkl", "rb") as handle:
saved_file = pickle.load(handle)
n_trajs = len(saved_file)
for traj_idx, traj_tuples in saved_file.items():
traj_tuples_split = []
for traj_tuple in traj_tuples:
assert len(traj_tuple) == 116
traj_tuple_split = [
traj_tuple[:52],
traj_tuple[52:64],
traj_tuple[64:116]
]
traj_tuples_split.append(traj_tuple_split)
all_trajs_split[traj_idx] = traj_tuples_split
with open("./laika_23_softfloor_n200_split.pkl", "wb") as handle:
# print(all_trajs)
pickle.dump(all_trajs_split, handle, protocol=pickle.HIGHEST_PROTOCOL)
| 34.871795
| 75
| 0.688235
|
4a0a86ab6c834c62a235974efc39a9c05c70752c
| 3,985
|
py
|
Python
|
cframework/longbow/src/python/longbow-coverage-report.py
|
cherouvim/cicn-nrs
|
440d6a7f56e7240f179205ed5ce1fe8000d03b83
|
[
"Apache-2.0"
] | 10
|
2018-11-04T06:37:14.000Z
|
2022-02-18T00:26:34.000Z
|
cframework/longbow/src/python/longbow-coverage-report.py
|
cherouvim/cicn-nrs
|
440d6a7f56e7240f179205ed5ce1fe8000d03b83
|
[
"Apache-2.0"
] | null | null | null |
cframework/longbow/src/python/longbow-coverage-report.py
|
cherouvim/cicn-nrs
|
440d6a7f56e7240f179205ed5ce1fe8000d03b83
|
[
"Apache-2.0"
] | 3
|
2019-01-17T19:47:55.000Z
|
2022-02-18T00:28:18.000Z
|
#! /usr/bin/env python
# Copyright (c) 2017 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
#
#
import sys
import argparse
sys.path.append("@INSTALL_PYTHON_DIR@")
sys.path.append("@DEPENDENCY_PYTHON_DIR@")
sys.path.append("../site-packages/longbow/")
import CoverageReport
if __name__ == '__main__':
'''
@(#) longbow-coverage-report @VERSION@ @DATE@
@(#) All Rights Reserved. Use is subject to license terms.
'''
description = '''
longbow-coverage-report @VERSION@ @DATE@
All Rights Reserved. Use is subject to license terms.
Report on the code coverage of tests.
The source files or executables to analyse are supplied as command line parameters,
or as a list of newline separated file names read from standard input.
Output is plain-text (default --output text) or a CSV file (--output csv)
reporting the results.
Results are:
An average of all files specified (--average)
A one line summary of all files specified (--summary)
A listing of the original source file, colorized showing tested and non-tested lines.
'''
parser = argparse.ArgumentParser(prog='longbow-coverage-report',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=description)
parser.add_argument('-', '--stdin', default=False, action="store_true", required=False,
help="Read the list of files from standard input.")
parser.add_argument('-s', '--summary', default=False, action="store_true", required=False,
help="Display the score for each file (excluding test source files).")
parser.add_argument('-a', '--average', default=False, action="store_true", required=False,
help="Display the average score for all C source files (excluding test source files).")
parser.add_argument('-o', '--output', default="text", action="store", required=False, type=str,
help="Set the output format: \"text\" or \"csv\"")
parser.add_argument('-v', '--visual', default=False, action="store_true", required=False,
help="Colorize the original source code showing coverage")
parser.add_argument('-x', '--explain', default=False, action="store_true", required=False,
help="Display information about the collection of coverage information (guru mode).")
parser.add_argument('-d', '--distribution', default="[95, 90]", action="store", required=False, type=str,
help="A list containing the score distributions for pretty-printing. Default [95, 90]")
parser.add_argument('-T', '--includeTestSources', default=False, action="store_true", required=False,
help="Include analysis of the test sources. Default False")
parser.add_argument('-t', '--testDir', default="", action="store", required=False, type=str,
help="Directory hint for locating test files.")
parser.add_argument("files", help="Files to check", nargs="*")
args = parser.parse_args()
if not args.summary and not args.average and not args.visual and not args.explain:
args.summary = True
fileNames = []
if args.stdin:
for line in sys.stdin:
t = line.strip()
if len(t) > 0:
fileNames.append(t)
else:
fileNames = args.files
CoverageReport.commandLineMain(args, fileNames, args.testDir)
| 45.284091
| 111
| 0.667754
|
4a0a86b01be5c1688690de2b7f76503c76c206b1
| 5,595
|
py
|
Python
|
bin/data/make_aws_archive/import_cv.py
|
dijksterhuis/cleverSpeech
|
aba8607ffa28e6be48e028e156d46254db19ad88
|
[
"MIT"
] | 3
|
2021-09-07T22:45:36.000Z
|
2022-01-01T16:59:57.000Z
|
bin/data/make_aws_archive/import_cv.py
|
dijksterhuis/cleverSpeech
|
aba8607ffa28e6be48e028e156d46254db19ad88
|
[
"MIT"
] | 4
|
2021-01-26T19:22:29.000Z
|
2021-12-31T14:38:12.000Z
|
bin/data/make_aws_archive/import_cv.py
|
dijksterhuis/cleverSpeech
|
aba8607ffa28e6be48e028e156d46254db19ad88
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
# Make sure we can import stuff from util/
# This script needs to be run from the root of the DeepSpeech repository
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import csv
import tarfile
import subprocess
import progressbar
from glob import glob
from os import path
from sox import Transformer
from threading import RLock
from multiprocessing.dummy import Pool
from multiprocessing import cpu_count
from util.downloader import maybe_download, SIMPLE_BAR
FIELDNAMES = ['wav_filename', 'wav_filesize', 'transcript']
SAMPLE_RATE = 16000
MAX_SECS = 10
ARCHIVE_DIR_NAME = 'cv_corpus_v1'
ARCHIVE_NAME = ARCHIVE_DIR_NAME + '.tar.gz'
ARCHIVE_URL = 'https://s3.us-east-2.amazonaws.com/common-voice-data-download/' + ARCHIVE_NAME
#########################################################
# Note from MR: #
# I've only changed the progressbar lines as my version #
# of progressbar has `maxval` as an argument and *not* #
# `max_value` as per the DeepSpeech implementation #
#########################################################
def _download_and_preprocess_data(target_dir):
# Making path absolute
target_dir = path.abspath(target_dir)
# Conditionally download data
archive_path = maybe_download(ARCHIVE_NAME, target_dir, ARCHIVE_URL)
# Conditionally extract common voice data
_maybe_extract(target_dir, ARCHIVE_DIR_NAME, archive_path)
# Conditionally convert common voice CSV files and mp3 data to DeepSpeech CSVs and wav
_maybe_convert_sets(target_dir, ARCHIVE_DIR_NAME)
def _maybe_extract(target_dir, extracted_data, archive_path):
# If target_dir/extracted_data does not exist, extract archive in target_dir
extracted_path = path.join(target_dir, extracted_data)
if not path.exists(extracted_path):
print('No directory "%s" - extracting archive...' % extracted_path)
with tarfile.open(archive_path) as tar:
tar.extractall(target_dir)
else:
print('Found directory "%s" - not extracting it from archive.' % extracted_path)
def _maybe_convert_sets(target_dir, extracted_data):
extracted_dir = path.join(target_dir, extracted_data)
for source_csv in glob(path.join(extracted_dir, '*.csv')):
_maybe_convert_set(extracted_dir, source_csv, path.join(target_dir, os.path.split(source_csv)[-1]))
def _maybe_convert_set(extracted_dir, source_csv, target_csv):
print()
if path.exists(target_csv):
print('Found CSV file "%s" - not importing "%s".' % (target_csv, source_csv))
return
print('No CSV file "%s" - importing "%s"...' % (target_csv, source_csv))
samples = []
with open(source_csv) as source_csv_file:
reader = csv.DictReader(source_csv_file)
for row in reader:
samples.append((row['filename'], row['text']))
# Mutable counters for the concurrent embedded routine
counter = { 'all': 0, 'too_short': 0, 'too_long': 0 }
lock = RLock()
num_samples = len(samples)
rows = []
def one_sample(sample):
mp3_filename = path.join(*(sample[0].split('/')))
mp3_filename = path.join(extracted_dir, mp3_filename)
# Storing wav files next to the mp3 ones - just with a different suffix
wav_filename = path.splitext(mp3_filename)[0] + ".wav"
_maybe_convert_wav(mp3_filename, wav_filename)
frames = int(subprocess.check_output(['soxi', '-s', wav_filename], stderr=subprocess.STDOUT))
file_size = path.getsize(wav_filename)
with lock:
if int(frames/SAMPLE_RATE*1000/10/2) < len(str(sample[1])):
# Excluding samples that are too short to fit the transcript
counter['too_short'] += 1
elif frames/SAMPLE_RATE > MAX_SECS:
# Excluding very long samples to keep a reasonable batch-size
counter['too_long'] += 1
else:
# This one is good - keep it for the target CSV
rows.append((wav_filename, file_size, sample[1]))
counter['all'] += 1
print('Importing mp3 files...')
pool = Pool(cpu_count())
bar = progressbar.ProgressBar(maxval=num_samples, widgets=SIMPLE_BAR)
for i, _ in enumerate(pool.imap_unordered(one_sample, samples), start=1):
bar.update(i)
bar.update(num_samples)
pool.close()
pool.join()
print('Writing "%s"...' % target_csv)
with open(target_csv, 'w') as target_csv_file:
writer = csv.DictWriter(target_csv_file, fieldnames=FIELDNAMES)
writer.writeheader()
bar = progressbar.ProgressBar(maxval=len(rows), widgets=SIMPLE_BAR)
for filename, file_size, transcript in bar(rows):
writer.writerow({ 'wav_filename': filename, 'wav_filesize': file_size, 'transcript': transcript })
print('Imported %d samples.' % (counter['all'] - counter['too_short'] - counter['too_long']))
if counter['too_short'] > 0:
print('Skipped %d samples that were too short to match the transcript.' % counter['too_short'])
if counter['too_long'] > 0:
print('Skipped %d samples that were longer than %d seconds.' % (counter['too_long'], MAX_SECS))
def _maybe_convert_wav(mp3_filename, wav_filename):
if not path.exists(wav_filename):
transformer = Transformer()
transformer.convert(samplerate=SAMPLE_RATE)
transformer.build(mp3_filename, wav_filename)
if __name__ == "__main__":
_download_and_preprocess_data(sys.argv[1])
| 42.386364
| 110
| 0.673816
|
4a0a86ca6bce1b0e35f5edc08e8cd799b94179df
| 700
|
py
|
Python
|
python/api_preprocess.py
|
PetalTech/petal-api-getting-started
|
d77eed5d414a6d9036b91992171e0e3e025199cc
|
[
"MIT"
] | 2
|
2020-09-29T16:39:34.000Z
|
2021-04-25T22:28:04.000Z
|
python/api_preprocess.py
|
PetalTech/petal-api-getting-started
|
d77eed5d414a6d9036b91992171e0e3e025199cc
|
[
"MIT"
] | 1
|
2022-01-13T23:19:24.000Z
|
2022-01-13T23:19:24.000Z
|
python/api_preprocess.py
|
PetalTech/petal-api-getting-started
|
d77eed5d414a6d9036b91992171e0e3e025199cc
|
[
"MIT"
] | null | null | null |
'''
This script contains an example of a preprocessed data Petal Metrics API call.
You will need a valid developer API key to access.
Usage: python api_preprocess.py -k $API_KEY
'''
import argparse
import random
import api
parser = argparse.ArgumentParser()
parser.add_argument('-k', '--api_key', type=str, required=True,
help='API key for the Petal Metrics API')
args = parser.parse_args()
random_eeg_data = [
[random.randint(0,100) / 100 for i in range(150)]
for num in range(4)
]
calculations = api.request_metrics(
api_key=args.api_key,
eeg_data=random_eeg_data,
metrics=['preprocessed_data'],
)
print(calculations['data'])
| 25
| 79
| 0.682857
|
4a0a87ce73525dc27ce39c2c7848b0da6fa2e080
| 535
|
py
|
Python
|
setup.py
|
gameduell/parallelpandas
|
967fba7a37247897001dbe0c065820ef511acb12
|
[
"MIT"
] | 1
|
2016-05-26T07:58:58.000Z
|
2016-05-26T07:58:58.000Z
|
setup.py
|
gameduell/parallelpandas
|
967fba7a37247897001dbe0c065820ef511acb12
|
[
"MIT"
] | null | null | null |
setup.py
|
gameduell/parallelpandas
|
967fba7a37247897001dbe0c065820ef511acb12
|
[
"MIT"
] | null | null | null |
from setuptools import setup, find_packages
setup(
name = "parallelpandas",
version = "0.1",
packages = find_packages(),
scripts = [],
install_requires=['dill>=0.2',
'pandas>=0.14'],
# metadata for upload to PyPI
author = "Philipp Metzner",
author_email = "philipp.metzner@gameduell.de",
description = "parallel version of some pandas function",
license = "MIT",
keywords = "pandas mutliprocessing parallel",
url = "https://github.com/GameDuell/parallelpandas",
)
| 29.722222
| 61
| 0.639252
|
4a0a8834afbdddec0840ecba04bbb745f403d3b3
| 245
|
py
|
Python
|
anagrams count.py
|
sundar369/coding
|
d5e99623f055a39604351752d494c1c8817d6d91
|
[
"MIT"
] | null | null | null |
anagrams count.py
|
sundar369/coding
|
d5e99623f055a39604351752d494c1c8817d6d91
|
[
"MIT"
] | null | null | null |
anagrams count.py
|
sundar369/coding
|
d5e99623f055a39604351752d494c1c8817d6d91
|
[
"MIT"
] | null | null | null |
lst1 = list(input().split())
lst2 = list(input().split())
for i in range(len(lst1)):
lst1[i] = "".join(sorted(lst1[i]))
for i in range(len(lst2)):
lst2[i] = "".join(sorted(lst2[i]))
count = 0
for i in lst1:
if i in lst2: count+=1
print(count)
| 24.5
| 35
| 0.62449
|
4a0a892fa51c2d80661d2778b8d5643f5ff12153
| 52
|
py
|
Python
|
hra.py
|
barcza/piskvorky1d
|
00bd5ab2c2c57e3520a8d8476e7015ab7e222667
|
[
"MIT"
] | null | null | null |
hra.py
|
barcza/piskvorky1d
|
00bd5ab2c2c57e3520a8d8476e7015ab7e222667
|
[
"MIT"
] | null | null | null |
hra.py
|
barcza/piskvorky1d
|
00bd5ab2c2c57e3520a8d8476e7015ab7e222667
|
[
"MIT"
] | null | null | null |
import ai
import piskvorky
piskvorky.piskvorky1d()
| 10.4
| 23
| 0.826923
|
4a0a8a822108336f379a76b7c1f7cc82c1be708b
| 574
|
py
|
Python
|
gmap_tagging.py
|
shelvi31/Gmap-Google-Map-Tagging
|
1cb1614b6c06eb1404a7b5a7a0047777e5c99970
|
[
"Apache-2.0"
] | null | null | null |
gmap_tagging.py
|
shelvi31/Gmap-Google-Map-Tagging
|
1cb1614b6c06eb1404a7b5a7a0047777e5c99970
|
[
"Apache-2.0"
] | null | null | null |
gmap_tagging.py
|
shelvi31/Gmap-Google-Map-Tagging
|
1cb1614b6c06eb1404a7b5a7a0047777e5c99970
|
[
"Apache-2.0"
] | null | null | null |
import pandas as pd
import gmplot
data = pd.read_csv('spatial_network.csv')
data.head()
# latitude and longitude list
latitude_list = data['LATITUDE']
longitude_list = data['LONGITUDE']
# center co-ordinates of the map
gmap = gmplot.GoogleMapPlotter( 56.730876,9.349849,9)
# plot the co-ordinates on the google map
gmap.scatter( latitude_list, longitude_list, 'red', size = 40, marker = True)
# the following code will create the html file view that in your web browser
gmap.heatmap(latitude_list, longitude_list)
gmap.draw( "mymap.html" )
| 27.333333
| 79
| 0.724739
|
4a0a8d4d1b0ea68bb1fa7614f6d7e8bd977327ff
| 1,481
|
py
|
Python
|
cate/util/undefined.py
|
strawpants/cate
|
eeef7da204b2f5c6dab1a90cb240aa5158c44513
|
[
"MIT"
] | 34
|
2017-09-28T19:08:59.000Z
|
2022-02-09T14:53:26.000Z
|
cate/util/undefined.py
|
strawpants/cate
|
eeef7da204b2f5c6dab1a90cb240aa5158c44513
|
[
"MIT"
] | 608
|
2017-09-25T20:29:52.000Z
|
2022-03-28T11:02:21.000Z
|
cate/util/undefined.py
|
strawpants/cate
|
eeef7da204b2f5c6dab1a90cb240aa5158c44513
|
[
"MIT"
] | 14
|
2017-10-16T07:34:59.000Z
|
2021-02-22T15:52:37.000Z
|
# The MIT License (MIT)
# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
__author__ = "Norman Fomferra (Brockmann Consult GmbH)"
class _Undefined:
"""
Represents the UNDEFINED value.
"""
def __str__(self):
return "UNDEFINED"
def __repr__(self):
return "UNDEFINED"
#: Singleton value used to indicate an undefined state.
UNDEFINED = _Undefined()
| 37.025
| 83
| 0.753545
|
4a0a8d716da14e1d5c89cd169ac05a0c488bc9d6
| 613
|
py
|
Python
|
setup.py
|
idel906/algofi-amm-py-sdk
|
eb5df585c6b890e4d948324c8a3ebf2fd8bc68d2
|
[
"MIT"
] | null | null | null |
setup.py
|
idel906/algofi-amm-py-sdk
|
eb5df585c6b890e4d948324c8a3ebf2fd8bc68d2
|
[
"MIT"
] | null | null | null |
setup.py
|
idel906/algofi-amm-py-sdk
|
eb5df585c6b890e4d948324c8a3ebf2fd8bc68d2
|
[
"MIT"
] | null | null | null |
import setuptools
with open("README.md", "r") as f:
long_description = f.read()
setuptools.setup(
name="algofi-amm-py-sdk",
description="Algofi AMM Python SDK",
author="Algofi",
author_email="founders@algofi.org",
version="0.0.6",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
project_urls={
"Source": "https://github.com/Algofiorg/algofi-amm-py-sdk",
},
install_requires=["py-algorand-sdk >= 1.6.0"],
packages=setuptools.find_packages(),
python_requires=">=3.7",
include_package_data=True
)
| 26.652174
| 67
| 0.672104
|
4a0a8de75892ade7a78f06bcbe7f82751c673698
| 4,521
|
py
|
Python
|
python_packages_static/pydrograph/attributes.py
|
usgs/neversink_workflow
|
acd61435b8553e38d4a903c8cd7a3afc612446f9
|
[
"CC0-1.0"
] | 5
|
2020-05-11T16:05:38.000Z
|
2021-11-03T22:01:24.000Z
|
python_packages_static/pydrograph/attributes.py
|
usgs/neversink_workflow
|
acd61435b8553e38d4a903c8cd7a3afc612446f9
|
[
"CC0-1.0"
] | 7
|
2020-08-19T15:53:54.000Z
|
2022-03-31T21:56:22.000Z
|
python_packages_static/pydrograph/attributes.py
|
usgs/neversink_workflow
|
acd61435b8553e38d4a903c8cd7a3afc612446f9
|
[
"CC0-1.0"
] | 6
|
2020-07-31T16:00:03.000Z
|
2022-03-04T20:54:57.000Z
|
# site_no -- Site identification number
# station_nm -- Site name
# site_tp_cd -- Site type
# lat_va -- DMS latitude
# long_va -- DMS longitude
# dec_lat_va -- Decimal latitude
# dec_long_va -- Decimal longitude
# coord_meth_cd -- Latitude-longitude method
# coord_acy_cd -- Latitude-longitude accuracy
# coord_datum_cd -- Latitude-longitude datum
# dec_coord_datum_cd -- Decimal Latitude-longitude datum
# district_cd -- District code
# state_cd -- State code
# county_cd -- County code
# country_cd -- Country code
# land_net_ds -- Land net location description
# map_nm -- Name of location map
# map_scale_fc -- Scale of location map
# alt_va -- Altitude of Gage/land surface
# alt_meth_cd -- Method altitude determined
# alt_acy_va -- Altitude accuracy
# alt_datum_cd -- Altitude datum
# huc_cd -- Hydrologic unit code
# basin_cd -- Drainage basin code
# topo_cd -- Topographic setting code
# data_types_cd -- Flags for the type of data collected
# instruments_cd -- Flags for instruments at site
# construction_dt -- Date of first construction
# inventory_dt -- Date site established or inventoried
# drain_area_va -- Drainage area
# contrib_drain_area_va -- Contributing drainage area
# tz_cd -- Mean Greenwich time offset
# local_time_fg -- Local standard time flag
# reliability_cd -- Data reliability code
# gw_file_cd -- Data-other GW files
# nat_aqfr_cd -- National aquifer code
# aqfr_cd -- Local aquifer code
# aqfr_type_cd -- Local aquifer type code
# well_depth_va -- Well depth
# hole_depth_va -- Hole depth
# depth_src_cd -- Source of depth data
# project_no -- Project number
# rt_bol -- Real-time data flag
# peak_begin_date -- Peak-streamflow data begin date
# peak_end_date -- Peak-streamflow data end date
# peak_count_nu -- Peak-streamflow data count
# qw_begin_date -- Water-quality data begin date
# qw_end_date -- Water-quality data end date
# qw_count_nu -- Water-quality data count
# gw_begin_date -- Field water-level measurements begin date
# gw_end_date -- Field water-level measurements end date
# gw_count_nu -- Field water-level measurements count
# sv_begin_date -- Site-visit data begin date
# sv_end_date -- Site-visit data end date
# sv_count_nu -- Site-visit data count
streamflow_attributes = [ \
'site_no',
'station_nm',
'site_tp_cd',
'dec_lat_va',
'dec_long_va',
'coord_meth_cd',
'coord_acy_cd',
'coord_datum_cd',
'dec_coord_datum_cd',
'district_cd',
'state_cd',
'county_cd',
'country_cd',
'land_net_ds',
'map_nm',
'map_scale_fc',
'alt_va',
'alt_meth_cd',
'alt_acy_va',
'alt_datum_cd',
'huc_cd',
'basin_cd',
'topo_cd',
'inventory_dt',
'drain_area_va',
'contrib_drain_area_va',
'tz_cd',
'local_time_fg',
'reliability_cd',
'project_no',
'rt_bol',
'peak_begin_date',
'peak_end_date',
'peak_count_nu',
'qw_begin_date',
'qw_end_date',
'qw_count_nu',
'sv_begin_date',
'sv_end_date',
'sv_count_nu']
iv_attributes = [ \
'agency_cd',
'site_no',
'station_nm',
'site_tp_cd',
'dec_lat_va',
'dec_long_va',
'coord_acy_cd',
'dec_coord_datum_cd',
'alt_va',
'alt_acy_va',
'alt_datum_cd',
'huc_cd',
'data_type_cd',
'parm_cd',
'stat_cd',
'ts_id',
'loc_web_ds',
'medium_grp_cd',
'parm_grp_cd',
'srs_id',
'access_cd',
'begin_date',
'end_date',
'count_nu']
gw_attributes = [
'site_no',
'station_nm',
'site_tp_cd',
'dec_lat_va',
'dec_long_va',
'coord_meth_cd',
'coord_acy_cd',
'coord_datum_cd',
'dec_coord_datum_cd',
'district_cd',
'state_cd',
'county_cd',
'country_cd',
'land_net_ds',
'map_nm',
'map_scale_fc',
'alt_va',
'alt_meth_cd',
'alt_acy_va',
'alt_datum_cd',
'huc_cd',
'basin_cd',
'topo_cd',
'data_types_cd',
'instruments_cd',
'construction_dt',
'inventory_dt',
'tz_cd',
'local_time_fg',
'reliability_cd',
'gw_file_cd',
'nat_aqfr_cd',
'aqfr_cd',
'aqfr_type_cd',
'well_depth_va',
'hole_depth_va',
'depth_src_cd',
'project_no',
'rt_bol',
'peak_begin_date',
'peak_end_date',
'peak_count_nu',
'qw_begin_date',
'qw_end_date',
'qw_count_nu',
'gw_begin_date',
'gw_end_date',
'gw_count_nu',
'sv_begin_date',
'sv_end_date',
'sv_count_nu'
]
| 25.398876
| 63
| 0.653616
|
4a0a8e88e3421d87979f0dbcc0c29bc94446ef54
| 3,420
|
py
|
Python
|
opendata/requests/views.py
|
OpenData-NC/open-data-nc
|
5e1964d5c986f79055e6f018f0f2f9a15a3eaf99
|
[
"MIT"
] | 5
|
2015-10-31T02:01:24.000Z
|
2021-03-02T12:34:59.000Z
|
opendata/requests/views.py
|
OpenData-NC/open-data-nc
|
5e1964d5c986f79055e6f018f0f2f9a15a3eaf99
|
[
"MIT"
] | null | null | null |
opendata/requests/views.py
|
OpenData-NC/open-data-nc
|
5e1964d5c986f79055e6f018f0f2f9a15a3eaf99
|
[
"MIT"
] | 4
|
2016-04-05T06:07:15.000Z
|
2020-10-18T01:17:17.000Z
|
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_POST
from django.views.generic import DetailView
from django.shortcuts import render, redirect, get_object_or_404
from djangoratings.exceptions import CannotDeleteVote
from .forms import SearchForm, RequestForm
from .models import Request
def list_requests(request):
"""List current requests"""
requests = Request.objects.filter(status=Request.APPROVED).order_by("-rating_score")
if request.method == 'GET':
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['text']
requests = requests.filter(title__icontains=query)
else:
form = SearchForm()
context = {
'form': form,
'requests': requests,
}
return render(request, 'requests/list.html', context)
class RequestDetailView(DetailView):
model = Request
def get_queryset(self):
qs = super(RequestDetailView, self).get_queryset()
return qs.filter(status=self.model.APPROVED)
def get_context_data(self, **kwargs):
context = super(RequestDetailView, self).get_context_data(**kwargs)
object = context['object']
votes = object.rating.votes
object_uri = self.request.build_absolute_uri(object.get_absolute_url())
context.update({'object_uri': object_uri, 'votes': votes})
return context
@login_required
def add_request(request):
"""Add new requests"""
if request.method == 'POST':
form = RequestForm(request.POST)
if form.is_valid():
request_object = form.save(commit=False)
request_object.suggested_by = request.user
request_object.save()
request_object.rating.add(score=1, user=request.user,
ip_address=request.META['REMOTE_ADDR'])
messages.success(
request,
"Thank you for your suggestion. It will appear on the site once "
"our editors review it. They will contact you if they have any questions."
)
return redirect(reverse('request-list'))
else:
form = RequestForm()
context = {
'form': form
}
return render(request, 'requests/create_edit.html', context)
@login_required
@require_POST
def vote(request, request_id):
"""Vote for a requests"""
redirect_url = request.POST.get('next', reverse('request-list'))
request_object = get_object_or_404(Request, pk=request_id)
voted = request_object.rating.get_rating_for_user(request.user,
request.META['REMOTE_ADDR'])
if not voted:
request_object.rating.add(score=1, user=request.user,
ip_address=request.META['REMOTE_ADDR'])
return redirect(redirect_url)
@login_required
@require_POST
def remove_vote(request, request_id):
"""Remove pre-existing vote for requests"""
request_object = get_object_or_404(Request, pk=request_id)
redirect_url = request.POST.get('next', reverse('request-list'))
try:
request_object.rating.delete(request.user, request.META['REMOTE_ADDR'])
except CannotDeleteVote:
# vote didn't exist, just move on
pass
return redirect(redirect_url)
| 34.897959
| 90
| 0.66462
|
4a0a8ef05ea5f491fbeeab962306014ee3d85a12
| 2,084
|
py
|
Python
|
test_source/TestTimeDifference.py
|
BogyMitutoyoCTL/Sophy
|
60832ad9c1369a8dcc0379031d2fe0ca9eef44e3
|
[
"MIT"
] | null | null | null |
test_source/TestTimeDifference.py
|
BogyMitutoyoCTL/Sophy
|
60832ad9c1369a8dcc0379031d2fe0ca9eef44e3
|
[
"MIT"
] | 1
|
2018-07-04T08:08:49.000Z
|
2018-07-04T08:09:01.000Z
|
test_source/TestTimeDifference.py
|
BogyMitutoyoCTL/Sophy
|
60832ad9c1369a8dcc0379031d2fe0ca9eef44e3
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python
import unittest
from datetime import datetime
from TimeDifference import TimeDifference
"""""
class NameInput(unittest.TestCase):
def test_1(self):
MyApp().run()
self.assertEqual(True, True)
"""""
class TestTimeDifference(unittest.TestCase):
def test_timedifference_calculate_diff_in_microseconds1(self):
td = TimeDifference()
dt1 = datetime(2018, 3, 19, 11, 0, 0, 0)
dt2 = datetime(2018, 3, 19, 11, 0, 0, 100)
timediff = td.calculate(dt1, dt2)
print(timediff.microseconds)
self.assertEqual(timediff.microseconds, 100)
def test_timedifference_calculate_diff_in_microseconds2(self):
td = TimeDifference()
dt1 = datetime(2018, 3, 19, 11, 0, 0, 0)
dt2 = datetime(2018, 3, 19, 11, 0, 0, 0)
timediff = td.calculate(dt1, dt2)
self.assertEqual(timediff.microseconds, 0)
def test_timedifference_calculate_diff_in_days1(self):
td = TimeDifference()
dt1 = datetime(2018, 3, 19, 11, 0, 0, 0)
dt2 = datetime(2018, 3, 11, 11, 0, 0, 0)
timediff = td.calculate(dt1, dt2)
self.assertEqual(timediff.days, -8)
def test_timedifference_calculate_diff_in_hours1(self):
td = TimeDifference()
dt1 = datetime(2018, 3, 19, 11, 0, 0, 0)
dt2 = datetime(2018, 3, 19, 14, 0, 0, 0)
timediff = td.calculate(dt1, dt2)
self.assertEqual(timediff.seconds, 3 * 60 * 60)
def test_timedifference_calculate_diff_in_minutes(self):
td = TimeDifference()
dt1 = datetime(2018, 3, 19, 11, 0, 0, 0)
dt2 = datetime(2018, 3, 19, 11, 15, 0, 0)
timediff = td.calculate(dt1, dt2)
self.assertEqual(timediff.seconds, 15 * 60)
def test_timedifference_calculate_diff_in_seconds(self):
td = TimeDifference()
dt1 = datetime(2018, 3, 19, 11, 0, 0, 0)
dt2 = datetime(2018, 3, 19, 11, 0, 21, 0)
timediff = td.calculate(dt1, dt2)
self.assertEqual(timediff.seconds, 21)
if __name__ == '__main__':
unittest.main()
| 32.061538
| 66
| 0.629079
|
4a0a907351610ae29bf2b9a1d16e693df16a88a8
| 1,844
|
py
|
Python
|
Aeneas/aeneas/bin/aeneas_execute_task.py
|
yalhaizaey/Dreich
|
9528856c3879d4c9d3ced453f223785a71188808
|
[
"Apache-2.0"
] | 25
|
2019-05-09T19:03:37.000Z
|
2022-02-06T20:47:37.000Z
|
Experiments/Aeneas/aeneas/bin/aeneas_execute_task.py
|
jonathanmcchesney/DeFog
|
bc314d41471d00b9d605bb4519f31a465e0a6b75
|
[
"Apache-2.0"
] | null | null | null |
Experiments/Aeneas/aeneas/bin/aeneas_execute_task.py
|
jonathanmcchesney/DeFog
|
bc314d41471d00b9d605bb4519f31a465e0a6b75
|
[
"Apache-2.0"
] | 9
|
2019-08-19T19:00:41.000Z
|
2021-12-09T04:46:07.000Z
|
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, Alberto Pettarin (www.albertopettarin.it)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Execute a Task, that is, a pair of audio/text files
and a configuration string.
"""
from __future__ import absolute_import
from __future__ import print_function
import sys
from aeneas.tools.execute_task import ExecuteTaskCLI
__author__ = "Alberto Pettarin"
__email__ = "aeneas@readbeyond.it"
__copyright__ = """
Copyright 2012-2013, Alberto Pettarin (www.albertopettarin.it)
Copyright 2013-2015, ReadBeyond Srl (www.readbeyond.it)
Copyright 2015-2017, Alberto Pettarin (www.albertopettarin.it)
"""
__license__ = "GNU AGPL 3"
__status__ = "Production"
__version__ = "1.7.3"
def main():
"""
Execute a Task, that is, a pair of audio/text files
and a configuration string.
"""
ExecuteTaskCLI(invoke="aeneas_execute_task").run(arguments=sys.argv)
if __name__ == '__main__':
main()
| 32.350877
| 77
| 0.746746
|
4a0a909cef8f68f565c38124d75f239d70e61c8f
| 4,668
|
py
|
Python
|
scripts/verify-test-files.py
|
illicitonion/buck
|
0336e37a5d9da94b6dcdf6ab78711c1788616ad0
|
[
"Apache-2.0"
] | null | null | null |
scripts/verify-test-files.py
|
illicitonion/buck
|
0336e37a5d9da94b6dcdf6ab78711c1788616ad0
|
[
"Apache-2.0"
] | null | null | null |
scripts/verify-test-files.py
|
illicitonion/buck
|
0336e37a5d9da94b6dcdf6ab78711c1788616ad0
|
[
"Apache-2.0"
] | null | null | null |
#!/usr/bin/env python
"""
Enforce that Java files which look like they contain JUnit test cases
are referenced by a test BUCK target. In other words: find tests that
will not run with `buck test --all`
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import codecs
import fnmatch
import json
import os
import platform
import subprocess
import sys
import tempfile
IGNORE_PREFIXES = [
'buck-out',
'src/com/facebook/buck/testrunner',
# t13833822
'src/com/facebook/buck/intellij/ideabuck/tests/integration',
]
# Due to path length issues during build on Windows the apple test target is
# only created on OSx.
if sys.platform != "darwin":
IGNORE_PREFIXES.extend([
'test/com/facebook/buck/apple'
])
# make the prefixes platform-specific
IGNORE_PREFIXES = [os.path.join(*p.split('/')) for p in IGNORE_PREFIXES]
def isPathIgnored(path):
for prefix in IGNORE_PREFIXES:
if path.startswith(prefix):
return True
return False
def containsJUnitImport(path):
with codecs.open(path, "r", "utf-8") as f:
for l in f.readlines():
if "import org.junit.Test" in l:
return True
return False
def getTestFiles(repo_root):
test_files = []
for root, dirs, files in os.walk(repo_root):
for f in files:
absolute_path = os.path.join(root, f)
if not f.endswith(".java"):
continue
if 'testdata' in absolute_path:
continue
if not containsJUnitImport(absolute_path):
continue
relative_path = os.path.relpath(absolute_path, repo_root)
if isPathIgnored(relative_path):
continue
assert os.path.exists(absolute_path), "%s doesn't exist" % line
test_files.append(relative_path)
return sorted(test_files)
def getOwningRulesData(repo_root, test_files):
t_fd, t_name = tempfile.mkstemp(text=True)
try:
with open(t_name, "w") as t_file:
for f in test_files:
t_file.write(f)
t_file.write("\n")
os.close(t_fd)
env = dict(os.environ.items())
env['NO_BUCKD'] = '1'
if platform.system() == 'Windows':
buck_path = os.path.join(repo_root, 'bin', 'buck.bat')
cmd_prefix = ['cmd.exe', '/C', buck_path]
else:
buck_path = os.path.join(repo_root, 'bin', 'buck')
cmd_prefix = [buck_path]
cmd_output = run_process(
cmd_prefix + ['targets', '--json',
'--referenced-file', '@' + t_name],
env=env,
cwd=repo_root)
# Drop anything that appears before the JSON output.
cmd_output = cmd_output[cmd_output.index("["):]
return json.loads(cmd_output)
except ValueError as e:
print('Problem parsing result to json', cmd_output)
raise e
finally:
if os.path.exists(t_name):
os.unlink(t_name)
def findUnreferencedTestFiles(test_files, owning_rules):
referenced_test_files = set()
for rule in owning_rules:
base_path = rule['buck.base_path']
rule_type = rule['buck.type']
# On windows base_path is still unix-style
base_path = os.path.join(*base_path.split('/'))
if not rule_type.endswith('_test'):
continue
for src in rule['srcs']:
referenced_test_files.add(os.path.join(base_path, src))
return set(test_files).difference(referenced_test_files)
def findRepoRoot(cwd):
while os.path.exists(cwd):
if os.path.exists(os.path.join(cwd, '.buckconfig')):
return cwd
cwd = os.path.dirname(cwd)
raise Exception('Could not locate buck repo root.')
def run_process(*args, **kwargs):
process = subprocess.Popen(stdout=subprocess.PIPE, *args, **kwargs)
stdout, _ = process.communicate()
retcode = process.poll()
if retcode != 0:
raise Exception('Error %s running %s' % (retcode, args))
return stdout
def main():
repo_root = findRepoRoot(os.getcwd())
test_files = getTestFiles(repo_root)
owning_rules = getOwningRulesData(repo_root, test_files)
unreferenced_files = findUnreferencedTestFiles(test_files, owning_rules)
for f in unreferenced_files:
print(f, "looks like a test file, but is not covered by a test rule.")
if len(unreferenced_files) == 0:
print('No unreferenced test files found, all is good.')
return 0
else:
return 1
if __name__ == '__main__':
sys.exit(main())
| 30.710526
| 78
| 0.631962
|
4a0a90a7e0bf3c4812511afd3ef5fe6b121c5084
| 64
|
py
|
Python
|
prediction/yahoo_finance_apis_cheatsheet.py
|
pradeep-charism/bigdata-analytics-ml
|
7448cf61ba7b2c4be54f2d6b08f00b7641389633
|
[
"MIT"
] | null | null | null |
prediction/yahoo_finance_apis_cheatsheet.py
|
pradeep-charism/bigdata-analytics-ml
|
7448cf61ba7b2c4be54f2d6b08f00b7641389633
|
[
"MIT"
] | null | null | null |
prediction/yahoo_finance_apis_cheatsheet.py
|
pradeep-charism/bigdata-analytics-ml
|
7448cf61ba7b2c4be54f2d6b08f00b7641389633
|
[
"MIT"
] | null | null | null |
import yfinance as yf
msft = yf.Ticker("MSFT")
print(msft.info)
| 16
| 24
| 0.734375
|
4a0a914bf391fb17e3db3099700a217c828b9b68
| 71,792
|
py
|
Python
|
yt/frontends/stream/data_structures.py
|
bkhamesra/yt-EinsteinToolkit
|
576bf88b5cd706fd577c513c23b1db07ec5f4cd2
|
[
"BSD-3-Clause-Clear"
] | 1
|
2021-11-29T21:59:06.000Z
|
2021-11-29T21:59:06.000Z
|
yt/frontends/stream/data_structures.py
|
bkhamesra/yt-EinsteinToolkit
|
576bf88b5cd706fd577c513c23b1db07ec5f4cd2
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
yt/frontends/stream/data_structures.py
|
bkhamesra/yt-EinsteinToolkit
|
576bf88b5cd706fd577c513c23b1db07ec5f4cd2
|
[
"BSD-3-Clause-Clear"
] | null | null | null |
"""
Data structures for Streaming, in-memory datasets
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-----------------------------------------------------------------------------
import os
import time
import weakref
import numpy as np
import uuid
from itertools import chain, product
from numbers import Number as numeric_type
from yt.funcs import \
iterable, \
ensure_list
from yt.utilities.io_handler import io_registry
from yt.data_objects.data_containers import \
YTFieldData
from yt.data_objects.particle_unions import \
ParticleUnion
from yt.data_objects.grid_patch import \
AMRGridPatch
from yt.data_objects.static_output import \
ParticleFile
from yt.geometry.geometry_handler import \
YTDataChunk
from yt.geometry.grid_geometry_handler import \
GridIndex
from yt.data_objects.octree_subset import \
OctreeSubset
from yt.geometry.oct_geometry_handler import \
OctreeIndex
from yt.geometry.particle_geometry_handler import \
ParticleIndex
from yt.geometry.oct_container import \
OctreeContainer
from yt.geometry.unstructured_mesh_handler import \
UnstructuredIndex
from yt.data_objects.static_output import \
Dataset
from yt.utilities.logger import ytLogger as mylog
from yt.utilities.lib.misc_utilities import \
get_box_grids_level
from yt.geometry.grid_container import \
GridTree, \
MatchPointsToGrids
from yt.utilities.decompose import \
decompose_array, get_psize
from yt.units.yt_array import \
YTQuantity, \
uconcatenate
from yt.utilities.flagging_methods import \
FlaggingGrid
from yt.data_objects.unstructured_mesh import \
SemiStructuredMesh, \
UnstructuredMesh
from yt.extern.six import string_types
from .fields import \
StreamFieldInfo
class StreamGrid(AMRGridPatch):
"""
Class representing a single In-memory Grid instance.
"""
__slots__ = ['proc_num']
_id_offset = 0
def __init__(self, id, index):
"""
Returns an instance of StreamGrid with *id*, associated with *filename*
and *index*.
"""
#All of the field parameters will be passed to us as needed.
AMRGridPatch.__init__(self, id, filename = None, index = index)
self._children_ids = []
self._parent_id = -1
self.Level = -1
def _guess_properties_from_parent(self):
rf = self.ds.refine_by
my_ind = self.id - self._id_offset
self.dds = self.Parent.dds/rf
ParentLeftIndex = np.rint((self.LeftEdge-self.Parent.LeftEdge)/self.Parent.dds)
self.start_index = rf*(ParentLeftIndex + self.Parent.get_global_startindex()).astype('int64')
self.LeftEdge = self.Parent.LeftEdge + self.Parent.dds * ParentLeftIndex
self.RightEdge = self.LeftEdge + self.ActiveDimensions*self.dds
self.index.grid_left_edge[my_ind,:] = self.LeftEdge
self.index.grid_right_edge[my_ind,:] = self.RightEdge
self._child_mask = None
self._child_index_mask = None
self._child_indices = None
self._setup_dx()
def set_filename(self, filename):
pass
def __repr__(self):
return "StreamGrid_%04i" % (self.id)
@property
def Parent(self):
if self._parent_id == -1: return None
return self.index.grids[self._parent_id - self._id_offset]
@property
def Children(self):
return [self.index.grids[cid - self._id_offset]
for cid in self._children_ids]
class StreamHandler(object):
def __init__(self, left_edges, right_edges, dimensions,
levels, parent_ids, particle_count, processor_ids,
fields, field_units, code_units, io = None,
particle_types = None, periodicity = (True, True, True)):
if particle_types is None: particle_types = {}
self.left_edges = np.array(left_edges)
self.right_edges = np.array(right_edges)
self.dimensions = dimensions
self.levels = levels
self.parent_ids = parent_ids
self.particle_count = particle_count
self.processor_ids = processor_ids
self.num_grids = self.levels.size
self.fields = fields
self.field_units = field_units
self.code_units = code_units
self.io = io
self.particle_types = particle_types
self.periodicity = periodicity
def get_fields(self):
return self.fields.all_fields
def get_particle_type(self, field) :
if field in self.particle_types :
return self.particle_types[field]
else :
return False
class StreamHierarchy(GridIndex):
grid = StreamGrid
def __init__(self, ds, dataset_type = None):
self.dataset_type = dataset_type
self.float_type = 'float64'
self.dataset = weakref.proxy(ds) # for _obtain_enzo
self.stream_handler = ds.stream_handler
self.float_type = "float64"
self.directory = os.getcwd()
GridIndex.__init__(self, ds, dataset_type)
def _count_grids(self):
self.num_grids = self.stream_handler.num_grids
def _parse_index(self):
self.grid_dimensions = self.stream_handler.dimensions
self.grid_left_edge[:] = self.stream_handler.left_edges
self.grid_right_edge[:] = self.stream_handler.right_edges
self.grid_levels[:] = self.stream_handler.levels
self.grid_procs = self.stream_handler.processor_ids
self.grid_particle_count[:] = self.stream_handler.particle_count
mylog.debug("Copying reverse tree")
self.grids = []
# We enumerate, so it's 0-indexed id and 1-indexed pid
for id in range(self.num_grids):
self.grids.append(self.grid(id, self))
self.grids[id].Level = self.grid_levels[id, 0]
parent_ids = self.stream_handler.parent_ids
if parent_ids is not None:
reverse_tree = self.stream_handler.parent_ids.tolist()
# Initial setup:
for gid, pid in enumerate(reverse_tree):
if pid >= 0:
self.grids[gid]._parent_id = pid
self.grids[pid]._children_ids.append(self.grids[gid].id)
else:
mylog.debug("Reconstructing parent-child relationships")
self._reconstruct_parent_child()
self.max_level = self.grid_levels.max()
mylog.debug("Preparing grids")
temp_grids = np.empty(self.num_grids, dtype='object')
for i, grid in enumerate(self.grids):
if (i%1e4) == 0: mylog.debug("Prepared % 7i / % 7i grids", i, self.num_grids)
grid.filename = None
grid._prepare_grid()
grid.proc_num = self.grid_procs[i]
temp_grids[i] = grid
self.grids = temp_grids
mylog.debug("Prepared")
def _reconstruct_parent_child(self):
mask = np.empty(len(self.grids), dtype='int32')
mylog.debug("First pass; identifying child grids")
for i, grid in enumerate(self.grids):
get_box_grids_level(self.grid_left_edge[i,:],
self.grid_right_edge[i,:],
self.grid_levels[i] + 1,
self.grid_left_edge, self.grid_right_edge,
self.grid_levels, mask)
ids = np.where(mask.astype("bool"))
grid._children_ids = ids[0] # where is a tuple
mylog.debug("Second pass; identifying parents")
self.stream_handler.parent_ids = np.zeros(
self.stream_handler.num_grids, "int64") - 1
for i, grid in enumerate(self.grids): # Second pass
for child in grid.Children:
child._parent_id = i
# _id_offset = 0
self.stream_handler.parent_ids[child.id] = i
def _initialize_grid_arrays(self):
GridIndex._initialize_grid_arrays(self)
self.grid_procs = np.zeros((self.num_grids,1),'int32')
def _detect_output_fields(self):
# NOTE: Because particle unions add to the actual field list, without
# having the keys in the field list itself, we need to double check
# here.
fl = set(self.stream_handler.get_fields())
fl.update(set(getattr(self, "field_list", [])))
self.field_list = list(fl)
def _populate_grid_objects(self):
for g in self.grids:
g._setup_dx()
self.max_level = self.grid_levels.max()
def _setup_data_io(self):
if self.stream_handler.io is not None:
self.io = self.stream_handler.io
else:
self.io = io_registry[self.dataset_type](self.ds)
def update_data(self, data, units = None):
"""
Update the stream data with a new data dict. If fields already exist,
they will be replaced, but if they do not, they will be added. Fields
already in the stream but not part of the data dict will be left
alone.
"""
[update_field_names(d) for d in data]
if units is not None:
self.stream_handler.field_units.update(units)
particle_types = set_particle_types(data[0])
ftype = "io"
for key in data[0].keys() :
if key is "number_of_particles": continue
self.stream_handler.particle_types[key] = particle_types[key]
for i, grid in enumerate(self.grids) :
if "number_of_particles" in data[i] :
grid.NumberOfParticles = data[i].pop("number_of_particles")
for fname in data[i]:
if fname in grid.field_data:
grid.field_data.pop(fname, None)
elif (ftype, fname) in grid.field_data:
grid.field_data.pop( ("io", fname) )
self.stream_handler.fields[grid.id][fname] = data[i][fname]
# We only want to create a superset of fields here.
self._detect_output_fields()
self.ds.create_field_info()
mylog.debug("Creating Particle Union 'all'")
pu = ParticleUnion("all", list(self.ds.particle_types_raw))
self.ds.add_particle_union(pu)
self.ds.particle_types = tuple(set(self.ds.particle_types))
class StreamDataset(Dataset):
_index_class = StreamHierarchy
_field_info_class = StreamFieldInfo
_dataset_type = 'stream'
def __init__(self, stream_handler, storage_filename=None,
geometry="cartesian", unit_system="cgs"):
#if parameter_override is None: parameter_override = {}
#self._parameter_override = parameter_override
#if conversion_override is None: conversion_override = {}
#self._conversion_override = conversion_override
self.fluid_types += ("stream",)
self.geometry = geometry
self.stream_handler = stream_handler
name = "InMemoryParameterFile_%s" % (uuid.uuid4().hex)
from yt.data_objects.static_output import _cached_datasets
_cached_datasets[name] = self
Dataset.__init__(self, name, self._dataset_type,
unit_system=unit_system)
def _parse_parameter_file(self):
self.basename = self.stream_handler.name
self.parameters['CurrentTimeIdentifier'] = time.time()
self.unique_identifier = self.parameters["CurrentTimeIdentifier"]
self.domain_left_edge = self.stream_handler.domain_left_edge.copy()
self.domain_right_edge = self.stream_handler.domain_right_edge.copy()
self.refine_by = self.stream_handler.refine_by
self.dimensionality = self.stream_handler.dimensionality
self.periodicity = self.stream_handler.periodicity
self.domain_dimensions = self.stream_handler.domain_dimensions
self.current_time = self.stream_handler.simulation_time
self.gamma = 5./3.
self.parameters['EOSType'] = -1
self.parameters['CosmologyHubbleConstantNow'] = 1.0
self.parameters['CosmologyCurrentRedshift'] = 1.0
self.parameters['HydroMethod'] = -1
if self.stream_handler.cosmology_simulation:
self.cosmological_simulation = 1
self.current_redshift = self.stream_handler.current_redshift
self.omega_lambda = self.stream_handler.omega_lambda
self.omega_matter = self.stream_handler.omega_matter
self.hubble_constant = self.stream_handler.hubble_constant
else:
self.current_redshift = self.omega_lambda = self.omega_matter = \
self.hubble_constant = self.cosmological_simulation = 0.0
def _set_units(self):
self.field_units = self.stream_handler.field_units
def _set_code_unit_attributes(self):
base_units = self.stream_handler.code_units
attrs = ('length_unit', 'mass_unit', 'time_unit', 'velocity_unit', 'magnetic_unit')
cgs_units = ('cm', 'g', 's', 'cm/s', 'gauss')
for unit, attr, cgs_unit in zip(base_units, attrs, cgs_units):
if isinstance(unit, string_types):
uq = self.quan(1.0, unit)
elif isinstance(unit, numeric_type):
uq = self.quan(unit, cgs_unit)
elif isinstance(unit, YTQuantity):
uq = unit
elif isinstance(unit, tuple):
uq = self.quan(unit[0], unit[1])
else:
raise RuntimeError("%s (%s) is invalid." % (attr, unit))
setattr(self, attr, uq)
@classmethod
def _is_valid(cls, *args, **kwargs):
return False
@property
def _skip_cache(self):
return True
class StreamDictFieldHandler(dict):
_additional_fields = ()
@property
def all_fields(self):
self_fields = chain.from_iterable(s.keys() for s in self.values())
self_fields = list(set(self_fields))
fields = list(self._additional_fields) + self_fields
fields = list(set(fields))
return fields
def update_field_names(data):
orig_names = list(data.keys())
for k in orig_names:
if isinstance(k, tuple):
continue
s = getattr(data[k], "shape", ())
if len(s) == 1:
field = ("io", k)
elif len(s) == 3:
field = ("stream", k)
elif len(s) == 0:
continue
else:
raise NotImplementedError
data[field] = data.pop(k)
def set_particle_types(data):
particle_types = {}
for key in data.keys():
if key == "number_of_particles":
continue
if len(data[key].shape) == 1:
particle_types[key] = True
else:
particle_types[key] = False
return particle_types
def assign_particle_data(ds, pdata):
"""
Assign particle data to the grids using MatchPointsToGrids. This
will overwrite any existing particle data, so be careful!
"""
# Note: what we need to do here is a bit tricky. Because occasionally this
# gets called before we property handle the field detection, we cannot use
# any information about the index. Fortunately for us, we can generate
# most of the GridTree utilizing information we already have from the
# stream handler.
if len(ds.stream_handler.fields) > 1:
if ("io", "particle_position_x") in pdata:
x, y, z = (pdata["io", "particle_position_%s" % ax] for ax in 'xyz')
elif ("io", "particle_position") in pdata:
x, y, z = pdata["io", "particle_position"].T
else:
raise KeyError(
"Cannot decompose particle data without position fields!")
num_grids = len(ds.stream_handler.fields)
parent_ids = ds.stream_handler.parent_ids
num_children = np.zeros(num_grids, dtype='int64')
# We're going to do this the slow way
mask = np.empty(num_grids, dtype="bool")
for i in range(num_grids):
np.equal(parent_ids, i, mask)
num_children[i] = mask.sum()
levels = ds.stream_handler.levels.astype("int64").ravel()
grid_tree = GridTree(num_grids,
ds.stream_handler.left_edges,
ds.stream_handler.right_edges,
ds.stream_handler.dimensions,
ds.stream_handler.parent_ids,
levels, num_children)
pts = MatchPointsToGrids(grid_tree, len(x), x, y, z)
particle_grid_inds = pts.find_points_in_tree()
idxs = np.argsort(particle_grid_inds)
particle_grid_count = np.bincount(particle_grid_inds.astype("intp"),
minlength=num_grids)
particle_indices = np.zeros(num_grids + 1, dtype='int64')
if num_grids > 1 :
np.add.accumulate(particle_grid_count.squeeze(),
out=particle_indices[1:])
else :
particle_indices[1] = particle_grid_count.squeeze()
pdata.pop("number_of_particles", None)
grid_pdata = []
for i, pcount in enumerate(particle_grid_count):
grid = {}
grid["number_of_particles"] = pcount
start = particle_indices[i]
end = particle_indices[i+1]
for key in pdata.keys() :
grid[key] = pdata[key][idxs][start:end]
grid_pdata.append(grid)
else :
grid_pdata = [pdata]
for pd, gi in zip(grid_pdata, sorted(ds.stream_handler.fields)):
ds.stream_handler.fields[gi].update(pd)
npart = ds.stream_handler.fields[gi].pop("number_of_particles", 0)
ds.stream_handler.particle_count[gi] = npart
def unitify_data(data):
new_data, field_units = {}, {}
for field, val in data.items():
# val is a data array
if isinstance(val, np.ndarray):
# val is a YTArray
if hasattr(val, "units"):
field_units[field] = val.units
new_data[field] = val.copy().d
# val is a numpy array
else:
field_units[field] = ""
new_data[field] = val.copy()
# val is a tuple of (data, units)
elif isinstance(val, tuple) and len(val) == 2:
try:
assert isinstance(field, (string_types, tuple)), \
"Field name is not a string!"
assert isinstance(val[0], np.ndarray), \
"Field data is not an ndarray!"
assert isinstance(val[1], string_types), \
"Unit specification is not a string!"
field_units[field] = val[1]
new_data[field] = val[0]
except AssertionError as e:
raise RuntimeError(
"The data dict appears to be invalid.\n" + str(e))
# val is a list of data to be turned into an array
elif iterable(val):
field_units[field] = ""
new_data[field] = np.asarray(val)
else:
raise RuntimeError("The data dict appears to be invalid. "
"The data dictionary must map from field "
"names to (numpy array, unit spec) tuples. ")
data = new_data
# At this point, we have arrays for all our fields
new_data = {}
for field in data:
if isinstance(field, tuple):
new_field = field
elif len(data[field].shape) in (1, 2):
new_field = ("io", field)
elif len(data[field].shape) == 3:
new_field = ("stream", field)
else:
raise RuntimeError
new_data[new_field] = data[field]
field_units[new_field] = field_units.pop(field)
known_fields = StreamFieldInfo.known_particle_fields \
+ StreamFieldInfo.known_other_fields
# We do not want to override any of the known ones, if it's not
# overridden here.
if any(f[0] == new_field[1] for f in known_fields) and \
field_units[new_field] == "":
field_units.pop(new_field)
data = new_data
return field_units, data
def load_uniform_grid(data, domain_dimensions, length_unit=None, bbox=None,
nprocs=1, sim_time=0.0, mass_unit=None, time_unit=None,
velocity_unit=None, magnetic_unit=None,
periodicity=(True, True, True),
geometry="cartesian", unit_system="cgs"):
r"""Load a uniform grid of data into yt as a
:class:`~yt.frontends.stream.data_structures.StreamHandler`.
This should allow a uniform grid of data to be loaded directly into yt and
analyzed as would any others. This comes with several caveats:
* Units will be incorrect unless the unit system is explicitly
specified.
* Some functions may behave oddly, and parallelism will be
disappointing or non-existent in most cases.
* Particles may be difficult to integrate.
Particle fields are detected as one-dimensional fields. The number of
particles is set by the "number_of_particles" key in data.
Parameters
----------
data : dict
This is a dict of numpy arrays or (numpy array, unit spec) tuples.
The keys are the field names.
domain_dimensions : array_like
This is the domain dimensions of the grid
length_unit : string
Unit to use for lengths. Defaults to unitless.
bbox : array_like (xdim:zdim, LE:RE), optional
Size of computational domain in units specified by length_unit.
Defaults to a cubic unit-length domain.
nprocs: integer, optional
If greater than 1, will create this number of subarrays out of data
sim_time : float, optional
The simulation time in seconds
mass_unit : string
Unit to use for masses. Defaults to unitless.
time_unit : string
Unit to use for times. Defaults to unitless.
velocity_unit : string
Unit to use for velocities. Defaults to unitless.
magnetic_unit : string
Unit to use for magnetic fields. Defaults to unitless.
periodicity : tuple of booleans
Determines whether the data will be treated as periodic along
each axis
geometry : string or tuple
"cartesian", "cylindrical", "polar", "spherical", "geographic" or
"spectral_cube". Optionally, a tuple can be provided to specify the
axis ordering -- for instance, to specify that the axis ordering should
be z, x, y, this would be: ("cartesian", ("z", "x", "y")). The same
can be done for other coordinates, for instance:
("spherical", ("theta", "phi", "r")).
Examples
--------
>>> bbox = np.array([[0., 1.0], [-1.5, 1.5], [1.0, 2.5]])
>>> arr = np.random.random((128, 128, 128))
>>> data = dict(density=arr)
>>> ds = load_uniform_grid(data, arr.shape, length_unit='cm',
... bbox=bbox, nprocs=12)
>>> dd = ds.all_data()
>>> dd['density']
YTArray([ 0.87568064, 0.33686453, 0.70467189, ..., 0.70439916,
0.97506269, 0.03047113]) g/cm**3
>>> data = dict(density=(arr, 'kg/m**3'))
>>> ds = load_uniform_grid(data, arr.shape, length_unit=3.03e24,
... bbox=bbox, nprocs=12)
>>> dd = ds.all_data()
>>> dd['density']
YTArray([ 8.75680644e-04, 3.36864527e-04, 7.04671886e-04, ...,
7.04399160e-04, 9.75062693e-04, 3.04711295e-05]) g/cm**3
"""
domain_dimensions = np.array(domain_dimensions)
if bbox is None:
bbox = np.array([[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], 'float64')
domain_left_edge = np.array(bbox[:, 0], 'float64')
domain_right_edge = np.array(bbox[:, 1], 'float64')
grid_levels = np.zeros(nprocs, dtype='int32').reshape((nprocs,1))
number_of_particles = data.pop("number_of_particles", 0)
# First we fix our field names
field_units, data = unitify_data(data)
for field_name in data:
fshape = data[field_name].shape
dshape = tuple(domain_dimensions)
pshape = (number_of_particles, )
if fshape != dshape and fshape != pshape:
msg = ("Input data shape %s for field %s does not match provided "
"domain_dimensions %s or number of particles %s")
msg = msg % (fshape, field_name, dshape, pshape)
raise RuntimeError(msg)
sfh = StreamDictFieldHandler()
if number_of_particles > 0:
particle_types = set_particle_types(data)
pdata = {} # Used much further below.
pdata["number_of_particles"] = number_of_particles
for key in list(data.keys()):
if len(data[key].shape) == 1 or key[0] == 'io':
if not isinstance(key, tuple):
field = ("io", key)
mylog.debug("Reassigning '%s' to '%s'", key, field)
else:
field = key
sfh._additional_fields += (field,)
pdata[field] = data.pop(key)
else:
particle_types = {}
update_field_names(data)
if nprocs > 1:
temp = {}
new_data = {}
for key in data.keys():
psize = get_psize(np.array(data[key].shape), nprocs)
grid_left_edges, grid_right_edges, shapes, slices = \
decompose_array(data[key].shape, psize, bbox)
grid_dimensions = np.array([shape for shape in shapes],
dtype="int32")
temp[key] = [data[key][slice] for slice in slices]
for gid in range(nprocs):
new_data[gid] = {}
for key in temp.keys():
new_data[gid].update({key:temp[key][gid]})
sfh.update(new_data)
del new_data, temp
else:
sfh.update({0:data})
grid_left_edges = domain_left_edge
grid_right_edges = domain_right_edge
grid_dimensions = domain_dimensions.reshape(nprocs,3).astype("int32")
if length_unit is None:
length_unit = 'code_length'
if mass_unit is None:
mass_unit = 'code_mass'
if time_unit is None:
time_unit = 'code_time'
if velocity_unit is None:
velocity_unit = 'code_velocity'
if magnetic_unit is None:
magnetic_unit = 'code_magnetic'
handler = StreamHandler(
grid_left_edges,
grid_right_edges,
grid_dimensions,
grid_levels,
-np.ones(nprocs, dtype='int64'),
np.zeros(nprocs, dtype='int64').reshape(nprocs,1), # particle count
np.zeros(nprocs).reshape((nprocs,1)),
sfh,
field_units,
(length_unit, mass_unit, time_unit, velocity_unit, magnetic_unit),
particle_types=particle_types,
periodicity=periodicity
)
handler.name = "UniformGridData"
handler.domain_left_edge = domain_left_edge
handler.domain_right_edge = domain_right_edge
handler.refine_by = 2
handler.dimensionality = 3
handler.domain_dimensions = domain_dimensions
handler.simulation_time = sim_time
handler.cosmology_simulation = 0
sds = StreamDataset(handler, geometry=geometry, unit_system=unit_system)
check_fields = [("io", "particle_position_x"), ("io", "particle_position")]
# Now figure out where the particles go
if number_of_particles > 0:
if all(f not in pdata for f in check_fields):
pdata_ftype = {}
for f in [k for k in sorted(pdata)]:
if not hasattr(pdata[f], "shape"):
continue
if f == 'number_of_particles':
continue
mylog.debug("Reassigning '%s' to ('io','%s')", f, f)
pdata_ftype["io",f] = pdata.pop(f)
pdata_ftype.update(pdata)
pdata = pdata_ftype
# This will update the stream handler too
assign_particle_data(sds, pdata)
return sds
def load_amr_grids(grid_data, domain_dimensions,
bbox=None, sim_time=0.0, length_unit=None,
mass_unit=None, time_unit=None, velocity_unit=None,
magnetic_unit=None, periodicity=(True, True, True),
geometry="cartesian", refine_by=2, unit_system="cgs"):
r"""Load a set of grids of data into yt as a
:class:`~yt.frontends.stream.data_structures.StreamHandler`.
This should allow a sequence of grids of varying resolution of data to be
loaded directly into yt and analyzed as would any others. This comes with
several caveats:
* Units will be incorrect unless the unit system is explicitly specified.
* Some functions may behave oddly, and parallelism will be
disappointing or non-existent in most cases.
* Particles may be difficult to integrate.
* No consistency checks are performed on the index
Parameters
----------
grid_data : list of dicts
This is a list of dicts. Each dict must have entries "left_edge",
"right_edge", "dimensions", "level", and then any remaining entries are
assumed to be fields. Field entries must map to an NDArray. The grid_data
may also include a particle count. If no particle count is supplied, the
dataset is understood to contain no particles. The grid_data will be
modified in place and can't be assumed to be static.
domain_dimensions : array_like
This is the domain dimensions of the grid
length_unit : string or float
Unit to use for lengths. Defaults to unitless. If set to be a string, the bbox
dimensions are assumed to be in the corresponding units. If set to a float, the
value is a assumed to be the conversion from bbox dimensions to centimeters.
mass_unit : string or float
Unit to use for masses. Defaults to unitless.
time_unit : string or float
Unit to use for times. Defaults to unitless.
velocity_unit : string or float
Unit to use for velocities. Defaults to unitless.
magnetic_unit : string or float
Unit to use for magnetic fields. Defaults to unitless.
bbox : array_like (xdim:zdim, LE:RE), optional
Size of computational domain in units specified by length_unit.
Defaults to a cubic unit-length domain.
sim_time : float, optional
The simulation time in seconds
periodicity : tuple of booleans
Determines whether the data will be treated as periodic along
each axis
geometry : string or tuple
"cartesian", "cylindrical", "polar", "spherical", "geographic" or
"spectral_cube". Optionally, a tuple can be provided to specify the
axis ordering -- for instance, to specify that the axis ordering should
be z, x, y, this would be: ("cartesian", ("z", "x", "y")). The same
can be done for other coordinates, for instance:
("spherical", ("theta", "phi", "r")).
refine_by : integer
Specifies the refinement ratio between levels. Defaults to 2.
Examples
--------
>>> grid_data = [
... dict(left_edge = [0.0, 0.0, 0.0],
... right_edge = [1.0, 1.0, 1.],
... level = 0,
... dimensions = [32, 32, 32],
... number_of_particles = 0)
... dict(left_edge = [0.25, 0.25, 0.25],
... right_edge = [0.75, 0.75, 0.75],
... level = 1,
... dimensions = [32, 32, 32],
... number_of_particles = 0)
... ]
...
>>> for g in grid_data:
... g["density"] = (np.random.random(g["dimensions"])*2**g["level"], "g/cm**3")
...
>>> ds = load_amr_grids(grid_data, [32, 32, 32], length_unit=1.0)
"""
domain_dimensions = np.array(domain_dimensions)
ngrids = len(grid_data)
if bbox is None:
bbox = np.array([[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], 'float64')
domain_left_edge = np.array(bbox[:, 0], 'float64')
domain_right_edge = np.array(bbox[:, 1], 'float64')
grid_levels = np.zeros((ngrids, 1), dtype='int32')
grid_left_edges = np.zeros((ngrids, 3), dtype="float64")
grid_right_edges = np.zeros((ngrids, 3), dtype="float64")
grid_dimensions = np.zeros((ngrids, 3), dtype="int32")
number_of_particles = np.zeros((ngrids,1), dtype='int64')
parent_ids = np.zeros(ngrids, dtype="int64") - 1
sfh = StreamDictFieldHandler()
for i, g in enumerate(grid_data):
grid_left_edges[i,:] = g.pop("left_edge")
grid_right_edges[i,:] = g.pop("right_edge")
grid_dimensions[i,:] = g.pop("dimensions")
grid_levels[i,:] = g.pop("level")
if "number_of_particles" in g:
number_of_particles[i,:] = g.pop("number_of_particles")
field_units, data = unitify_data(g)
update_field_names(data)
sfh[i] = data
# We now reconstruct our parent ids, so that our particle assignment can
# proceed.
mask = np.empty(ngrids, dtype='int32')
for gi in range(ngrids):
get_box_grids_level(grid_left_edges[gi,:],
grid_right_edges[gi,:],
grid_levels[gi] + 1,
grid_left_edges, grid_right_edges,
grid_levels, mask)
ids = np.where(mask.astype("bool"))
for ci in ids:
parent_ids[ci] = gi
if length_unit is None:
length_unit = 'code_length'
if mass_unit is None:
mass_unit = 'code_mass'
if time_unit is None:
time_unit = 'code_time'
if velocity_unit is None:
velocity_unit = 'code_velocity'
if magnetic_unit is None:
magnetic_unit = 'code_magnetic'
particle_types = {}
for grid in sfh.values():
particle_types.update(set_particle_types(grid))
handler = StreamHandler(
grid_left_edges,
grid_right_edges,
grid_dimensions,
grid_levels,
parent_ids,
number_of_particles,
np.zeros(ngrids).reshape((ngrids,1)),
sfh,
field_units,
(length_unit, mass_unit, time_unit, velocity_unit, magnetic_unit),
particle_types=particle_types,
periodicity=periodicity
)
handler.name = "AMRGridData"
handler.domain_left_edge = domain_left_edge
handler.domain_right_edge = domain_right_edge
handler.refine_by = refine_by
handler.dimensionality = 3
handler.domain_dimensions = domain_dimensions
handler.simulation_time = sim_time
handler.cosmology_simulation = 0
sds = StreamDataset(handler, geometry=geometry, unit_system=unit_system)
return sds
def refine_amr(base_ds, refinement_criteria, fluid_operators, max_level,
callback=None):
r"""Given a base dataset, repeatedly apply refinement criteria and
fluid operators until a maximum level is reached.
Parameters
----------
base_ds : Dataset
This is any static output. It can also be a stream static output, for
instance as returned by load_uniform_data.
refinement_critera : list of :class:`~yt.utilities.flagging_methods.FlaggingMethod`
These criteria will be applied in sequence to identify cells that need
to be refined.
fluid_operators : list of :class:`~yt.utilities.initial_conditions.FluidOperator`
These fluid operators will be applied in sequence to all resulting
grids.
max_level : int
The maximum level to which the data will be refined
callback : function, optional
A function that will be called at the beginning of each refinement
cycle, with the current dataset.
Examples
--------
>>> domain_dims = (32, 32, 32)
>>> data = np.zeros(domain_dims) + 0.25
>>> fo = [ic.CoredSphere(0.05, 0.3, [0.7,0.4,0.75], {"Density": (0.25, 100.0)})]
>>> rc = [fm.flagging_method_registry["overdensity"](8.0)]
>>> ug = load_uniform_grid({'Density': data}, domain_dims, 1.0)
>>> ds = refine_amr(ug, rc, fo, 5)
"""
# If we have particle data, set it aside for now
number_of_particles = np.sum([grid.NumberOfParticles
for grid in base_ds.index.grids])
if number_of_particles > 0:
pdata = {}
for field in base_ds.field_list:
if not isinstance(field, tuple):
field = ("unknown", field)
fi = base_ds._get_field_info(*field)
if fi.particle_type :
pdata[field] = uconcatenate([grid[field]
for grid in base_ds.index.grids])
pdata["number_of_particles"] = number_of_particles
last_gc = base_ds.index.num_grids
cur_gc = -1
ds = base_ds
bbox = np.array([(ds.domain_left_edge[i], ds.domain_right_edge[i])
for i in range(3)])
while ds.index.max_level < max_level and last_gc != cur_gc:
mylog.info("Refining another level. Current max level: %s",
ds.index.max_level)
last_gc = ds.index.grids.size
for m in fluid_operators: m.apply(ds)
if callback is not None: callback(ds)
grid_data = []
for g in ds.index.grids:
gd = dict( left_edge = g.LeftEdge,
right_edge = g.RightEdge,
level = g.Level,
dimensions = g.ActiveDimensions )
for field in ds.field_list:
if not isinstance(field, tuple):
field = ("unknown", field)
fi = ds._get_field_info(*field)
if not fi.particle_type :
gd[field] = g[field]
grid_data.append(gd)
if g.Level < ds.index.max_level: continue
fg = FlaggingGrid(g, refinement_criteria)
nsg = fg.find_subgrids()
for sg in nsg:
LE = sg.left_index * g.dds + ds.domain_left_edge
dims = sg.dimensions * ds.refine_by
grid = ds.smoothed_covering_grid(g.Level + 1, LE, dims)
gd = dict(left_edge = LE, right_edge = grid.right_edge,
level = g.Level + 1, dimensions = dims)
for field in ds.field_list:
if not isinstance(field, tuple):
field = ("unknown", field)
fi = ds._get_field_info(*field)
if not fi.particle_type :
gd[field] = grid[field]
grid_data.append(gd)
ds = load_amr_grids(grid_data, ds.domain_dimensions, bbox=bbox)
if number_of_particles > 0:
if ("io", "particle_position_x") not in pdata:
pdata_ftype = {}
for f in [k for k in sorted(pdata)]:
if not hasattr(pdata[f], "shape"): continue
mylog.debug("Reassigning '%s' to ('io','%s')", f, f)
pdata_ftype["io",f] = pdata.pop(f)
pdata_ftype.update(pdata)
pdata = pdata_ftype
assign_particle_data(ds, pdata)
# We need to reassign the field list here.
cur_gc = ds.index.num_grids
return ds
class StreamParticleIndex(ParticleIndex):
def __init__(self, ds, dataset_type = None):
self.stream_handler = ds.stream_handler
super(StreamParticleIndex, self).__init__(ds, dataset_type)
def _setup_data_io(self):
if self.stream_handler.io is not None:
self.io = self.stream_handler.io
else:
self.io = io_registry[self.dataset_type](self.ds)
class StreamParticleFile(ParticleFile):
pass
class StreamParticlesDataset(StreamDataset):
_index_class = StreamParticleIndex
_file_class = StreamParticleFile
_field_info_class = StreamFieldInfo
_dataset_type = "stream_particles"
file_count = 1
filename_template = "stream_file"
n_ref = 64
over_refine_factor = 1
def load_particles(data, length_unit = None, bbox=None,
sim_time=0.0, mass_unit = None, time_unit = None,
velocity_unit=None, magnetic_unit=None,
periodicity=(True, True, True),
n_ref = 64, over_refine_factor = 1, geometry = "cartesian",
unit_system="cgs"):
r"""Load a set of particles into yt as a
:class:`~yt.frontends.stream.data_structures.StreamParticleHandler`.
This should allow a collection of particle data to be loaded directly into
yt and analyzed as would any others. This comes with several caveats:
* Units will be incorrect unless the data has already been converted to
cgs.
* Some functions may behave oddly, and parallelism will be
disappointing or non-existent in most cases.
This will initialize an Octree of data. Note that fluid fields will not
work yet, or possibly ever.
Parameters
----------
data : dict
This is a dict of numpy arrays, where the keys are the field names.
Particles positions must be named "particle_position_x",
"particle_position_y", "particle_position_z".
length_unit : float
Conversion factor from simulation length units to centimeters
mass_unit : float
Conversion factor from simulation mass units to grams
time_unit : float
Conversion factor from simulation time units to seconds
velocity_unit : float
Conversion factor from simulation velocity units to cm/s
magnetic_unit : float
Conversion factor from simulation magnetic units to gauss
bbox : array_like (xdim:zdim, LE:RE), optional
Size of computational domain in units of the length_unit
sim_time : float, optional
The simulation time in seconds
periodicity : tuple of booleans
Determines whether the data will be treated as periodic along
each axis
n_ref : int
The number of particles that result in refining an oct used for
indexing the particles.
Examples
--------
>>> pos = [np.random.random(128*128*128) for i in range(3)]
>>> data = dict(particle_position_x = pos[0],
... particle_position_y = pos[1],
... particle_position_z = pos[2])
>>> bbox = np.array([[0., 1.0], [0.0, 1.0], [0.0, 1.0]])
>>> ds = load_particles(data, 3.08e24, bbox=bbox)
"""
domain_dimensions = np.ones(3, "int32") * (1 << over_refine_factor)
nprocs = 1
if bbox is None:
bbox = np.array([[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], 'float64')
domain_left_edge = np.array(bbox[:, 0], 'float64')
domain_right_edge = np.array(bbox[:, 1], 'float64')
grid_levels = np.zeros(nprocs, dtype='int32').reshape((nprocs,1))
field_units, data = unitify_data(data)
sfh = StreamDictFieldHandler()
pdata = {}
for key in data.keys() :
if not isinstance(key, tuple):
field = ("io", key)
mylog.debug("Reassigning '%s' to '%s'", key, field)
else:
field = key
pdata[field] = data[key]
sfh._additional_fields += (field,)
data = pdata # Drop reference count
update_field_names(data)
particle_types = set_particle_types(data)
sfh.update({'stream_file':data})
grid_left_edges = domain_left_edge
grid_right_edges = domain_right_edge
grid_dimensions = domain_dimensions.reshape(nprocs,3).astype("int32")
if length_unit is None:
length_unit = 'code_length'
if mass_unit is None:
mass_unit = 'code_mass'
if time_unit is None:
time_unit = 'code_time'
if velocity_unit is None:
velocity_unit = 'code_velocity'
if magnetic_unit is None:
magnetic_unit = 'code_magnetic'
# I'm not sure we need any of this.
handler = StreamHandler(
grid_left_edges,
grid_right_edges,
grid_dimensions,
grid_levels,
-np.ones(nprocs, dtype='int64'),
np.zeros(nprocs, dtype='int64').reshape(nprocs,1), # Temporary
np.zeros(nprocs).reshape((nprocs,1)),
sfh,
field_units,
(length_unit, mass_unit, time_unit, velocity_unit, magnetic_unit),
particle_types=particle_types,
periodicity=periodicity
)
handler.name = "ParticleData"
handler.domain_left_edge = domain_left_edge
handler.domain_right_edge = domain_right_edge
handler.refine_by = 2
handler.dimensionality = 3
handler.domain_dimensions = domain_dimensions
handler.simulation_time = sim_time
handler.cosmology_simulation = 0
sds = StreamParticlesDataset(handler, geometry=geometry, unit_system=unit_system)
sds.n_ref = n_ref
sds.over_refine_factor = over_refine_factor
return sds
_cis = np.fromiter(chain.from_iterable(product([0,1], [0,1], [0,1])),
dtype=np.int64, count = 8*3)
_cis.shape = (8, 3)
def hexahedral_connectivity(xgrid, ygrid, zgrid):
r"""Define the cell coordinates and cell neighbors of a hexahedral mesh
for a semistructured grid. Used to specify the connectivity and
coordinates parameters used in
:function:`~yt.frontends.stream.data_structures.load_hexahedral_mesh`.
Parameters
----------
xgrid : array_like
x-coordinates of boundaries of the hexahedral cells. Should be a
one-dimensional array.
ygrid : array_like
y-coordinates of boundaries of the hexahedral cells. Should be a
one-dimensional array.
zgrid : array_like
z-coordinates of boundaries of the hexahedral cells. Should be a
one-dimensional array.
Returns
-------
coords : array_like
The list of (x,y,z) coordinates of the vertices of the mesh.
Is of size (M,3) where M is the number of vertices.
connectivity : array_like
For each hexahedron h in the mesh, gives the index of each of h's
neighbors. Is of size (N,8), where N is the number of hexahedra.
Examples
--------
>>> xgrid = np.array([-1,-0.25,0,0.25,1])
>>> coords, conn = hexahedral_connectivity(xgrid,xgrid,xgrid)
>>> coords
array([[-1. , -1. , -1. ],
[-1. , -1. , -0.25],
[-1. , -1. , 0. ],
...,
[ 1. , 1. , 0. ],
[ 1. , 1. , 0.25],
[ 1. , 1. , 1. ]])
>>> conn
array([[ 0, 1, 5, 6, 25, 26, 30, 31],
[ 1, 2, 6, 7, 26, 27, 31, 32],
[ 2, 3, 7, 8, 27, 28, 32, 33],
...,
[ 91, 92, 96, 97, 116, 117, 121, 122],
[ 92, 93, 97, 98, 117, 118, 122, 123],
[ 93, 94, 98, 99, 118, 119, 123, 124]])
"""
nx = len(xgrid)
ny = len(ygrid)
nz = len(zgrid)
coords = np.zeros((nx, ny, nz, 3), dtype="float64", order="C")
coords[:,:,:,0] = xgrid[:,None,None]
coords[:,:,:,1] = ygrid[None,:,None]
coords[:,:,:,2] = zgrid[None,None,:]
coords.shape = (nx * ny * nz, 3)
cycle = np.rollaxis(np.indices((nx-1,ny-1,nz-1)), 0, 4)
cycle.shape = ((nx-1)*(ny-1)*(nz-1), 3)
off = _cis + cycle[:, np.newaxis]
connectivity = ((off[:,:,0] * ny) + off[:,:,1]) * nz + off[:,:,2]
return coords, connectivity
class StreamHexahedralMesh(SemiStructuredMesh):
_connectivity_length = 8
_index_offset = 0
class StreamHexahedralHierarchy(UnstructuredIndex):
def __init__(self, ds, dataset_type = None):
self.stream_handler = ds.stream_handler
super(StreamHexahedralHierarchy, self).__init__(ds, dataset_type)
def _initialize_mesh(self):
coords = self.stream_handler.fields.pop('coordinates')
connec = self.stream_handler.fields.pop('connectivity')
self.meshes = [StreamHexahedralMesh(0,
self.index_filename, connec, coords, self)]
def _setup_data_io(self):
if self.stream_handler.io is not None:
self.io = self.stream_handler.io
else:
self.io = io_registry[self.dataset_type](self.ds)
def _detect_output_fields(self):
self.field_list = list(set(self.stream_handler.get_fields()))
class StreamHexahedralDataset(StreamDataset):
_index_class = StreamHexahedralHierarchy
_field_info_class = StreamFieldInfo
_dataset_type = "stream_hexahedral"
def load_hexahedral_mesh(data, connectivity, coordinates,
length_unit = None, bbox=None, sim_time=0.0,
mass_unit = None, time_unit = None,
velocity_unit = None, magnetic_unit = None,
periodicity=(True, True, True),
geometry = "cartesian", unit_system="cgs"):
r"""Load a hexahedral mesh of data into yt as a
:class:`~yt.frontends.stream.data_structures.StreamHandler`.
This should allow a semistructured grid of data to be loaded directly into
yt and analyzed as would any others. This comes with several caveats:
* Units will be incorrect unless the data has already been converted to
cgs.
* Some functions may behave oddly, and parallelism will be
disappointing or non-existent in most cases.
* Particles may be difficult to integrate.
Particle fields are detected as one-dimensional fields. The number of particles
is set by the "number_of_particles" key in data.
Parameters
----------
data : dict
This is a dict of numpy arrays, where the keys are the field names.
There must only be one. Note that the data in the numpy arrays should
define the cell-averaged value for of the quantity in in the hexahedral
cell.
connectivity : array_like
This should be of size (N,8) where N is the number of zones.
coordinates : array_like
This should be of size (M,3) where M is the number of vertices
indicated in the connectivity matrix.
bbox : array_like (xdim:zdim, LE:RE), optional
Size of computational domain in units of the length unit.
sim_time : float, optional
The simulation time in seconds
mass_unit : string
Unit to use for masses. Defaults to unitless.
time_unit : string
Unit to use for times. Defaults to unitless.
velocity_unit : string
Unit to use for velocities. Defaults to unitless.
magnetic_unit : string
Unit to use for magnetic fields. Defaults to unitless.
periodicity : tuple of booleans
Determines whether the data will be treated as periodic along
each axis
geometry : string or tuple
"cartesian", "cylindrical", "polar", "spherical", "geographic" or
"spectral_cube". Optionally, a tuple can be provided to specify the
axis ordering -- for instance, to specify that the axis ordering should
be z, x, y, this would be: ("cartesian", ("z", "x", "y")). The same
can be done for other coordinates, for instance:
("spherical", ("theta", "phi", "r")).
"""
domain_dimensions = np.ones(3, "int32") * 2
nprocs = 1
if bbox is None:
bbox = np.array([[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], 'float64')
domain_left_edge = np.array(bbox[:, 0], 'float64')
domain_right_edge = np.array(bbox[:, 1], 'float64')
grid_levels = np.zeros(nprocs, dtype='int32').reshape((nprocs,1))
field_units, data = unitify_data(data)
sfh = StreamDictFieldHandler()
particle_types = set_particle_types(data)
sfh.update({'connectivity': connectivity,
'coordinates': coordinates,
0: data})
# Simple check for axis length correctness
if len(data) > 0:
fn = list(sorted(data))[0]
array_values = data[fn]
if array_values.size != connectivity.shape[0]:
mylog.error("Dimensions of array must be one fewer than the" +
" coordinate set.")
raise RuntimeError
grid_left_edges = domain_left_edge
grid_right_edges = domain_right_edge
grid_dimensions = domain_dimensions.reshape(nprocs,3).astype("int32")
if length_unit is None:
length_unit = 'code_length'
if mass_unit is None:
mass_unit = 'code_mass'
if time_unit is None:
time_unit = 'code_time'
if velocity_unit is None:
velocity_unit = 'code_velocity'
if magnetic_unit is None:
magnetic_unit = 'code_magnetic'
# I'm not sure we need any of this.
handler = StreamHandler(
grid_left_edges,
grid_right_edges,
grid_dimensions,
grid_levels,
-np.ones(nprocs, dtype='int64'),
np.zeros(nprocs, dtype='int64').reshape(nprocs,1), # Temporary
np.zeros(nprocs).reshape((nprocs,1)),
sfh,
field_units,
(length_unit, mass_unit, time_unit, velocity_unit, magnetic_unit),
particle_types=particle_types,
periodicity=periodicity
)
handler.name = "HexahedralMeshData"
handler.domain_left_edge = domain_left_edge
handler.domain_right_edge = domain_right_edge
handler.refine_by = 2
handler.dimensionality = 3
handler.domain_dimensions = domain_dimensions
handler.simulation_time = sim_time
handler.cosmology_simulation = 0
sds = StreamHexahedralDataset(handler, geometry=geometry, unit_system=unit_system)
return sds
class StreamOctreeSubset(OctreeSubset):
domain_id = 1
_domain_offset = 1
def __init__(self, base_region, ds, oct_handler, over_refine_factor = 1):
self._num_zones = 1 << (over_refine_factor)
self.field_data = YTFieldData()
self.field_parameters = {}
self.ds = ds
self.oct_handler = oct_handler
self._last_mask = None
self._last_selector_id = None
self._current_particle_type = 'io'
self._current_fluid_type = self.ds.default_fluid_type
self.base_region = base_region
self.base_selector = base_region.selector
def fill(self, content, dest, selector, offset):
# Here we get a copy of the file, which we skip through and read the
# bits we want.
oct_handler = self.oct_handler
cell_count = selector.count_oct_cells(self.oct_handler, self.domain_id)
levels, cell_inds, file_inds = self.oct_handler.file_index_octs(
selector, self.domain_id, cell_count)
levels[:] = 0
dest.update((field, np.empty(cell_count, dtype="float64"))
for field in content)
# Make references ...
count = oct_handler.fill_level(0, levels, cell_inds, file_inds,
dest, content, offset)
return count
class StreamOctreeHandler(OctreeIndex):
def __init__(self, ds, dataset_type = None):
self.stream_handler = ds.stream_handler
self.dataset_type = dataset_type
super(StreamOctreeHandler, self).__init__(ds, dataset_type)
def _setup_data_io(self):
if self.stream_handler.io is not None:
self.io = self.stream_handler.io
else:
self.io = io_registry[self.dataset_type](self.ds)
def _initialize_oct_handler(self):
header = dict(dims = [1, 1, 1],
left_edge = self.ds.domain_left_edge,
right_edge = self.ds.domain_right_edge,
octree = self.ds.octree_mask,
over_refine = self.ds.over_refine_factor,
partial_coverage = self.ds.partial_coverage)
self.oct_handler = OctreeContainer.load_octree(header)
def _identify_base_chunk(self, dobj):
if getattr(dobj, "_chunk_info", None) is None:
base_region = getattr(dobj, "base_region", dobj)
subset = [StreamOctreeSubset(base_region, self.dataset,
self.oct_handler,
self.ds.over_refine_factor)]
dobj._chunk_info = subset
dobj._current_chunk = list(self._chunk_all(dobj))[0]
def _chunk_all(self, dobj):
oobjs = getattr(dobj._current_chunk, "objs", dobj._chunk_info)
yield YTDataChunk(dobj, "all", oobjs, None)
def _chunk_spatial(self, dobj, ngz, sort = None, preload_fields = None):
sobjs = getattr(dobj._current_chunk, "objs", dobj._chunk_info)
# We actually do not really use the data files except as input to the
# ParticleOctreeSubset.
# This is where we will perform cutting of the Octree and
# load-balancing. That may require a specialized selector object to
# cut based on some space-filling curve index.
for i,og in enumerate(sobjs):
if ngz > 0:
g = og.retrieve_ghost_zones(ngz, [], smoothed=True)
else:
g = og
yield YTDataChunk(dobj, "spatial", [g])
def _chunk_io(self, dobj, cache = True, local_only = False):
oobjs = getattr(dobj._current_chunk, "objs", dobj._chunk_info)
for subset in oobjs:
yield YTDataChunk(dobj, "io", [subset], None, cache = cache)
def _setup_classes(self):
dd = self._get_data_reader_dict()
super(StreamOctreeHandler, self)._setup_classes(dd)
def _detect_output_fields(self):
# NOTE: Because particle unions add to the actual field list, without
# having the keys in the field list itself, we need to double check
# here.
fl = set(self.stream_handler.get_fields())
fl.update(set(getattr(self, "field_list", [])))
self.field_list = list(fl)
class StreamOctreeDataset(StreamDataset):
_index_class = StreamOctreeHandler
_field_info_class = StreamFieldInfo
_dataset_type = "stream_octree"
def load_octree(octree_mask, data,
bbox=None, sim_time=0.0, length_unit=None,
mass_unit=None, time_unit=None,
velocity_unit=None, magnetic_unit=None,
periodicity=(True, True, True),
over_refine_factor = 1, partial_coverage = 1,
unit_system="cgs"):
r"""Load an octree mask into yt.
Octrees can be saved out by calling save_octree on an OctreeContainer.
This enables them to be loaded back in.
This will initialize an Octree of data. Note that fluid fields will not
work yet, or possibly ever.
Parameters
----------
octree_mask : np.ndarray[uint8_t]
This is a depth-first refinement mask for an Octree. It should be of
size n_octs * 8, where each item is 1 for an oct-cell being refined and
0 for it not being refined. Note that for over_refine_factors != 1,
the children count will still be 8, so this is always 8.
data : dict
A dictionary of 1D arrays. Note that these must of the size of the
number of "False" values in the ``octree_mask``.
bbox : array_like (xdim:zdim, LE:RE), optional
Size of computational domain in units of length
sim_time : float, optional
The simulation time in seconds
length_unit : string
Unit to use for lengths. Defaults to unitless.
mass_unit : string
Unit to use for masses. Defaults to unitless.
time_unit : string
Unit to use for times. Defaults to unitless.
velocity_unit : string
Unit to use for velocities. Defaults to unitless.
magnetic_unit : string
Unit to use for magnetic fields. Defaults to unitless.
periodicity : tuple of booleans
Determines whether the data will be treated as periodic along
each axis
partial_coverage : boolean
Whether or not an oct can be refined cell-by-cell, or whether all 8 get
refined.
"""
if not isinstance(octree_mask, np.ndarray) or octree_mask.dtype != np.uint8:
raise TypeError("octree_mask should be a Numpy array with type uint8")
nz = (1 << (over_refine_factor))
domain_dimensions = np.array([nz, nz, nz])
nprocs = 1
if bbox is None:
bbox = np.array([[0.0, 1.0], [0.0, 1.0], [0.0, 1.0]], 'float64')
domain_left_edge = np.array(bbox[:, 0], 'float64')
domain_right_edge = np.array(bbox[:, 1], 'float64')
grid_levels = np.zeros(nprocs, dtype='int32').reshape((nprocs,1))
update_field_names(data)
field_units, data = unitify_data(data)
sfh = StreamDictFieldHandler()
particle_types = set_particle_types(data)
sfh.update({0:data})
grid_left_edges = domain_left_edge
grid_right_edges = domain_right_edge
grid_dimensions = domain_dimensions.reshape(nprocs,3).astype("int32")
if length_unit is None:
length_unit = 'code_length'
if mass_unit is None:
mass_unit = 'code_mass'
if time_unit is None:
time_unit = 'code_time'
if velocity_unit is None:
velocity_unit = 'code_velocity'
if magnetic_unit is None:
magnetic_unit = 'code_magnetic'
# I'm not sure we need any of this.
handler = StreamHandler(
grid_left_edges,
grid_right_edges,
grid_dimensions,
grid_levels,
-np.ones(nprocs, dtype='int64'),
np.zeros(nprocs, dtype='int64').reshape(nprocs,1), # Temporary
np.zeros(nprocs).reshape((nprocs,1)),
sfh,
field_units,
(length_unit, mass_unit, time_unit, velocity_unit, magnetic_unit),
particle_types=particle_types,
periodicity=periodicity
)
handler.name = "OctreeData"
handler.domain_left_edge = domain_left_edge
handler.domain_right_edge = domain_right_edge
handler.refine_by = 2
handler.dimensionality = 3
handler.domain_dimensions = domain_dimensions
handler.simulation_time = sim_time
handler.cosmology_simulation = 0
sds = StreamOctreeDataset(handler, unit_system=unit_system)
sds.octree_mask = octree_mask
sds.partial_coverage = partial_coverage
sds.over_refine_factor = over_refine_factor
return sds
class StreamUnstructuredMesh(UnstructuredMesh):
_index_offset = 0
def __init__(self, *args, **kwargs):
super(StreamUnstructuredMesh, self).__init__(*args, **kwargs)
self._connectivity_length = self.connectivity_indices.shape[1]
class StreamUnstructuredIndex(UnstructuredIndex):
def __init__(self, ds, dataset_type = None):
self.stream_handler = ds.stream_handler
super(StreamUnstructuredIndex, self).__init__(ds, dataset_type)
def _initialize_mesh(self):
coords = ensure_list(self.stream_handler.fields.pop("coordinates"))
connec = ensure_list(self.stream_handler.fields.pop("connectivity"))
self.meshes = [StreamUnstructuredMesh(
i, self.index_filename, c1, c2, self)
for i, (c1, c2) in enumerate(zip(connec, coords))]
def _setup_data_io(self):
if self.stream_handler.io is not None:
self.io = self.stream_handler.io
else:
self.io = io_registry[self.dataset_type](self.ds)
def _detect_output_fields(self):
self.field_list = list(set(self.stream_handler.get_fields()))
class StreamUnstructuredMeshDataset(StreamDataset):
_index_class = StreamUnstructuredIndex
_field_info_class = StreamFieldInfo
_dataset_type = "stream_unstructured"
def load_unstructured_mesh(connectivity, coordinates, node_data=None,
elem_data=None, length_unit=None, bbox=None,
sim_time=0.0, mass_unit=None, time_unit=None,
velocity_unit=None, magnetic_unit=None,
periodicity=(False, False, False),
geometry = "cartesian", unit_system="cgs"):
r"""Load an unstructured mesh of data into yt as a
:class:`~yt.frontends.stream.data_structures.StreamHandler`.
This should allow an unstructured mesh data to be loaded directly into
yt and analyzed as would any others. Not all functionality for
visualization will be present, and some analysis functions may not yet have
been implemented.
Particle fields are detected as one-dimensional fields. The number of
particles is set by the "number_of_particles" key in data.
In the parameter descriptions below, a "vertex" is a 3D point in space, an
"element" is a single polyhedron whose location is defined by a set of
vertices, and a "mesh" is a set of polyhedral elements, each with the same
number of vertices.
Parameters
----------
connectivity : list of array_like or array_like
This should either be a single 2D array or list of 2D arrays. If this
is a list, each element in the list corresponds to the connectivity
information for a distinct mesh. Each array can have different
connectivity length and should be of shape (N,M) where N is the number
of elements and M is the number of vertices per element.
coordinates : array_like
The 3D coordinates of mesh vertices. This should be of size (L,3) where
L is the number of vertices. When loading more than one mesh, the data
for each mesh should be concatenated into a single coordinates array.
node_data : dict or list of dicts
For a single mesh, a dict mapping field names to 2D numpy arrays,
representing data defined at element vertices. For multiple meshes,
this must be a list of dicts.
elem_data : dict or list of dicts
For a single mesh, a dict mapping field names to 1D numpy arrays, where
each array has a length equal to the number of elements. The data
must be defined at the center of each mesh element and there must be
only one data value for each element. For multiple meshes, this must be
a list of dicts, with one dict for each mesh.
bbox : array_like (xdim:zdim, LE:RE), optional
Size of computational domain in units of the length unit.
sim_time : float, optional
The simulation time in seconds
mass_unit : string
Unit to use for masses. Defaults to unitless.
time_unit : string
Unit to use for times. Defaults to unitless.
velocity_unit : string
Unit to use for velocities. Defaults to unitless.
magnetic_unit : string
Unit to use for magnetic fields. Defaults to unitless.
periodicity : tuple of booleans
Determines whether the data will be treated as periodic along
each axis
geometry : string or tuple
"cartesian", "cylindrical", "polar", "spherical", "geographic" or
"spectral_cube". Optionally, a tuple can be provided to specify the
axis ordering -- for instance, to specify that the axis ordering should
be z, x, y, this would be: ("cartesian", ("z", "x", "y")). The same
can be done for other coordinates, for instance:
("spherical", ("theta", "phi", "r")).
>>> # Coordinates for vertices of two tetrahedra
>>> coordinates = np.array([[0.0, 0.0, 0.5], [0.0, 1.0, 0.5], [0.5, 1, 0.5],
[0.5, 0.5, 0.0], [0.5, 0.5, 1.0]])
>>> # The indices in the coordinates array of mesh vertices.
>>> # This mesh has two elements.
>>> connectivity = np.array([[0, 1, 2, 4], [0, 1, 2, 3]])
>>> # Field data defined at the centers of the two mesh elements.
>>> elem_data = {
... ('connect1', 'elem_field'): np.array([1, 2])
... }
>>> # Field data defined at node vertices
>>> node_data = {
... ('connect1', 'node_field'): np.array([[0.0, 1.0, 2.0, 4.0],
... [0.0, 1.0, 2.0, 3.0]])
... }
>>> ds = yt.load_unstructured_mesh(connectivity, coordinates,
... elem_data=elem_data,
... node_data=node_data)
"""
domain_dimensions = np.ones(3, "int32") * 2
nprocs = 1
if elem_data is None and node_data is None:
raise RuntimeError("No data supplied in load_unstructured_mesh.")
if isinstance(connectivity, list):
num_meshes = len(connectivity)
else:
num_meshes = 1
connectivity = ensure_list(connectivity)
if elem_data is None:
elem_data = [{} for i in range(num_meshes)]
elem_data = ensure_list(elem_data)
if node_data is None:
node_data = [{} for i in range(num_meshes)]
node_data = ensure_list(node_data)
data = [{} for i in range(num_meshes)]
for elem_dict, data_dict in zip(elem_data, data):
for field, values in elem_dict.items():
data_dict[field] = values
for node_dict, data_dict in zip(node_data, data):
for field, values in node_dict.items():
data_dict[field] = values
data = ensure_list(data)
if bbox is None:
bbox = np.array([[coordinates[:,i].min() - 0.1 * abs(coordinates[:,i].min()),
coordinates[:,i].max() + 0.1 * abs(coordinates[:,i].max())]
for i in range(3)], "float64")
domain_left_edge = np.array(bbox[:, 0], 'float64')
domain_right_edge = np.array(bbox[:, 1], 'float64')
grid_levels = np.zeros(nprocs, dtype='int32').reshape((nprocs,1))
field_units = {}
particle_types = {}
sfh = StreamDictFieldHandler()
sfh.update({'connectivity': connectivity,
'coordinates': coordinates})
for i, d in enumerate(data):
_f_unit, _data = unitify_data(d)
field_units.update(_f_unit)
sfh[i] = _data
particle_types.update(set_particle_types(d))
# Simple check for axis length correctness
if 0 and len(data) > 0:
fn = list(sorted(data))[0]
array_values = data[fn]
if array_values.size != connectivity.shape[0]:
mylog.error("Dimensions of array must be one fewer than the" +
" coordinate set.")
raise RuntimeError
grid_left_edges = domain_left_edge
grid_right_edges = domain_right_edge
grid_dimensions = domain_dimensions.reshape(nprocs,3).astype("int32")
if length_unit is None:
length_unit = 'code_length'
if mass_unit is None:
mass_unit = 'code_mass'
if time_unit is None:
time_unit = 'code_time'
if velocity_unit is None:
velocity_unit = 'code_velocity'
if magnetic_unit is None:
magnetic_unit = 'code_magnetic'
# I'm not sure we need any of this.
handler = StreamHandler(
grid_left_edges,
grid_right_edges,
grid_dimensions,
grid_levels,
-np.ones(nprocs, dtype='int64'),
np.zeros(nprocs, dtype='int64').reshape(nprocs,1), # Temporary
np.zeros(nprocs).reshape((nprocs,1)),
sfh,
field_units,
(length_unit, mass_unit, time_unit, velocity_unit, magnetic_unit),
particle_types=particle_types,
periodicity=periodicity
)
handler.name = "UnstructuredMeshData"
handler.domain_left_edge = domain_left_edge
handler.domain_right_edge = domain_right_edge
handler.refine_by = 2
handler.dimensionality = 3
handler.domain_dimensions = domain_dimensions
handler.simulation_time = sim_time
handler.cosmology_simulation = 0
sds = StreamUnstructuredMeshDataset(handler, geometry=geometry,
unit_system=unit_system)
fluid_types = ()
for i in range(1, num_meshes + 1):
fluid_types += ('connect%d' % i,)
sds.fluid_types = fluid_types
sds._node_fields = node_data[0].keys()
sds._elem_fields = elem_data[0].keys()
sds.default_field = [f for f in sds.field_list
if f[0] == 'connect1'][-1]
return sds
| 39.166394
| 101
| 0.623133
|
4a0a91bc16fd8054c1bef8d01a7d432a790bd32a
| 7,582
|
py
|
Python
|
src/oscar/defaults.py
|
quangvinh1305/django-oscar
|
ec51f0d36d0bc148cb33f63362d6d55c9f583849
|
[
"BSD-3-Clause"
] | null | null | null |
src/oscar/defaults.py
|
quangvinh1305/django-oscar
|
ec51f0d36d0bc148cb33f63362d6d55c9f583849
|
[
"BSD-3-Clause"
] | null | null | null |
src/oscar/defaults.py
|
quangvinh1305/django-oscar
|
ec51f0d36d0bc148cb33f63362d6d55c9f583849
|
[
"BSD-3-Clause"
] | null | null | null |
from collections import OrderedDict
from django.urls import reverse_lazy
from django.utils.translation import gettext_lazy as _
OSCAR_SHOP_NAME = 'Xhealthy'
OSCAR_SHOP_TAGLINE = ''
OSCAR_HOMEPAGE = reverse_lazy('catalogue:index')
# Dynamic class loading
OSCAR_DYNAMIC_CLASS_LOADER = 'oscar.core.loading.default_class_loader'
# Basket settings
OSCAR_BASKET_COOKIE_LIFETIME = 7 * 24 * 60 * 60
OSCAR_BASKET_COOKIE_OPEN = 'oscar_open_basket'
OSCAR_BASKET_COOKIE_SECURE = False
OSCAR_MAX_BASKET_QUANTITY_THRESHOLD = 10000
# Recently-viewed products
OSCAR_RECENTLY_VIEWED_COOKIE_LIFETIME = 7 * 24 * 60 * 60
OSCAR_RECENTLY_VIEWED_COOKIE_NAME = 'oscar_history'
OSCAR_RECENTLY_VIEWED_COOKIE_SECURE = False
OSCAR_RECENTLY_VIEWED_PRODUCTS = 20
# Currency
OSCAR_DEFAULT_CURRENCY = 'VND'
# Paths
OSCAR_IMAGE_FOLDER = 'images/products/%Y/%m/'
OSCAR_DELETE_IMAGE_FILES = True
# Copy this image from oscar/static/img to your MEDIA_ROOT folder.
# It needs to be there so Sorl can resize it.
OSCAR_MISSING_IMAGE_URL = 'image_not_found.jpg'
# Address settings
OSCAR_REQUIRED_ADDRESS_FIELDS = ('first_name', 'last_name', 'line1')
# Pagination settings
OSCAR_OFFERS_PER_PAGE = 20
OSCAR_PRODUCTS_PER_PAGE = 20
OSCAR_REVIEWS_PER_PAGE = 20
OSCAR_NOTIFICATIONS_PER_PAGE = 20
OSCAR_EMAILS_PER_PAGE = 20
OSCAR_ORDERS_PER_PAGE = 20
OSCAR_ADDRESSES_PER_PAGE = 20
OSCAR_STOCK_ALERTS_PER_PAGE = 20
OSCAR_DASHBOARD_ITEMS_PER_PAGE = 20
# Checkout
OSCAR_ALLOW_ANON_CHECKOUT = False
# Reviews
OSCAR_ALLOW_ANON_REVIEWS = True
OSCAR_MODERATE_REVIEWS = False
# Accounts
OSCAR_ACCOUNTS_REDIRECT_URL = 'customer:profile-view'
# This enables sending alert notifications/emails instantly when products get
# back in stock by listening to stock record update signals.
# This might impact performance for large numbers of stock record updates.
# Alternatively, the management command ``oscar_send_alerts`` can be used to
# run periodically, e.g. as a cron job. In this case eager alerts should be
# disabled.
OSCAR_EAGER_ALERTS = True
# Registration
OSCAR_SEND_REGISTRATION_EMAIL = True
OSCAR_FROM_EMAIL = 'oscar@example.com'
# Slug handling
OSCAR_SLUG_FUNCTION = 'oscar.core.utils.default_slugifier'
OSCAR_SLUG_MAP = {}
OSCAR_SLUG_BLACKLIST = []
OSCAR_SLUG_ALLOW_UNICODE = False
# Cookies
OSCAR_COOKIES_DELETE_ON_LOGOUT = ['oscar_recently_viewed_products', ]
# Offers
OSCAR_OFFERS_INCL_TAX = False
# Hidden Oscar features, e.g. wishlists or reviews
OSCAR_HIDDEN_FEATURES = []
# Menu structure of the dashboard navigation
OSCAR_DASHBOARD_NAVIGATION = [
{
'label': _('Dashboard'),
'icon': 'fas fa-list',
'url_name': 'dashboard:index',
},
{
'label': _('Catalogue'),
'icon': 'fas fa-sitemap',
'children': [
{
'label': _('Products'),
'url_name': 'dashboard:catalogue-product-list',
},
{
'label': _('Product Types'),
'url_name': 'dashboard:catalogue-class-list',
},
{
'label': _('Categories'),
'url_name': 'dashboard:catalogue-category-list',
},
{
'label': _('Ranges'),
'url_name': 'dashboard:range-list',
},
{
'label': _('Low stock alerts'),
'url_name': 'dashboard:stock-alert-list',
},
{
'label': _('Options'),
'url_name': 'dashboard:catalogue-option-list',
},
]
},
{
'label': _('Fulfilment'),
'icon': 'fas fa-shopping-cart',
'children': [
{
'label': _('Orders'),
'url_name': 'dashboard:order-list',
},
{
'label': _('Statistics'),
'url_name': 'dashboard:order-stats',
},
{
'label': _('Partners'),
'url_name': 'dashboard:partner-list',
},
# The shipping method dashboard is disabled by default as it might
# be confusing. Weight-based shipping methods aren't hooked into
# the shipping repository by default (as it would make
# customising the repository slightly more difficult).
# {
# 'label': _('Shipping charges'),
# 'url_name': 'dashboard:shipping-method-list',
# },
]
},
{
'label': _('Customers'),
'icon': 'fas fa-users',
'children': [
{
'label': _('Customers'),
'url_name': 'dashboard:users-index',
},
{
'label': _('Stock alert requests'),
'url_name': 'dashboard:user-alert-list',
},
]
},
{
'label': _('Offers'),
'icon': 'fas fa-bullhorn',
'children': [
{
'label': _('Offers'),
'url_name': 'dashboard:offer-list',
},
{
'label': _('Vouchers'),
'url_name': 'dashboard:voucher-list',
},
{
'label': _('Voucher Sets'),
'url_name': 'dashboard:voucher-set-list',
},
],
},
{
'label': _('Content'),
'icon': 'fas fa-folder',
'children': [
{
'label': _('Pages'),
'url_name': 'dashboard:page-list',
},
{
'label': _('Email templates'),
'url_name': 'dashboard:comms-list',
},
{
'label': _('Reviews'),
'url_name': 'dashboard:reviews-list',
},
]
},
{
'label': _('Reports'),
'icon': 'fas fa-chart-bar',
'url_name': 'dashboard:reports-index',
},
]
OSCAR_DASHBOARD_DEFAULT_ACCESS_FUNCTION = 'oscar.apps.dashboard.nav.default_access_fn' # noqa
# Search facets
OSCAR_SEARCH_FACETS = {
'fields': OrderedDict([
# The key for these dicts will be used when passing facet data
# to the template. Same for the 'queries' dict below.
('product_class', {'name': _('Type'), 'field': 'product_class'}),
('rating', {'name': _('Rating'), 'field': 'rating'}),
# You can specify an 'options' element that will be passed to the
# SearchQuerySet.facet() call.
# For instance, with Elasticsearch backend, 'options': {'order': 'term'}
# will sort items in a facet by title instead of number of items.
# It's hard to get 'missing' to work
# correctly though as of Solr's hilarious syntax for selecting
# items without a specific facet:
# http://wiki.apache.org/solr/SimpleFacetParameters#facet.method
# 'options': {'missing': 'true'}
]),
'queries': OrderedDict([
('price_range',
{
'name': _('Price range'),
'field': 'price',
'queries': [
# This is a list of (name, query) tuples where the name will
# be displayed on the front-end.
(_('0 to 20'), '[0 TO 20]'),
(_('20 to 40'), '[20 TO 40]'),
(_('40 to 60'), '[40 TO 60]'),
(_('60+'), '[60 TO *]'),
]
}),
]),
}
OSCAR_PRODUCT_SEARCH_HANDLER = None
OSCAR_THUMBNAILER = 'oscar.core.thumbnails.SorlThumbnail'
OSCAR_URL_SCHEMA = 'http'
OSCAR_SAVE_SENT_EMAILS_TO_DB = True
| 30.207171
| 94
| 0.570034
|
4a0a91c532ef48f71ad69c1a9d9e3d8537c1e669
| 16,135
|
py
|
Python
|
tests/pfc/test_unknown_mac.py
|
ysmanman/sonic-mgmt
|
f6b129ede1521211370520dcd4a57279f84e940a
|
[
"Apache-2.0"
] | 2
|
2020-07-03T01:16:27.000Z
|
2020-10-09T05:38:07.000Z
|
tests/pfc/test_unknown_mac.py
|
ysmanman/sonic-mgmt
|
f6b129ede1521211370520dcd4a57279f84e940a
|
[
"Apache-2.0"
] | 2
|
2021-08-18T18:21:10.000Z
|
2021-08-23T13:49:11.000Z
|
tests/pfc/test_unknown_mac.py
|
ysmanman/sonic-mgmt
|
f6b129ede1521211370520dcd4a57279f84e940a
|
[
"Apache-2.0"
] | 1
|
2020-07-02T02:49:56.000Z
|
2020-07-02T02:49:56.000Z
|
import functools
import inspect
import json
import logging
import pytest
import random
import re
import time
import ptf.testutils as testutils
import ptf.mask as mask
import ptf.packet as packet
from tests.common import constants
from tests.common.fixtures.ptfhost_utils import change_mac_addresses
from tests.common.fixtures.ptfhost_utils import copy_arp_responder_py
from tests.common.helpers.assertions import pytest_assert
from tests.common.dualtor.dual_tor_utils import mux_cable_server_ip
from tests.common.dualtor.mux_simulator_control import toggle_all_simulator_ports_to_rand_selected_tor
from tests.common.utilities import get_intf_by_sub_intf
logger = logging.getLogger(__name__)
pytestmark = [pytest.mark.topology("t0")]
TEST_PKT_CNT = 10
def initClassVars(func):
"""
Automatically assign instance variables. currently handles only arg list
"""
names, varargs, keywords, defaults = inspect.getargspec(func)
@functools.wraps(func)
def wrapper(self, *args):
for name, value in list(zip(names[1:], args)):
setattr(self, name, value)
func(self, *args)
return wrapper
@pytest.fixture(autouse=True, scope="module")
def unknownMacSetup(duthosts, rand_one_dut_hostname, tbinfo):
"""
Fixture to populate all the parameters needed for the test
Args:
duthosts(AnsibleHost) : multi dut instance
rand_one_dut_hostname(string) : one of the dut instances from the multi dut
tbinfo(TestbedInfo) : testbed info
Yields:
setup(dict): dict of vlan, ptf, portchannel intf mappings
"""
duthost = duthosts[rand_one_dut_hostname]
mg_facts = duthost.get_extended_minigraph_facts(tbinfo)
is_backend_topology = mg_facts.get(constants.IS_BACKEND_TOPOLOGY_KEY, False)
server_ips = []
if 'dualtor' in tbinfo['topo']['name']:
servers = mux_cable_server_ip(duthost)
for ips in servers.values():
server_ips.append(ips['server_ipv4'].split('/')[0])
# populate vlan info
vlan = dict()
vlan['addr'] = mg_facts['minigraph_vlan_interfaces'][0]['addr']
vlan['pfx'] = mg_facts['minigraph_vlan_interfaces'][0]['prefixlen']
vlan['ips'] = duthost.get_ip_in_range(num=1, prefix="{}/{}".format(vlan['addr'], vlan['pfx']),
exclude_ips=[vlan['addr']] + server_ips)['ansible_facts']['generated_ips']
vlan['hostip'] = vlan['ips'][0].split('/')[0]
vlan['ports'] = mg_facts["minigraph_vlans"].values()[0]["members"]
# populate dst intf and ptf id
ptf_portmap = mg_facts['minigraph_ptf_indices']
dst_port = random.choice(vlan['ports'])
if is_backend_topology:
ptf_dst_port = str(ptf_portmap[dst_port]) + constants.VLAN_SUB_INTERFACE_SEPARATOR + \
mg_facts["minigraph_vlans"].values()[0]["vlanid"]
else:
ptf_dst_port = ptf_portmap[dst_port]
ptf_vlan_ports = [ptf_portmap[ifname] for ifname in vlan['ports']]
# populate portchannel intf, peer address and ptf ids
pc = dict()
intfs = list()
ptf_ports = dict()
sub_intfs = set()
if is_backend_topology:
for vlan_sub_interface in mg_facts['minigraph_vlan_sub_interfaces']:
sub_intf_name = vlan_sub_interface['attachto']
if sub_intf_name in intfs:
continue
vlan_id = vlan_sub_interface['vlan']
intf_name = get_intf_by_sub_intf(sub_intf_name, vlan_id)
sub_intfs.add(sub_intf_name)
ptf_ports[sub_intf_name] = (ptf_portmap[intf_name], sub_intf_name,
vlan_sub_interface['peer_addr'],
vlan_id)
intfs = list(sub_intfs)
else:
for key in mg_facts['minigraph_portchannels']:
value = mg_facts['minigraph_portchannels'][key]
for item in value['members']:
intfs.append(item)
ptf_ports[item] = (ptf_portmap[item], item, None, None)
pc.setdefault(key, []).append(item)
for element in mg_facts['minigraph_portchannel_interfaces']:
if key in element['attachto']:
for member in pc[key]:
tmp_list = list(ptf_ports[member])
tmp_list[2] = element['peer_addr']
ptf_ports[member] = tuple(tmp_list)
break
setup = {'vlan': vlan,
'dst_port': dst_port,
'ptf_dst_port': ptf_dst_port,
'ptf_vlan_ports': ptf_vlan_ports,
'intfs': intfs,
'ptf_ports': ptf_ports
}
yield setup
@pytest.fixture
def flushArpFdb(duthosts, rand_one_dut_hostname):
"""
Fixture to flush all ARP and FDB entries
Args:
duthosts(AnsibleHost) : multi dut instance
rand_one_dut_hostname(string) : one of the dut instances from the multi dut
"""
duthost = duthosts[rand_one_dut_hostname]
logger.info("Clear all ARP and FDB entries on the DUT")
duthost.shell("sonic-clear fdb all")
duthost.shell("ip neigh flush all")
yield
logger.info("Clear all ARP and FDB entries on the DUT")
duthost.shell("sonic-clear fdb all")
duthost.shell("ip neigh flush all")
@pytest.fixture(autouse=True)
def populateArp(unknownMacSetup, flushArpFdb, ptfhost, duthosts, rand_one_dut_hostname,
toggle_all_simulator_ports_to_rand_selected_tor):
"""
Fixture to populate ARP entry on the DUT for the traffic destination
Args:
unknownMacSetup(fixture) : module scope autouse fixture for test setup
flushArpFdb(fixture) : func scope fixture
ptfhost(AnsibleHost) : ptf host instance
duthosts(AnsibleHost) : multi dut instance
rand_one_dut_hostname(string) : one of the dut instances from the multi dut
"""
# Wait 5 seconds for mux to toggle
time.sleep(5)
duthost = duthosts[rand_one_dut_hostname]
setup = unknownMacSetup
ptfhost.script("./scripts/remove_ip.sh")
logger.info("Populate ARP entry for dest port")
ptfhost.command("ifconfig eth{} {}".format(setup['ptf_dst_port'], setup['vlan']['ips'][0]))
ptfhost.command("ping {} -c 3".format(setup['vlan']['addr']))
# Wait 5 seconds for secondary ARP before proceeding to clear FDB
time.sleep(5)
yield
logger.info("Clean up all ips on the PTF")
ptfhost.script("./scripts/remove_ip.sh")
class PreTestVerify(object):
""" Verify ARP and FDB entries are populated correctly """
def __init__(self, duthost, dst_ip, dst_port):
"""
Args:
duthost(AnsibleHost) : dut instance
dst_ip(string): traffic dest ip
dst_port(int): ptf id for the dest port
"""
self.duthost = duthost
self.dst_ip = dst_ip
self.dst_port = dst_port
self.arp_entry = dict()
def _checkArpEntryExist(self):
"""
Check if the ARP entry is present and populate the ARP to mac mapping
"""
logger.info("Verify if the ARP entry is present for {}".format(self.dst_ip))
result = self.duthost.command("show arp {}".format(self.dst_ip))
pytest_assert("Total number of entries 1" in result['stdout'],
"ARP entry for {} missing in ASIC".format(self.dst_ip))
result = self.duthost.shell("ip neigh show {}".format(self.dst_ip))
pytest_assert(result['stdout_lines'], "{} not in arp table".format(self.dst_ip))
match = re.match("{}.*lladdr\s+(.*)\s+[A-Z]+".format(self.dst_ip),
result['stdout_lines'][0])
pytest_assert(match,
"Regex failed while retreiving arp entry for {}".format(self.dst_ip))
self.arp_entry.update({self.dst_ip: match.group(1)})
def _checkFdbEntryMiss(self):
"""
Check if the FDB entry is missing for the port
"""
result = self.duthost.command("show mac -p {}".format(self.dst_port),
module_ignore_errors=True)
out = result['stdout']
pytest_assert("not in list" in out, "{} present in FDB".format(self.arp_entry[self.dst_ip]))
logger.info("'{}' not present in fdb as expected".format(self.arp_entry[self.dst_ip]))
def verifyArpFdb(self):
"""
Validate ARP and FDB entries prior to the test run
Returns:
arp_entry(dict) : ARP to mac mapping
"""
self._checkArpEntryExist()
logger.info("Clear all FDB entries")
self.duthost.shell("sonic-clear fdb all")
time.sleep(5)
self._checkFdbEntryMiss()
return self.arp_entry
class TrafficSendVerify(object):
""" Send traffic and check interface counters and ptf ports """
@initClassVars
def __init__(self, duthost, ptfadapter, dst_ip, ptf_dst_port, ptf_vlan_ports,
intfs, ptf_ports, arp_entry, dscp):
"""
Args:
duthost(AnsibleHost) : dut instance
ptfadapter(dataplane) : ptf runner instance
dst_ip(string) : traffic dest ip
ptf_dst_port(int) : ptf index of dest port
ptf_vlan_ports(list) : ptf indices of all DUT vlan ports
intfs(list) : all portchannel members/sub interfaces
ptf_ports(dict) : mapping of pc member/sub interface to ptf id, peer addr
arp_entry(dict) : ARP to mac mapping
dscp(int) : dscp value to be used for the packet that gets send out
"""
self.pkts = list()
self.exp_pkts = list()
self.pkt_map = dict()
self.pre_rx_drops = dict()
self.dut_mac = duthost.facts['router_mac']
def _constructPacket(self):
"""
Build list of packets to be sent and expected
"""
for idx, intf in enumerate(self.ptf_ports):
udp_sport = random.randint(0, 65535)
udp_dport = random.randint(0, 65535)
src_port = self.ptf_ports[intf][0]
src_ip = self.ptf_ports[intf][2]
vlan_id = self.ptf_ports[intf][3]
pkt = testutils.simple_udp_packet(eth_dst=self.dut_mac,
eth_src=self.ptfadapter.dataplane.get_mac(0, src_port),
ip_dst=self.dst_ip,
ip_src=src_ip,
ip_tos=self.dscp << 2,
udp_sport=udp_sport,
udp_dport=udp_dport,
ip_ttl=64
)
self.pkts.append(pkt)
tmp_pkt = testutils.simple_udp_packet(eth_dst=self.arp_entry[self.dst_ip],
eth_src=self.dut_mac,
ip_dst=self.dst_ip,
ip_src=src_ip,
ip_tos=self.dscp << 2,
udp_sport=udp_sport,
udp_dport=udp_dport,
ip_ttl=63
)
tmp_pkt = mask.Mask(tmp_pkt)
tmp_pkt.set_do_not_care_scapy(packet.IP, "chksum")
self.exp_pkts.append(tmp_pkt)
# if inft is a sub interface, tuple be like ("Eth0.10", "Eth0")
# if inft is a general interface, tuple be like ("Eth0", "Eth0")
self.pkt_map[pkt] = (intf, get_intf_by_sub_intf(intf, vlan_id))
def _parseCntrs(self):
"""
Parse the port stats
Returns:
stats(dict) : mapping of interface to interface counters
"""
result = self.duthost.command("portstat -j")["stdout"]
match = re.search("Last cached time was.*\n", result)
if match:
result = re.sub("Last cached time was.*\n", "", result)
stats = json.loads(result)
return stats
def _verifyIntfCounters(self, pretest=False):
"""
Collect counters before and after the test and verify them
Args:
pretest(bool): collect counters before or after the test run
"""
stats = self._parseCntrs()
for key, value in self.pkt_map.items():
intf = value[1]
if pretest:
self.pre_rx_drops[intf] = int(stats[intf]['RX_DRP'])
else:
actual_cnt = int(stats[intf]['RX_DRP'])
exp_cnt = self.pre_rx_drops[intf] + TEST_PKT_CNT
pytest_assert(actual_cnt >= exp_cnt,
"Pkt dropped cnt incorrect for intf {}. Expected: {}, Obtained: {}".format(intf, exp_cnt,
actual_cnt))
logger.info("Pkt count dropped on interface {}: {}, Expected: {}".format(intf, actual_cnt, exp_cnt))
def runTest(self):
"""
Test run and verification
"""
self._constructPacket()
logger.info("Clear all counters before test run")
self.duthost.command("sonic-clear counters")
time.sleep(1)
logger.info("Collect drop counters before test run")
self._verifyIntfCounters(pretest=True)
for pkt, exp_pkt in zip(self.pkts, self.exp_pkts):
self.ptfadapter.dataplane.flush()
out_intf = self.pkt_map[pkt][0]
src_port = self.ptf_ports[out_intf][0]
logger.info("Sending traffic on intf {}".format(out_intf))
testutils.send(self.ptfadapter, src_port, pkt, count=TEST_PKT_CNT)
testutils.verify_no_packet_any(self.ptfadapter, exp_pkt, ports=self.ptf_vlan_ports)
logger.info("Collect and verify drop counters after test run")
self._verifyIntfCounters()
class TestUnknownMac(object):
@pytest.mark.parametrize("dscp", ["dscp-3", "dscp-4", "dscp-8"])
def test_unknown_mac(self, unknownMacSetup, dscp, duthosts, rand_one_dut_hostname, ptfadapter):
"""
Verify unknown mac behavior for lossless and lossy priority
This test ensures that packets send on lossless and lossy priority get dropped
when the arp to mac mapping is present in the arp table and mac to port mapping
is absent in the mac table
Args:
unknownMacSetup(fixture) : module scope autouse fixture for test setup
dscp(string) : parametrized values for dscp
duthosts(AnsibleHost) : multi dut instance
rand_one_dut_hostname(AnsibleHost) : one of the dut instances from the multi dut
ptfadapter(dataplane) : ptf runner instance
"""
setup = unknownMacSetup
self.dscp = int(dscp.split("-")[-1])
self.duthost = duthosts[rand_one_dut_hostname]
self.ptfadapter = ptfadapter
self.dst_port = setup['dst_port']
self.ptf_dst_port = setup['ptf_dst_port']
self.dst_ip = setup['vlan']['hostip']
self.vlan_ports = setup['vlan']['ports']
self.ptf_vlan_ports = setup['ptf_vlan_ports']
self.intfs = setup['intfs']
self.ptf_ports = setup['ptf_ports']
self.validateEntries()
self.run()
def validateEntries(self):
"""
Validate ARP and FDB prior to the test run
"""
pre_handle = PreTestVerify(self.duthost, self.dst_ip, self.dst_port)
self.arp_entry = pre_handle.verifyArpFdb()
def run(self):
"""
Traffic test and verification
"""
thandle = TrafficSendVerify(self.duthost, self.ptfadapter, self.dst_ip, self.ptf_dst_port,
self.ptf_vlan_ports,
self.intfs, self.ptf_ports,
self.arp_entry, self.dscp)
thandle.runTest()
| 41.478149
| 119
| 0.593616
|
4a0a93aec6aeab1dca3e420d491be431cdee7c08
| 3,966
|
py
|
Python
|
search/seg_metrics.py
|
songzijiang/FasterSeg
|
1a14ef6dd665afd229a16ab43b532b5a406512f8
|
[
"MIT"
] | 334
|
2019-12-20T02:43:08.000Z
|
2020-08-11T07:14:21.000Z
|
search/seg_metrics.py
|
songzijiang/FasterSeg
|
1a14ef6dd665afd229a16ab43b532b5a406512f8
|
[
"MIT"
] | 39
|
2019-12-23T04:05:29.000Z
|
2020-08-01T20:14:04.000Z
|
search/seg_metrics.py
|
songzijiang/FasterSeg
|
1a14ef6dd665afd229a16ab43b532b5a406512f8
|
[
"MIT"
] | 63
|
2019-12-21T11:05:52.000Z
|
2020-07-27T11:54:55.000Z
|
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Created by: Hang Zhang
# ECE Department, Rutgers University
## Email: zhang.hang@rutgers.edu
# Copyright (c) 2017
##
# This source code is licensed under the MIT-style license found in the
# LICENSE file in the root directory of this source tree
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
import numpy as np
import torch
class Seg_Metrics(object):
def __init__(self, n_classes=19):
self.n_classes = n_classes
self.total_inter = np.zeros(n_classes)
self.total_union = np.zeros(n_classes)
def update(self, pred, target):
inter, union = batch_intersection_union(pred, target, self.n_classes)
self.total_inter += inter
self.total_union += union
def get_scores(self):
idx = self.total_union > 0
IoU = 1.0 * self.total_inter[idx] / (np.spacing(1) + self.total_union[idx])
mIoU = IoU.mean()
return mIoU
def reset(self):
self.total_inter = np.zeros(n_classes)
self.total_union = np.zeros(n_classes)
def batch_pix_accuracy(predict, target):
"""Batch Pixel Accuracy
Args:
predict: input 4D tensor
target: label 3D tensor
"""
_, predict = torch.max(predict, 1)
predict = predict.cpu().numpy() + 1
target = target.cpu().numpy() + 1
pixel_labeled = np.sum(target > 0)
pixel_correct = np.sum((predict == target)*(target > 0))
assert pixel_correct <= pixel_labeled, \
"Correct area should be smaller than Labeled"
return pixel_correct, pixel_labeled
def batch_intersection_union(predict, target, nclass):
"""Batch Intersection of Union
Args:
predict: input 4D tensor
target: label 3D tensor
nclass: number of categories (int)
"""
_, predict = torch.max(predict, 1)
mini = 1
maxi = nclass
nbins = nclass
predict = predict.cpu().numpy() + 1
target = target.cpu().numpy() + 1
k = (target >= 1) & (target <= nclass)
# predict = predict * (target > 0).astype(predict.dtype)
predict = predict * k.astype(predict.dtype)
intersection = predict * (predict == target)
# areas of intersection and union
area_inter, _ = np.histogram(intersection, bins=nbins, range=(mini, maxi))
area_pred, _ = np.histogram(predict, bins=nbins, range=(mini, maxi))
area_lab, _ = np.histogram(target, bins=nbins, range=(mini, maxi))
area_union = area_pred + area_lab - area_inter
assert (area_inter <= area_union).all(), \
"Intersection area should be smaller than Union area"
return area_inter, area_union
# ref https://github.com/CSAILVision/sceneparsing/blob/master/evaluationCode/utils_eval.py
def pixel_accuracy(im_pred, im_lab):
im_pred = np.asarray(im_pred)
im_lab = np.asarray(im_lab)
# Remove classes from unlabeled pixels in gt image.
# We should not penalize detections in unlabeled portions of the image.
pixel_labeled = np.sum(im_lab > 0)
pixel_correct = np.sum((im_pred == im_lab) * (im_lab > 0))
#pixel_accuracy = 1.0 * pixel_correct / pixel_labeled
return pixel_correct, pixel_labeled
def intersection_and_union(im_pred, im_lab, num_class):
im_pred = np.asarray(im_pred)
im_lab = np.asarray(im_lab)
# Remove classes from unlabeled pixels in gt image.
im_pred = im_pred * (im_lab > 0)
# Compute area intersection:
intersection = im_pred * (im_pred == im_lab)
area_inter, _ = np.histogram(intersection, bins=num_class-1,
range=(1, num_class - 1))
# Compute area union:
area_pred, _ = np.histogram(im_pred, bins=num_class-1,
range=(1, num_class - 1))
area_lab, _ = np.histogram(im_lab, bins=num_class-1,
range=(1, num_class - 1))
area_union = area_pred + area_lab - area_inter
return area_inter, area_union
| 36.054545
| 90
| 0.63061
|
4a0a9449cebf24f6afb5eaa8a7fa985bcb29c04f
| 9,144
|
py
|
Python
|
rapid/client/controllers/work_controller.py
|
m2bright/rapid
|
fd66515105ca9773c5da8562a878c6b0bfa4487a
|
[
"Apache-2.0"
] | 4
|
2018-04-12T20:16:04.000Z
|
2020-03-03T08:09:19.000Z
|
rapid/client/controllers/work_controller.py
|
m2bright/rapid
|
fd66515105ca9773c5da8562a878c6b0bfa4487a
|
[
"Apache-2.0"
] | 69
|
2019-03-13T21:30:51.000Z
|
2021-12-08T16:54:05.000Z
|
rapid/client/controllers/work_controller.py
|
m2bright/rapid
|
fd66515105ca9773c5da8562a878c6b0bfa4487a
|
[
"Apache-2.0"
] | 4
|
2020-03-03T08:09:20.000Z
|
2020-07-20T22:06:28.000Z
|
"""
Copyright (c) 2015 Michael Bright and Bamboo HR LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain 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 language governing permissions and
limitations under the License.
"""
try:
import simplejson as json
except ImportError:
import json
import os
from os.path import basename
import time
import pickle
import logging
import threading
from flask.globals import request
from flask.wrappers import Response
from rapid.client.communicator.client_communicator import ClientCommunicator
from rapid.lib import api_key_required
from rapid.lib.store_service import StoreService
from rapid.lib.utils import UpgradeUtil
from rapid.lib.work_request import WorkRequest
from rapid.client.executor import Executor
from ...lib.base_controller import BaseController
from ...lib.version import Version
logger = logging.getLogger("rapid")
# pylint: disable=broad-except
class WorkController(BaseController):
executors = []
def __init__(self):
self.app = None
def register_url_rules(self, flask_app):
"""
This is the entry point for the controller. All URL ruls are add_url_rule(d) here.
:param flask_app: The app you want to add a url to
:return: void
"""
flask_app.add_url_rule('/work/request', 'work_request', api_key_required(self.work_request))
flask_app.add_url_rule('/work/execute', 'work_execute', api_key_required(self.work_execute), methods=['POST'])
flask_app.add_url_rule('/work/cancel/<path:action_instance_id>', 'work_cancel', api_key_required(self.work_cancel), methods=['POST'])
self.app = flask_app
def work_request(self):
current_work = StoreService.get_executors()
current_work = current_work + self.__get_quarantined_items()
work = {'current_work': current_work,
'hostname': self.app.rapid_config.hostname}
if self.can_work_on() and self.check_version(request):
return Response(json.dumps(work), content_type='application/json', headers={Version.HEADER: Version.get_version()})
return Response(json.dumps(work), status=423, content_type='application/json', headers={Version.HEADER: Version.get_version()})
def __get_quarantined_items(self):
items = []
quarantine_directory = self.app.rapid_config.quarantine_directory
if quarantine_directory:
communicator = None
if not os.path.isdir(quarantine_directory):
os.makedirs(quarantine_directory)
for item in os.listdir(quarantine_directory):
if item in ['.', '..']:
continue
try:
items.append({'action_instance_id': int(item), 'pid': 'quarantined'})
if communicator is None:
communicator = ClientCommunicator(self.app.rapid_config.master_uri,
self.app.rapid_config.quarantine_directory,
verify_certs=self.app.rapid_config.verify_certs,
get_files_auth=self.app.rapid_config.get_files_basic_auth)
try:
delete_file = False
with open("{}/{}".format(quarantine_directory, item), 'r') as tmp_file:
data = pickle.loads(tmp_file.read())
try:
status = data['status']
parameters = data['parameters'] if 'parameters' in data else None
stats = data['stats'] if 'stats' in data else None
results = data['results'] if 'results' in data else None
communicator.send_done(int(item), status, parameters, stats, results, logger, headers={'X-Rapid-Quarantine': 'true'})
delete_file = True
except Exception:
import traceback
traceback.print_exc()
if delete_file:
try:
os.remove("{}/{}".format(quarantine_directory, item))
except Exception:
logger.error("Couldn't remove.")
except Exception:
import traceback
traceback.print_exc()
except Exception:
pass
return items
def can_work_on(self, work=None):
"""
This checks the work queue and what is being run at the moment.
:param work
:type work dict
:return: True|False
"""
executors = StoreService.get_executors()
return len(executors) < self.app.rapid_config.executor_count and not self.currently_running(work)
def currently_running(self, work):
pid_exists = False
try:
if work['action_instance_id'] is not None:
pid_exists = StoreService.check_for_pidfile(work['action_instance_id'])
if pid_exists is not None:
logger.info("Request was sent, but was already running, ignoring for [{}]".format(work['action_instance_id']))
except Exception:
pass
return pid_exists
def check_version(self, check_request):
if Version.HEADER in check_request.headers:
if check_request.headers[Version.HEADER] == self.get_version():
return True
if not StoreService.is_updating(self.app):
StoreService.set_updating(self.app)
thread = threading.Thread(target=self._perform_upgrade, args=(check_request.headers[Version.HEADER],))
thread.daemon = True
thread.start()
return False
return False
def _perform_upgrade(self, new_version):
logger.info("Performing upgrade: {}".format(new_version))
executors = self._sleep_for_executors()
self._start_upgrade(new_version, executors)
def _start_upgrade(self, new_version, executors):
if not executors:
UpgradeUtil.upgrade_version(new_version, self.app.rapid_config)
else:
logger.info("Waiting for executors...")
StoreService.set_updating(self.app, False)
@staticmethod
def _sleep_for_executors(seconds_to_sleep=10, count_limit=10):
executors = StoreService.get_executors()
count = 0
while executors:
time.sleep(seconds_to_sleep)
count += 1
if count >= count_limit:
break
executors = StoreService.get_executors()
return executors
def get_version(self):
return Version.get_version()
def work_execute(self):
try:
if self.can_work_on(request.get_json()):
self.start_work()
executors = StoreService.get_executors()
headers = {}
if len(executors) + 1 >= self.app.rapid_config.executor_count:
headers["X-Exclude-Resource"] = 'true'
return Response(json.dumps({"message": "Work started"}), status=201, content_type="application/json", headers=headers)
except Exception as exception:
logger.error(exception)
return Response(json.dumps({'message': str(exception)}), status=422, content_type='application/json')
return Response(json.dumps({"message": "Cannot execute work at this time."}), status=423, content_type='application/json')
def start_work(self):
executor = Executor(WorkRequest(request.get_json()),
self.app.rapid_config.master_uri,
workspace=self.app.rapid_config.workspace,
quarantine=self.app.rapid_config.quarantine_directory,
verify_certs=self.app.rapid_config.verify_certs,
rapid_config=self.app.rapid_config)
executor.verify_work_request()
executor.start()
def work_cancel(self, action_instance_id):
pid_file = StoreService.check_for_pidfile(action_instance_id)
if pid_file is not None:
try:
base_name = basename(pid_file)
os.kill(int(base_name.split('-')[-1]), 9)
return Response(json.dumps({"message": "Killed process."}), 200)
except Exception:
pass
return Response(json.dumps({"message": "Failed to kill process"}), 501)
| 41.753425
| 149
| 0.602472
|
4a0a94c35674c2f7faf717b3150754ef0cc8b29f
| 21,058
|
py
|
Python
|
setup.py
|
andreagrant/bokehDev
|
a684afee183496c54d4f187a890707cf6b5ec2a5
|
[
"BSD-3-Clause"
] | null | null | null |
setup.py
|
andreagrant/bokehDev
|
a684afee183496c54d4f187a890707cf6b5ec2a5
|
[
"BSD-3-Clause"
] | null | null | null |
setup.py
|
andreagrant/bokehDev
|
a684afee183496c54d4f187a890707cf6b5ec2a5
|
[
"BSD-3-Clause"
] | null | null | null |
"""Setup script for Bokeh."""
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENCE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import print_function
# Stdlib imports
import os, platform, re, shutil, site, subprocess, sys, time
from os.path import abspath, dirname, exists, isdir, join, realpath, relpath
from shutil import copy
import sys
if 'install' in sys.argv and sys.platform.startswith('win'):
# Try use setuptools, so that entry_points is handled, creating a bokeh.exe
try:
import setuptools
except ImportError:
pass
try:
import colorama
def bright(text): return "%s%s%s" % (colorama.Style.BRIGHT, text, colorama.Style.RESET_ALL)
def dim(text): return "%s%s%s" % (colorama.Style.DIM, text, colorama.Style.RESET_ALL)
def white(text): return "%s%s%s" % (colorama.Fore.WHITE, text, colorama.Style.RESET_ALL)
def blue(text): return "%s%s%s" % (colorama.Fore.BLUE, text, colorama.Style.RESET_ALL)
def red(text): return "%s%s%s" % (colorama.Fore.RED, text, colorama.Style.RESET_ALL)
def green(text): return "%s%s%s" % (colorama.Fore.GREEN, text, colorama.Style.RESET_ALL)
def yellow(text): return "%s%s%s" % (colorama.Fore.YELLOW, text, colorama.Style.RESET_ALL)
sys.platform == "win32" and colorama.init()
except ImportError:
def bright(text): return text
def dim(text): return text
def white(text) : return text
def blue(text) : return text
def red(text) : return text
def green(text) : return text
def yellow(text) : return text
if 'nightly' in sys.argv:
from setuptools import setup
sys.argv.remove('nightly')
with open('__conda_version__.txt', 'r') as f:
version = f.read().rstrip()
vers_file = os.path.join('bokeh', '__conda_version__.py')
with open(vers_file, 'w') as f:
f.write("conda_version=" + "'" + version + "'")
else:
from distutils.core import setup
from distutils import dir_util
# Our own imports
import versioneer
# -----------------------------------------------------------------------------
# Globals and constants
# -----------------------------------------------------------------------------
ROOT = dirname(realpath(__file__))
BOKEHJSROOT = join(ROOT, 'bokehjs')
BOKEHJSBUILD = join(BOKEHJSROOT, 'build')
CSS = join(BOKEHJSBUILD, 'css')
JS = join(BOKEHJSBUILD, 'js')
SERVER = join(ROOT, 'bokeh/server')
if sys.version_info[0] < 3:
input = raw_input
# -----------------------------------------------------------------------------
# Local utilities
# -----------------------------------------------------------------------------
versioneer.versionfile_source = 'bokeh/_version.py'
versioneer.versionfile_build = 'bokeh/_version.py'
versioneer.tag_prefix = '' # tags are like 1.2.0
versioneer.parentdir_prefix = 'Bokeh-' # dirname like 'myproject-1.2.0'
# -----------------------------------------------------------------------------
# Classes and functions
# -----------------------------------------------------------------------------
copy("LICENSE.txt", "bokeh/")
package_data = ['LICENSE.txt', 'themes/*.yaml']
def package_path(path, filters=()):
if not os.path.exists(path):
raise RuntimeError("packaging non-existent path: %s" % path)
elif os.path.isfile(path):
package_data.append(relpath(path, 'bokeh'))
else:
for path, dirs, files in os.walk(path):
path = relpath(path, 'bokeh')
for f in files:
if not filters or f.endswith(filters):
package_data.append(join(path, f))
# You can't install Bokeh in a virtualenv because the lack of getsitepackages()
# This is an open bug: https://github.com/pypa/virtualenv/issues/355
# And this is an intended PR to fix it: https://github.com/pypa/virtualenv/pull/508
# Workaround to fix our issue: https://github.com/bokeh/bokeh/issues/378
def getsitepackages():
"""Returns a list containing all global site-packages directories
(and possibly site-python)."""
_is_64bit = (getattr(sys, 'maxsize', None) or getattr(sys, 'maxint')) > 2**32
_is_pypy = hasattr(sys, 'pypy_version_info')
_is_jython = sys.platform[:4] == 'java'
prefixes = [sys.prefix, sys.exec_prefix]
sitepackages = []
seen = set()
for prefix in prefixes:
if not prefix or prefix in seen:
continue
seen.add(prefix)
if sys.platform in ('os2emx', 'riscos') or _is_jython:
sitedirs = [os.path.join(prefix, "Lib", "site-packages")]
elif _is_pypy:
sitedirs = [os.path.join(prefix, 'site-packages')]
elif sys.platform == 'darwin' and prefix == sys.prefix:
if prefix.startswith("/System/Library/Frameworks/"): # Apple's Python
sitedirs = [os.path.join("/Library/Python", sys.version[:3], "site-packages"),
os.path.join(prefix, "Extras", "lib", "python")]
else: # any other Python distros on OSX work this way
sitedirs = [os.path.join(prefix, "lib",
"python" + sys.version[:3], "site-packages")]
elif os.sep == '/':
sitedirs = [os.path.join(prefix,
"lib",
"python" + sys.version[:3],
"site-packages"),
os.path.join(prefix, "lib", "site-python"),
]
lib64_dir = os.path.join(prefix, "lib64", "python" + sys.version[:3], "site-packages")
if (os.path.exists(lib64_dir) and
os.path.realpath(lib64_dir) not in [os.path.realpath(p) for p in sitedirs]):
if _is_64bit:
sitedirs.insert(0, lib64_dir)
else:
sitedirs.append(lib64_dir)
try:
# sys.getobjects only available in --with-pydebug build
sys.getobjects
sitedirs.insert(0, os.path.join(sitedirs[0], 'debug'))
except AttributeError:
pass
# Debian-specific dist-packages directories:
sitedirs.append(os.path.join(prefix, "local/lib",
"python" + sys.version[:3],
"dist-packages"))
sitedirs.append(os.path.join(prefix, "lib",
"python" + sys.version[:3],
"dist-packages"))
if sys.version_info[0] >= 3:
sitedirs.append(os.path.join(prefix, "lib",
"python" + sys.version[0],
"dist-packages"))
sitedirs.append(os.path.join(prefix, "lib", "dist-python"))
else:
sitedirs = [os.path.join(prefix, "lib", "site-packages"), prefix]
if sys.platform == 'darwin':
# for framework builds *only* we add the standard Apple
# locations. Currently only per-user, but /Library and
# /Network/Library could be added too
if 'Python.framework' in prefix:
home = os.environ.get('HOME')
if home:
sitedirs.append(
os.path.join(home,
'Library',
'Python',
sys.version[:3],
'site-packages'))
for sitedir in sitedirs:
sitepackages.append(os.path.abspath(sitedir))
sitepackages = [p for p in sitepackages if os.path.isdir(p)]
return sitepackages
def check_remove_bokeh_install(site_packages):
old_bokeh_files = []
for d in os.listdir(site_packages):
bokeh_path = join(site_packages, d)
if not (d == 'bokeh' or d.startswith('bokeh-')):
continue
old_bokeh_files.append(bokeh_path)
if len(old_bokeh_files) == 0:
return
print("Found old Bokeh files:")
for path in old_bokeh_files:
print(" - %s" % path)
val = input("Remove %s? [y|N] " % ("it" if len(old_bokeh_files)==1 else "them",))
if val == "y":
print("Removing old Bokeh files...", end=" ")
for path in old_bokeh_files:
try:
if isdir(path): shutil.rmtree(path)
else: os.remove(path)
except (IOError, OSError) as e:
print(bright(red("\nUnable to remove old Bokeh file at %s, exiting" % path)) + " [reason: %s]" % e)
sys.exit(-1)
print("Done")
else:
print(bright(red("Old Bokeh files not removed, exiting.")))
sys.exit(1)
def remove_bokeh_pth(path_file):
if exists(path_file):
try:
os.remove(path_file)
except (IOError, OSError):
print(bright(red("Unable to remove old path file at %s, exiting" % path_file)))
sys.exit(-1)
return True
return False
BUILD_EXEC_FAIL_MSG = bright(red("Failed.")) + """
ERROR: subprocess.Popen(%r) failed to execute:
%s
Have you run `npm install` from the bokehjs subdirectory?
For more information, see the Dev Guide:
http://bokeh.pydata.org/en/latest/docs/dev_guide.html
"""
BUILD_FAIL_MSG = bright(red("Failed.")) + """
ERROR: 'gulp build' returned the following
---- on stdout:
%s
---- on stderr:
%s
"""
BUILD_SIZE_FAIL_MSG = """
ERROR: could not determine sizes:
%s
"""
BUILD_SUCCESS_MSG = bright(green("Success!")) + """
Build output:
%s"""
def build_js():
print("Building BokehJS... ", end="")
sys.stdout.flush()
os.chdir('bokehjs')
if sys.platform != "win32":
cmd = [join('node_modules', '.bin', 'gulp'), 'build']
else:
cmd = [join('node_modules', '.bin', 'gulp.cmd'), 'build']
t0 = time.time()
try:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except OSError as e:
print(BUILD_EXEC_FAIL_MSG % (cmd, e))
sys.exit(1)
finally:
os.chdir('..')
result = proc.wait()
t1 = time.time()
if result != 0:
indented_msg = ""
outmsg = proc.stdout.read().decode('ascii', errors='ignore')
outmsg = "\n".join([" " + x for x in outmsg.split("\n")])
errmsg = proc.stderr.read().decode('ascii', errors='ignore')
errmsg = "\n".join([" " + x for x in errmsg.split("\n")])
print(BUILD_FAIL_MSG % (red(outmsg), red(errmsg)))
sys.exit(1)
indented_msg = ""
msg = proc.stdout.read().decode('ascii', errors='ignore')
pat = re.compile(r"(\[.*\]) (.*)", re.DOTALL)
for line in msg.strip().split("\n"):
m = pat.match(line)
if not m: continue # skip generate.py output lines
stamp, txt = m.groups()
indented_msg += " " + dim(green(stamp)) + " " + dim(txt) + "\n"
msg = "\n".join([" " + x for x in msg.split("\n")])
print(BUILD_SUCCESS_MSG % indented_msg)
print("Build time: %s" % bright(yellow("%0.1f seconds" % (t1-t0))))
print()
print("Build artifact sizes:")
try:
def size(*path):
return os.stat(join("bokehjs", "build", *path)).st_size / 2**10
print(" - bokeh.js : %6.1f KB" % size("js", "bokeh.js"))
print(" - bokeh.css : %6.1f KB" % size("css", "bokeh.css"))
print(" - bokeh.min.js : %6.1f KB" % size("js", "bokeh.min.js"))
print(" - bokeh.min.css : %6.1f KB" % size("css", "bokeh.min.css"))
print(" - bokeh-widgets.js : %6.1f KB" % size("js", "bokeh-widgets.js"))
print(" - bokeh-widgets.css : %6.1f KB" % size("css", "bokeh-widgets.css"))
print(" - bokeh-widgets.min.js : %6.1f KB" % size("js", "bokeh-widgets.min.js"))
print(" - bokeh-widgets.min.css : %6.1f KB" % size("css", "bokeh-widgets.min.css"))
print(" - bokeh-compiler.js : %6.1f KB" % size("js", "bokeh-compiler.js"))
print(" - bokeh-compiler.min.js : %6.1f KB" % size("js", "bokeh-compiler.min.js"))
except Exception as e:
print(BUILD_SIZE_FAIL_MSG % e)
def install_js():
target_jsdir = join(SERVER, 'static', 'js')
target_cssdir = join(SERVER, 'static', 'css')
STATIC_ASSETS = [
join(JS, 'bokeh.js'),
join(JS, 'bokeh.min.js'),
join(CSS, 'bokeh.css'),
join(CSS, 'bokeh.min.css'),
]
if not all([exists(a) for a in STATIC_ASSETS]):
print("""
ERROR: Cannot install BokehJS: files missing in `./bokehjs/build`.
Please build BokehJS by running setup.py with the `--build_js` option.
Dev Guide: http://bokeh.pydata.org/docs/dev_guide.html#bokehjs.
""")
sys.exit(1)
if exists(target_jsdir):
shutil.rmtree(target_jsdir)
shutil.copytree(JS, target_jsdir)
if exists(target_cssdir):
shutil.rmtree(target_cssdir)
shutil.copytree(CSS, target_cssdir)
def clean():
print("Removing prior-built items...", end=" ")
build_dir = 'build/lib/bokeh'
if os.path.exists(build_dir):
dir_util.remove_tree(build_dir)
for root, dirs, files in os.walk('.'):
for item in files:
if item.endswith('.pyc'):
os.remove(os.path.join(root, item))
print("Done")
def get_user_jsargs():
print("""
Bokeh includes a JavaScript library (BokehJS) that has its own
build process. How would you like to handle BokehJS:
1) build and install fresh BokehJS
2) install last built BokehJS from bokeh/bokehjs/build
""")
mapping = {"1": True, "2": False}
value = input("Choice? ")
while value not in mapping:
print("Input '%s' not understood. Valid choices: 1, 2\n" % value)
value = input("Choice? ")
return mapping[value]
def parse_jsargs():
options = ('install', 'develop', 'sdist', 'egg_info', 'build')
installing = any(arg in sys.argv for arg in options)
if '--build_js' in sys.argv:
if not installing:
print("Error: Option '--build_js' only valid with 'install', 'develop', 'sdist', or 'build', exiting.")
sys.exit(1)
jsbuild = True
sys.argv.remove('--build_js')
elif '--install_js' in sys.argv:
# Note that --install_js can be used by itself (without sdist/install/develop)
jsbuild = False
sys.argv.remove('--install_js')
else:
if installing:
jsbuild = get_user_jsargs()
else:
jsbuild = False
return jsbuild
def package_tree(pkgroot):
""" Get list of packages by walking the directory structure and
including all dirs that have an __init__.py or are named test.
"""
subdirs = [os.path.relpath(i[0], ROOT).replace(os.path.sep, '.')
for i in os.walk(os.path.join(ROOT, pkgroot))
if '__init__.py' in i[2]]
return subdirs
# -----------------------------------------------------------------------------
# Main script
# -----------------------------------------------------------------------------
# Aliases for build_js and install_js
for i in range(len(sys.argv)):
if sys.argv[i] == '--build-js':
sys.argv[i] = '--build_js'
if sys.argv[i] == '--install-js':
sys.argv[i] = '--install_js'
# Set up this checkout or source archive with the right BokehJS files.
if sys.version_info[:2] < (2, 6):
raise RuntimeError("Bokeh requires python >= 2.6")
# Lightweight command to only install js and nothing more - developer mode
if len(sys.argv) == 2 and sys.argv[-1] == '--install_js':
install_js()
sys.exit(0)
# check for 'sdist' and make sure we always do a BokehJS build when packaging
if "sdist" in sys.argv:
if "--install_js" in sys.argv:
print("Removing '--install_js' incompatible with 'sdist'")
sys.argv.remove('--install_js')
if "--build_js" not in sys.argv:
print("Adding '--build_js' required for 'sdist'")
sys.argv.append('--build_js')
# check for package install, set jsinstall to False to skip prompt
jsinstall = True
if not exists(join(ROOT, 'MANIFEST.in')):
if "--build_js" in sys.argv or "--install_js" in sys.argv:
print("BokehJS source code is not shipped in sdist packages; "
"building/installing from the bokehjs source directory is disabled. "
"To build or develop BokehJS yourself, you must clone the full "
"Bokeh repository from https://github.com/bokeh/bokeh")
if "--build_js" in sys.argv:
sys.argv.remove('--build_js')
if "--install_js" in sys.argv:
sys.argv.remove('--install_js')
jsbuild = False
jsinstall = False
else:
jsbuild = parse_jsargs()
if jsbuild:
build_js()
if jsinstall:
install_js()
sampledata_suffixes = ('.csv', '.conf', '.gz', '.json', '.png', '.ics', '.geojson')
package_path(join(SERVER, 'static'))
package_path(join(ROOT, 'bokeh', 'core', '_templates'))
package_path(join(ROOT, 'bokeh', 'sampledata'), sampledata_suffixes)
if '--user' in sys.argv:
site_packages = site.USER_SITE
else:
site_packages = getsitepackages()[0]
path_file = join(site_packages, "bokeh.pth")
path = abspath(dirname(__file__))
print()
if 'develop' in sys.argv:
# Note that setuptools supports 'develop' too, but we roll our own implementation
# that removes any existing Bokeh installation, and works in virtualenv
if exists('bokeh/__conda_version__.py'):
print(bright(red("ERROR:")) + " Detected a __conda_version__.py file, exiting")
sys.exit(1)
check_remove_bokeh_install(site_packages)
with open(path_file, "w+") as f:
f.write(path)
print("Installing Bokeh for development:")
print(" - writing path '%s' to %s" % (path, path_file))
if jsinstall:
print(" - using %s built BokehJS from bokehjs/build\n" % (bright(yellow("NEWLY")) if jsbuild else bright(yellow("PREVIOUSLY"))))
else:
print(" - using %s BokehJS, located in 'bokeh.server.static'\n" % yellow("PACKAGED"))
sys.exit()
elif 'clean' in sys.argv:
clean()
elif 'install' in sys.argv:
pth_removed = remove_bokeh_pth(path_file)
print("Installing Bokeh:")
if pth_removed:
print(" - removed path file at %s" % path_file)
if jsinstall:
print(" - using %s built BokehJS from bokehjs/build\n" % (bright(yellow("NEWLY")) if jsbuild else bright(yellow("PREVIOUSLY"))))
else:
print(" - using %s BokehJS, located in 'bokeh.server.static'\n" % bright(yellow("PACKAGED")))
elif '--help' in sys.argv:
if jsinstall:
print("Bokeh-specific options available with 'install' or 'develop':")
print()
print(" --build_js build and install a fresh BokehJS")
print(" --install_js install only last previously built BokehJS")
else:
print("Bokeh is using PACKAGED BokehJS, located in 'bokeh.server.static'")
print()
print()
REQUIRES = [
'six>=1.5.2',
'requests>=1.2.3',
'PyYAML>=3.10',
'python-dateutil>=2.1',
'Jinja2>=2.7',
'numpy>=1.7.1',
'tornado>=4.3',
]
if sys.version_info[:2] == (2, 7):
REQUIRES.append('futures>=3.0.3')
_version = versioneer.get_version()
_cmdclass = versioneer.get_cmdclass()
# Horrible hack: workaround to allow creation of bdist_wheel on pip installation
# Why, for God's sake, is pip forcing the generation of wheels when installing a package?
try:
from wheel.bdist_wheel import bdist_wheel
except ImportError as e:
# pip is not claiming for bdist_wheel when wheel is not installed
bdist_wheel = None
if bdist_wheel is not None:
_cmdclass["bdist_wheel"] = bdist_wheel
# Note on scripts and entry points. The 'scripts' value is handled by
# distutils but does not provide an .exe, making it not very useful on
# Windows. The 'entry_points' value is handled only if setuptools is
# used, and does make an .exe. Note that in our conda recipe, we
# seperately define an entry point.
setup(
name='bokeh',
version=_version,
cmdclass=_cmdclass,
packages=package_tree('bokeh'),
package_data={'bokeh': package_data},
author='Continuum Analytics',
author_email='info@continuum.io',
url='http://github.com/bokeh/bokeh',
description='Statistical and novel interactive HTML plots for Python',
license='New BSD',
scripts=['bin/bokeh', 'bin/bokeh-server'],
entry_points={'console_scripts': ['bokeh = bokeh.__main__:main',], },
zip_safe=False,
install_requires=REQUIRES
)
| 35.214047
| 137
| 0.572514
|
4a0a96349c14c509cc8a2a21f3d3a94a12eae6c8
| 8,311
|
py
|
Python
|
docs/conf.py
|
rishikesh67/django-shared-schema-tenants
|
ed3bcddf80a7838979fe1be2045dfa16b545beed
|
[
"MIT"
] | 20
|
2017-08-29T02:36:32.000Z
|
2021-12-06T21:29:46.000Z
|
docs/conf.py
|
rishikesh67/django-shared-schema-tenants
|
ed3bcddf80a7838979fe1be2045dfa16b545beed
|
[
"MIT"
] | 35
|
2017-08-18T06:28:31.000Z
|
2021-09-02T01:53:09.000Z
|
docs/conf.py
|
rishikesh67/django-shared-schema-tenants
|
ed3bcddf80a7838979fe1be2045dfa16b545beed
|
[
"MIT"
] | 9
|
2018-06-17T22:04:13.000Z
|
2022-03-18T09:27:18.000Z
|
# -*- coding: utf-8 -*-
#
# complexity documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
cwd = os.getcwd()
parent = os.path.dirname(cwd)
sys.path.append(parent)
import shared_schema_tenants
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Django Shared Schema Tenants'
copyright = u'2017, Hugo Bessa'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = shared_schema_tenants.__version__
# The full version, including alpha/beta/rc tags.
release = shared_schema_tenants.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'django-shared-schema-tenantsdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'django-shared-schema-tenants.tex', u'Django Shared Schema Tenants Documentation',
u'Hugo Bessa', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'django-shared-schema-tenants', u'Django Shared Schema Tenants Documentation',
[u'Hugo Bessa'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'django-shared-schema-tenants', u'Django Shared Schema Tenants Documentation',
u'Hugo Bessa', 'django-shared-schema-tenants', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| 32.592157
| 94
| 0.721093
|
4a0a96427e916d8a9ad4bbf72cfb3485dc2ed0aa
| 41,889
|
py
|
Python
|
yt_dlp/postprocessor/ffmpeg.py
|
t03b10t99/ytdl-good-boys
|
d183af3cc1dbb98d2e2f89dbc7cff2901bd10408
|
[
"Unlicense"
] | 18
|
2020-12-21T22:33:46.000Z
|
2021-01-11T20:14:35.000Z
|
yt_dlp/postprocessor/ffmpeg.py
|
t03b10t99/ytdl-good-boys
|
d183af3cc1dbb98d2e2f89dbc7cff2901bd10408
|
[
"Unlicense"
] | 8
|
2021-01-06T21:01:20.000Z
|
2021-01-12T21:34:46.000Z
|
yt_dlp/postprocessor/ffmpeg.py
|
t03b10t99/ytdl-good-boys
|
d183af3cc1dbb98d2e2f89dbc7cff2901bd10408
|
[
"Unlicense"
] | 2
|
2021-01-08T17:38:57.000Z
|
2021-01-12T11:08:27.000Z
|
from __future__ import unicode_literals
import io
import itertools
import os
import subprocess
import time
import re
import json
from .common import AudioConversionError, PostProcessor
from ..compat import compat_str
from ..utils import (
dfxp2srt,
encodeArgument,
encodeFilename,
float_or_none,
get_exe_version,
is_outdated_version,
ISO639Utils,
orderedSet,
Popen,
PostProcessingError,
prepend_extension,
replace_extension,
shell_quote,
traverse_obj,
variadic,
)
EXT_TO_OUT_FORMATS = {
'aac': 'adts',
'flac': 'flac',
'm4a': 'ipod',
'mka': 'matroska',
'mkv': 'matroska',
'mpg': 'mpeg',
'ogv': 'ogg',
'ts': 'mpegts',
'wma': 'asf',
'wmv': 'asf',
}
ACODECS = {
'mp3': 'libmp3lame',
'aac': 'aac',
'flac': 'flac',
'm4a': 'aac',
'opus': 'libopus',
'vorbis': 'libvorbis',
'wav': None,
}
class FFmpegPostProcessorError(PostProcessingError):
pass
class FFmpegPostProcessor(PostProcessor):
def __init__(self, downloader=None):
PostProcessor.__init__(self, downloader)
self._determine_executables()
def check_version(self):
if not self.available:
raise FFmpegPostProcessorError('ffmpeg not found. Please install or provide the path using --ffmpeg-location')
required_version = '10-0' if self.basename == 'avconv' else '1.0'
if is_outdated_version(
self._versions[self.basename], required_version):
warning = 'Your copy of %s is outdated, update %s to version %s or newer if you encounter any errors.' % (
self.basename, self.basename, required_version)
self.report_warning(warning)
@staticmethod
def get_versions(downloader=None):
return FFmpegPostProcessor(downloader)._versions
def _determine_executables(self):
programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
prefer_ffmpeg = True
def get_ffmpeg_version(path):
ver = get_exe_version(path, args=['-version'])
if ver:
regexs = [
r'(?:\d+:)?([0-9.]+)-[0-9]+ubuntu[0-9.]+$', # Ubuntu, see [1]
r'n([0-9.]+)$', # Arch Linux
# 1. http://www.ducea.com/2006/06/17/ubuntu-package-version-naming-explanation/
]
for regex in regexs:
mobj = re.match(regex, ver)
if mobj:
ver = mobj.group(1)
return ver
self.basename = None
self.probe_basename = None
self._paths = None
self._versions = None
if self._downloader:
prefer_ffmpeg = self.get_param('prefer_ffmpeg', True)
location = self.get_param('ffmpeg_location')
if location is not None:
if not os.path.exists(location):
self.report_warning(
'ffmpeg-location %s does not exist! '
'Continuing without ffmpeg.' % (location))
self._versions = {}
return
elif os.path.isdir(location):
dirname, basename = location, None
else:
basename = os.path.splitext(os.path.basename(location))[0]
basename = next((p for p in programs if basename.startswith(p)), 'ffmpeg')
dirname = os.path.dirname(os.path.abspath(location))
if basename in ('ffmpeg', 'ffprobe'):
prefer_ffmpeg = True
self._paths = dict(
(p, os.path.join(dirname, p)) for p in programs)
if basename:
self._paths[basename] = location
self._versions = dict(
(p, get_ffmpeg_version(self._paths[p])) for p in programs)
if self._versions is None:
self._versions = dict(
(p, get_ffmpeg_version(p)) for p in programs)
self._paths = dict((p, p) for p in programs)
if prefer_ffmpeg is False:
prefs = ('avconv', 'ffmpeg')
else:
prefs = ('ffmpeg', 'avconv')
for p in prefs:
if self._versions[p]:
self.basename = p
break
if prefer_ffmpeg is False:
prefs = ('avprobe', 'ffprobe')
else:
prefs = ('ffprobe', 'avprobe')
for p in prefs:
if self._versions[p]:
self.probe_basename = p
break
@property
def available(self):
return self.basename is not None
@property
def executable(self):
return self._paths[self.basename]
@property
def probe_available(self):
return self.probe_basename is not None
@property
def probe_executable(self):
return self._paths[self.probe_basename]
def get_audio_codec(self, path):
if not self.probe_available and not self.available:
raise PostProcessingError('ffprobe and ffmpeg not found. Please install or provide the path using --ffmpeg-location')
try:
if self.probe_available:
cmd = [
encodeFilename(self.probe_executable, True),
encodeArgument('-show_streams')]
else:
cmd = [
encodeFilename(self.executable, True),
encodeArgument('-i')]
cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
self.write_debug('%s command line: %s' % (self.basename, shell_quote(cmd)))
handle = Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout_data, stderr_data = handle.communicate_or_kill()
expected_ret = 0 if self.probe_available else 1
if handle.wait() != expected_ret:
return None
except (IOError, OSError):
return None
output = (stdout_data if self.probe_available else stderr_data).decode('ascii', 'ignore')
if self.probe_available:
audio_codec = None
for line in output.split('\n'):
if line.startswith('codec_name='):
audio_codec = line.split('=')[1].strip()
elif line.strip() == 'codec_type=audio' and audio_codec is not None:
return audio_codec
else:
# Stream #FILE_INDEX:STREAM_INDEX[STREAM_ID](LANGUAGE): CODEC_TYPE: CODEC_NAME
mobj = re.search(
r'Stream\s*#\d+:\d+(?:\[0x[0-9a-f]+\])?(?:\([a-z]{3}\))?:\s*Audio:\s*([0-9a-z]+)',
output)
if mobj:
return mobj.group(1)
return None
def get_metadata_object(self, path, opts=[]):
if self.probe_basename != 'ffprobe':
if self.probe_available:
self.report_warning('Only ffprobe is supported for metadata extraction')
raise PostProcessingError('ffprobe not found. Please install or provide the path using --ffmpeg-location')
self.check_version()
cmd = [
encodeFilename(self.probe_executable, True),
encodeArgument('-hide_banner'),
encodeArgument('-show_format'),
encodeArgument('-show_streams'),
encodeArgument('-print_format'),
encodeArgument('json'),
]
cmd += opts
cmd.append(encodeFilename(self._ffmpeg_filename_argument(path), True))
self.write_debug('ffprobe command line: %s' % shell_quote(cmd))
p = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout, stderr = p.communicate()
return json.loads(stdout.decode('utf-8', 'replace'))
def get_stream_number(self, path, keys, value):
streams = self.get_metadata_object(path)['streams']
num = next(
(i for i, stream in enumerate(streams) if traverse_obj(stream, keys, casesense=False) == value),
None)
return num, len(streams)
def _get_real_video_duration(self, info, fatal=True):
try:
if '_real_duration' not in info:
info['_real_duration'] = float_or_none(
traverse_obj(self.get_metadata_object(info['filepath']), ('format', 'duration')))
if not info['_real_duration']:
raise PostProcessingError('ffprobe returned empty duration')
except PostProcessingError as e:
if fatal:
raise PostProcessingError(f'Unable to determine video duration; {e}')
return info.setdefault('_real_duration', None)
def _duration_mismatch(self, d1, d2):
if not d1 or not d2:
return None
return abs(d1 - d2) > 1
def run_ffmpeg_multiple_files(self, input_paths, out_path, opts, **kwargs):
return self.real_run_ffmpeg(
[(path, []) for path in input_paths],
[(out_path, opts)], **kwargs)
def real_run_ffmpeg(self, input_path_opts, output_path_opts, *, expected_retcodes=(0,)):
self.check_version()
oldest_mtime = min(
os.stat(encodeFilename(path)).st_mtime for path, _ in input_path_opts if path)
cmd = [encodeFilename(self.executable, True), encodeArgument('-y')]
# avconv does not have repeat option
if self.basename == 'ffmpeg':
cmd += [encodeArgument('-loglevel'), encodeArgument('repeat+info')]
def make_args(file, args, name, number):
keys = ['_%s%d' % (name, number), '_%s' % name]
if name == 'o' and number == 1:
keys.append('')
args += self._configuration_args(self.basename, keys)
if name == 'i':
args.append('-i')
return (
[encodeArgument(arg) for arg in args]
+ [encodeFilename(self._ffmpeg_filename_argument(file), True)])
for arg_type, path_opts in (('i', input_path_opts), ('o', output_path_opts)):
cmd += itertools.chain.from_iterable(
make_args(path, list(opts), arg_type, i + 1)
for i, (path, opts) in enumerate(path_opts) if path)
self.write_debug('ffmpeg command line: %s' % shell_quote(cmd))
p = Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout, stderr = p.communicate_or_kill()
if p.returncode not in variadic(expected_retcodes):
stderr = stderr.decode('utf-8', 'replace').strip()
self.write_debug(stderr)
raise FFmpegPostProcessorError(stderr.split('\n')[-1])
for out_path, _ in output_path_opts:
if out_path:
self.try_utime(out_path, oldest_mtime, oldest_mtime)
return stderr.decode('utf-8', 'replace')
def run_ffmpeg(self, path, out_path, opts, **kwargs):
return self.run_ffmpeg_multiple_files([path], out_path, opts, **kwargs)
@staticmethod
def _ffmpeg_filename_argument(fn):
# Always use 'file:' because the filename may contain ':' (ffmpeg
# interprets that as a protocol) or can start with '-' (-- is broken in
# ffmpeg, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details)
# Also leave '-' intact in order not to break streaming to stdout.
if fn.startswith(('http://', 'https://')):
return fn
return 'file:' + fn if fn != '-' else fn
@staticmethod
def _quote_for_ffmpeg(string):
# See https://ffmpeg.org/ffmpeg-utils.html#toc-Quoting-and-escaping
# A sequence of '' produces '\'''\'';
# final replace removes the empty '' between \' \'.
string = string.replace("'", r"'\''").replace("'''", "'")
# Handle potential ' at string boundaries.
string = string[1:] if string[0] == "'" else "'" + string
return string[:-1] if string[-1] == "'" else string + "'"
def force_keyframes(self, filename, timestamps):
timestamps = orderedSet(timestamps)
if timestamps[0] == 0:
timestamps = timestamps[1:]
keyframe_file = prepend_extension(filename, 'keyframes.temp')
self.to_screen(f'Re-encoding "{filename}" with appropriate keyframes')
self.run_ffmpeg(filename, keyframe_file, ['-force_key_frames', ','.join(
f'{t:.6f}' for t in timestamps)])
return keyframe_file
def concat_files(self, in_files, out_file, concat_opts=None):
"""
Use concat demuxer to concatenate multiple files having identical streams.
Only inpoint, outpoint, and duration concat options are supported.
See https://ffmpeg.org/ffmpeg-formats.html#concat-1 for details
"""
concat_file = f'{out_file}.concat'
self.write_debug(f'Writing concat spec to {concat_file}')
with open(concat_file, 'wt', encoding='utf-8') as f:
f.writelines(self._concat_spec(in_files, concat_opts))
out_flags = ['-c', 'copy']
if out_file.rpartition('.')[-1] in ('mp4', 'mov'):
# For some reason, '-c copy' is not enough to copy subtitles
out_flags.extend(['-c:s', 'mov_text', '-movflags', '+faststart'])
try:
self.real_run_ffmpeg(
[(concat_file, ['-hide_banner', '-nostdin', '-f', 'concat', '-safe', '0'])],
[(out_file, out_flags)])
finally:
os.remove(concat_file)
@classmethod
def _concat_spec(cls, in_files, concat_opts=None):
if concat_opts is None:
concat_opts = [{}] * len(in_files)
yield 'ffconcat version 1.0\n'
for file, opts in zip(in_files, concat_opts):
yield f'file {cls._quote_for_ffmpeg(cls._ffmpeg_filename_argument(file))}\n'
# Iterate explicitly to yield the following directives in order, ignoring the rest.
for directive in 'inpoint', 'outpoint', 'duration':
if directive in opts:
yield f'{directive} {opts[directive]}\n'
class FFmpegExtractAudioPP(FFmpegPostProcessor):
COMMON_AUDIO_EXTS = ('wav', 'flac', 'm4a', 'aiff', 'mp3', 'ogg', 'mka', 'opus', 'wma')
SUPPORTED_EXTS = ('best', 'aac', 'flac', 'mp3', 'm4a', 'opus', 'vorbis', 'wav')
def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
FFmpegPostProcessor.__init__(self, downloader)
self._preferredcodec = preferredcodec or 'best'
self._preferredquality = preferredquality
self._nopostoverwrites = nopostoverwrites
def run_ffmpeg(self, path, out_path, codec, more_opts):
if codec is None:
acodec_opts = []
else:
acodec_opts = ['-acodec', codec]
opts = ['-vn'] + acodec_opts + more_opts
try:
FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
except FFmpegPostProcessorError as err:
raise AudioConversionError(err.msg)
@PostProcessor._restrict_to(images=False)
def run(self, information):
path = information['filepath']
orig_ext = information['ext']
if self._preferredcodec == 'best' and orig_ext in self.COMMON_AUDIO_EXTS:
self.to_screen('Skipping audio extraction since the file is already in a common audio format')
return [], information
filecodec = self.get_audio_codec(path)
if filecodec is None:
raise PostProcessingError('WARNING: unable to obtain file audio codec with ffprobe')
more_opts = []
if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
# Lossless, but in another container
acodec = 'copy'
extension = 'm4a'
more_opts = ['-bsf:a', 'aac_adtstoasc']
elif filecodec in ['aac', 'flac', 'mp3', 'vorbis', 'opus']:
# Lossless if possible
acodec = 'copy'
extension = filecodec
if filecodec == 'aac':
more_opts = ['-f', 'adts']
if filecodec == 'vorbis':
extension = 'ogg'
else:
# MP3 otherwise.
acodec = 'libmp3lame'
extension = 'mp3'
more_opts = []
if self._preferredquality is not None:
if int(self._preferredquality) < 10:
more_opts += ['-q:a', self._preferredquality]
else:
more_opts += ['-b:a', self._preferredquality + 'k']
else:
# We convert the audio (lossy if codec is lossy)
acodec = ACODECS[self._preferredcodec]
extension = self._preferredcodec
more_opts = []
if self._preferredquality is not None:
# The opus codec doesn't support the -aq option
if int(self._preferredquality) < 10 and extension != 'opus':
more_opts += ['-q:a', self._preferredquality]
else:
more_opts += ['-b:a', self._preferredquality + 'k']
if self._preferredcodec == 'aac':
more_opts += ['-f', 'adts']
if self._preferredcodec == 'm4a':
more_opts += ['-bsf:a', 'aac_adtstoasc']
if self._preferredcodec == 'vorbis':
extension = 'ogg'
if self._preferredcodec == 'wav':
extension = 'wav'
more_opts += ['-f', 'wav']
prefix, sep, ext = path.rpartition('.') # not os.path.splitext, since the latter does not work on unicode in all setups
new_path = prefix + sep + extension
information['filepath'] = new_path
information['ext'] = extension
# If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
if (new_path == path
or (self._nopostoverwrites and os.path.exists(encodeFilename(new_path)))):
self.to_screen('Post-process file %s exists, skipping' % new_path)
return [], information
try:
self.to_screen('Destination: ' + new_path)
self.run_ffmpeg(path, new_path, acodec, more_opts)
except AudioConversionError as e:
raise PostProcessingError(
'audio conversion failed: ' + e.msg)
except Exception:
raise PostProcessingError('error running ' + self.basename)
# Try to update the date time for extracted audio file.
if information.get('filetime') is not None:
self.try_utime(
new_path, time.time(), information['filetime'],
errnote='Cannot update utime of audio file')
return [path], information
class FFmpegVideoConvertorPP(FFmpegPostProcessor):
SUPPORTED_EXTS = ('mp4', 'mkv', 'flv', 'webm', 'mov', 'avi', 'mp3', 'mka', 'm4a', 'ogg', 'opus')
FORMAT_RE = re.compile(r'{0}(?:/{0})*$'.format(r'(?:\w+>)?(?:%s)' % '|'.join(SUPPORTED_EXTS)))
_ACTION = 'converting'
def __init__(self, downloader=None, preferedformat=None):
super(FFmpegVideoConvertorPP, self).__init__(downloader)
self._preferedformats = preferedformat.lower().split('/')
def _target_ext(self, source_ext):
for pair in self._preferedformats:
kv = pair.split('>')
if len(kv) == 1 or kv[0].strip() == source_ext:
return kv[-1].strip()
@staticmethod
def _options(target_ext):
if target_ext == 'avi':
return ['-c:v', 'libxvid', '-vtag', 'XVID']
return []
@PostProcessor._restrict_to(images=False)
def run(self, info):
filename, source_ext = info['filepath'], info['ext'].lower()
target_ext = self._target_ext(source_ext)
_skip_msg = (
f'could not find a mapping for {source_ext}' if not target_ext
else f'already is in target format {source_ext}' if source_ext == target_ext
else None)
if _skip_msg:
self.to_screen(f'Not {self._ACTION} media file {filename!r}; {_skip_msg}')
return [], info
outpath = replace_extension(filename, target_ext, source_ext)
self.to_screen(f'{self._ACTION.title()} video from {source_ext} to {target_ext}; Destination: {outpath}')
self.run_ffmpeg(filename, outpath, self._options(target_ext))
info['filepath'] = outpath
info['format'] = info['ext'] = target_ext
return [filename], info
class FFmpegVideoRemuxerPP(FFmpegVideoConvertorPP):
_ACTION = 'remuxing'
@staticmethod
def _options(target_ext):
options = ['-c', 'copy', '-map', '0', '-dn']
if target_ext in ['mp4', 'm4a', 'mov']:
options.extend(['-movflags', '+faststart'])
return options
class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
def __init__(self, downloader=None, already_have_subtitle=False):
super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
self._already_have_subtitle = already_have_subtitle
@PostProcessor._restrict_to(images=False)
def run(self, information):
if information['ext'] not in ('mp4', 'webm', 'mkv'):
self.to_screen('Subtitles can only be embedded in mp4, webm or mkv files')
return [], information
subtitles = information.get('requested_subtitles')
if not subtitles:
self.to_screen('There aren\'t any subtitles to embed')
return [], information
filename = information['filepath']
if information.get('duration') and self._duration_mismatch(
self._get_real_video_duration(information, False), information['duration']):
self.to_screen(f'Skipping {self.pp_key()} since the real and expected durations mismatch')
return [], information
ext = information['ext']
sub_langs, sub_names, sub_filenames = [], [], []
webm_vtt_warn = False
mp4_ass_warn = False
for lang, sub_info in subtitles.items():
if not os.path.exists(sub_info.get('filepath', '')):
self.report_warning(f'Skipping embedding {lang} subtitle because the file is missing')
continue
sub_ext = sub_info['ext']
if sub_ext == 'json':
self.report_warning('JSON subtitles cannot be embedded')
elif ext != 'webm' or ext == 'webm' and sub_ext == 'vtt':
sub_langs.append(lang)
sub_names.append(sub_info.get('name'))
sub_filenames.append(sub_info['filepath'])
else:
if not webm_vtt_warn and ext == 'webm' and sub_ext != 'vtt':
webm_vtt_warn = True
self.report_warning('Only WebVTT subtitles can be embedded in webm files')
if not mp4_ass_warn and ext == 'mp4' and sub_ext == 'ass':
mp4_ass_warn = True
self.report_warning('ASS subtitles cannot be properly embedded in mp4 files; expect issues')
if not sub_langs:
return [], information
input_files = [filename] + sub_filenames
opts = [
'-c', 'copy', '-map', '0', '-dn',
# Don't copy the existing subtitles, we may be running the
# postprocessor a second time
'-map', '-0:s',
# Don't copy Apple TV chapters track, bin_data (see #19042, #19024,
# https://trac.ffmpeg.org/ticket/6016)
'-map', '-0:d',
]
if information['ext'] == 'mp4':
opts += ['-c:s', 'mov_text']
for i, (lang, name) in enumerate(zip(sub_langs, sub_names)):
opts.extend(['-map', '%d:0' % (i + 1)])
lang_code = ISO639Utils.short2long(lang) or lang
opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
if name:
opts.extend(['-metadata:s:s:%d' % i, 'handler_name=%s' % name,
'-metadata:s:s:%d' % i, 'title=%s' % name])
temp_filename = prepend_extension(filename, 'temp')
self.to_screen('Embedding subtitles in "%s"' % filename)
self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
os.replace(temp_filename, filename)
files_to_delete = [] if self._already_have_subtitle else sub_filenames
return files_to_delete, information
class FFmpegMetadataPP(FFmpegPostProcessor):
def __init__(self, downloader, add_metadata=True, add_chapters=True):
FFmpegPostProcessor.__init__(self, downloader)
self._add_metadata = add_metadata
self._add_chapters = add_chapters
@staticmethod
def _options(target_ext):
yield from ('-map', '0', '-dn')
if target_ext == 'm4a':
yield from ('-vn', '-acodec', 'copy')
else:
yield from ('-c', 'copy')
@PostProcessor._restrict_to(images=False)
def run(self, info):
filename, metadata_filename = info['filepath'], None
options = []
if self._add_chapters and info.get('chapters'):
metadata_filename = replace_extension(filename, 'meta')
options.extend(self._get_chapter_opts(info['chapters'], metadata_filename))
if self._add_metadata:
options.extend(self._get_metadata_opts(info))
if not options:
self.to_screen('There isn\'t any metadata to add')
return [], info
temp_filename = prepend_extension(filename, 'temp')
self.to_screen('Adding metadata to "%s"' % filename)
self.run_ffmpeg_multiple_files(
(filename, metadata_filename), temp_filename,
itertools.chain(self._options(info['ext']), *options))
if metadata_filename:
os.remove(metadata_filename)
os.replace(temp_filename, filename)
return [], info
@staticmethod
def _get_chapter_opts(chapters, metadata_filename):
with io.open(metadata_filename, 'wt', encoding='utf-8') as f:
def ffmpeg_escape(text):
return re.sub(r'([\\=;#\n])', r'\\\1', text)
metadata_file_content = ';FFMETADATA1\n'
for chapter in chapters:
metadata_file_content += '[CHAPTER]\nTIMEBASE=1/1000\n'
metadata_file_content += 'START=%d\n' % (chapter['start_time'] * 1000)
metadata_file_content += 'END=%d\n' % (chapter['end_time'] * 1000)
chapter_title = chapter.get('title')
if chapter_title:
metadata_file_content += 'title=%s\n' % ffmpeg_escape(chapter_title)
f.write(metadata_file_content)
yield ('-map_metadata', '1')
def _get_metadata_opts(self, info):
metadata = {}
meta_prefix = 'meta_'
def add(meta_list, info_list=None):
value = next((
str(info[key]) for key in [meta_prefix] + list(variadic(info_list or meta_list))
if info.get(key) is not None), None)
if value not in ('', None):
metadata.update({meta_f: value for meta_f in variadic(meta_list)})
# See [1-4] for some info on media metadata/metadata supported
# by ffmpeg.
# 1. https://kdenlive.org/en/project/adding-meta-data-to-mp4-video/
# 2. https://wiki.multimedia.cx/index.php/FFmpeg_Metadata
# 3. https://kodi.wiki/view/Video_file_tagging
add('title', ('track', 'title'))
add('date', 'upload_date')
add(('description', 'synopsis'), 'description')
add(('purl', 'comment'), 'webpage_url')
add('track', 'track_number')
add('artist', ('artist', 'creator', 'uploader', 'uploader_id'))
add('genre')
add('album')
add('album_artist')
add('disc', 'disc_number')
add('show', 'series')
add('season_number')
add('episode_id', ('episode', 'episode_id'))
add('episode_sort', 'episode_number')
for key, value in info.items():
if value is not None and key != meta_prefix and key.startswith(meta_prefix):
metadata[key[len(meta_prefix):]] = value
for name, value in metadata.items():
yield ('-metadata', f'{name}={value}')
stream_idx = 0
for fmt in info.get('requested_formats') or []:
stream_count = 2 if 'none' not in (fmt.get('vcodec'), fmt.get('acodec')) else 1
if fmt.get('language'):
lang = ISO639Utils.short2long(fmt['language']) or fmt['language']
for i in range(stream_count):
yield ('-metadata:s:%d' % (stream_idx + i), 'language=%s' % lang)
stream_idx += stream_count
if ('no-attach-info-json' not in self.get_param('compat_opts', [])
and '__infojson_filename' in info and info['ext'] in ('mkv', 'mka')):
old_stream, new_stream = self.get_stream_number(info['filepath'], ('tags', 'mimetype'), 'application/json')
if old_stream is not None:
yield ('-map', '-0:%d' % old_stream)
new_stream -= 1
yield ('-attach', info['__infojson_filename'],
'-metadata:s:%d' % new_stream, 'mimetype=application/json')
class FFmpegMergerPP(FFmpegPostProcessor):
@PostProcessor._restrict_to(images=False)
def run(self, info):
filename = info['filepath']
temp_filename = prepend_extension(filename, 'temp')
args = ['-c', 'copy']
audio_streams = 0
for (i, fmt) in enumerate(info['requested_formats']):
if fmt.get('acodec') != 'none':
args.extend(['-map', f'{i}:a:0'])
aac_fixup = fmt['protocol'].startswith('m3u8') and self.get_audio_codec(fmt['filepath']) == 'aac'
if aac_fixup:
args.extend([f'-bsf:a:{audio_streams}', 'aac_adtstoasc'])
audio_streams += 1
if fmt.get('vcodec') != 'none':
args.extend(['-map', '%u:v:0' % (i)])
self.to_screen('Merging formats into "%s"' % filename)
self.run_ffmpeg_multiple_files(info['__files_to_merge'], temp_filename, args)
os.rename(encodeFilename(temp_filename), encodeFilename(filename))
return info['__files_to_merge'], info
def can_merge(self):
# TODO: figure out merge-capable ffmpeg version
if self.basename != 'avconv':
return True
required_version = '10-0'
if is_outdated_version(
self._versions[self.basename], required_version):
warning = ('Your copy of %s is outdated and unable to properly mux separate video and audio files, '
'yt-dlp will download single file media. '
'Update %s to version %s or newer to fix this.') % (
self.basename, self.basename, required_version)
self.report_warning(warning)
return False
return True
class FFmpegFixupPostProcessor(FFmpegPostProcessor):
def _fixup(self, msg, filename, options):
temp_filename = prepend_extension(filename, 'temp')
self.to_screen(f'{msg} of "{filename}"')
self.run_ffmpeg(filename, temp_filename, options)
os.replace(temp_filename, filename)
class FFmpegFixupStretchedPP(FFmpegFixupPostProcessor):
@PostProcessor._restrict_to(images=False, audio=False)
def run(self, info):
stretched_ratio = info.get('stretched_ratio')
if stretched_ratio not in (None, 1):
self._fixup('Fixing aspect ratio', info['filepath'], [
'-c', 'copy', '-map', '0', '-dn', '-aspect', '%f' % stretched_ratio])
return [], info
class FFmpegFixupM4aPP(FFmpegFixupPostProcessor):
@PostProcessor._restrict_to(images=False, video=False)
def run(self, info):
if info.get('container') == 'm4a_dash':
self._fixup('Correcting container', info['filepath'], [
'-c', 'copy', '-map', '0', '-dn', '-f', 'mp4'])
return [], info
class FFmpegFixupM3u8PP(FFmpegFixupPostProcessor):
@PostProcessor._restrict_to(images=False)
def run(self, info):
if self.get_audio_codec(info['filepath']) == 'aac':
self._fixup('Fixing malformed AAC bitstream', info['filepath'], [
'-c', 'copy', '-map', '0', '-dn', '-f', 'mp4', '-bsf:a', 'aac_adtstoasc'])
return [], info
class FFmpegFixupTimestampPP(FFmpegFixupPostProcessor):
def __init__(self, downloader=None, trim=0.001):
# "trim" should be used when the video contains unintended packets
super(FFmpegFixupTimestampPP, self).__init__(downloader)
assert isinstance(trim, (int, float))
self.trim = str(trim)
@PostProcessor._restrict_to(images=False)
def run(self, info):
required_version = '4.4'
if is_outdated_version(self._versions[self.basename], required_version):
self.report_warning(
'A re-encode is needed to fix timestamps in older versions of ffmpeg. '
f'Please install ffmpeg {required_version} or later to fixup without re-encoding')
opts = ['-vf', 'setpts=PTS-STARTPTS']
else:
opts = ['-c', 'copy', '-bsf', 'setts=ts=TS-STARTPTS']
self._fixup('Fixing frame timestamp', info['filepath'], opts + ['-map', '0', '-dn', '-ss', self.trim])
return [], info
class FFmpegFixupDurationPP(FFmpegFixupPostProcessor):
@PostProcessor._restrict_to(images=False)
def run(self, info):
self._fixup('Fixing video duration', info['filepath'], ['-c', 'copy', '-map', '0', '-dn'])
return [], info
class FFmpegSubtitlesConvertorPP(FFmpegPostProcessor):
SUPPORTED_EXTS = ('srt', 'vtt', 'ass', 'lrc')
def __init__(self, downloader=None, format=None):
super(FFmpegSubtitlesConvertorPP, self).__init__(downloader)
self.format = format
def run(self, info):
subs = info.get('requested_subtitles')
new_ext = self.format
new_format = new_ext
if new_format == 'vtt':
new_format = 'webvtt'
if subs is None:
self.to_screen('There aren\'t any subtitles to convert')
return [], info
self.to_screen('Converting subtitles')
sub_filenames = []
for lang, sub in subs.items():
if not os.path.exists(sub.get('filepath', '')):
self.report_warning(f'Skipping embedding {lang} subtitle because the file is missing')
continue
ext = sub['ext']
if ext == new_ext:
self.to_screen('Subtitle file for %s is already in the requested format' % new_ext)
continue
elif ext == 'json':
self.to_screen(
'You have requested to convert json subtitles into another format, '
'which is currently not possible')
continue
old_file = sub['filepath']
sub_filenames.append(old_file)
new_file = replace_extension(old_file, new_ext)
if ext in ('dfxp', 'ttml', 'tt'):
self.report_warning(
'You have requested to convert dfxp (TTML) subtitles into another format, '
'which results in style information loss')
dfxp_file = old_file
srt_file = replace_extension(old_file, 'srt')
with open(dfxp_file, 'rb') as f:
srt_data = dfxp2srt(f.read())
with io.open(srt_file, 'wt', encoding='utf-8') as f:
f.write(srt_data)
old_file = srt_file
subs[lang] = {
'ext': 'srt',
'data': srt_data,
'filepath': srt_file,
}
if new_ext == 'srt':
continue
else:
sub_filenames.append(srt_file)
self.run_ffmpeg(old_file, new_file, ['-f', new_format])
with io.open(new_file, 'rt', encoding='utf-8') as f:
subs[lang] = {
'ext': new_ext,
'data': f.read(),
'filepath': new_file,
}
info['__files_to_move'][new_file] = replace_extension(
info['__files_to_move'][sub['filepath']], new_ext)
return sub_filenames, info
class FFmpegSplitChaptersPP(FFmpegPostProcessor):
def __init__(self, downloader, force_keyframes=False):
FFmpegPostProcessor.__init__(self, downloader)
self._force_keyframes = force_keyframes
def _prepare_filename(self, number, chapter, info):
info = info.copy()
info.update({
'section_number': number,
'section_title': chapter.get('title'),
'section_start': chapter.get('start_time'),
'section_end': chapter.get('end_time'),
})
return self._downloader.prepare_filename(info, 'chapter')
def _ffmpeg_args_for_chapter(self, number, chapter, info):
destination = self._prepare_filename(number, chapter, info)
if not self._downloader._ensure_dir_exists(encodeFilename(destination)):
return
chapter['filepath'] = destination
self.to_screen('Chapter %03d; Destination: %s' % (number, destination))
return (
destination,
['-ss', compat_str(chapter['start_time']),
'-t', compat_str(chapter['end_time'] - chapter['start_time'])])
@PostProcessor._restrict_to(images=False)
def run(self, info):
chapters = info.get('chapters') or []
if not chapters:
self.to_screen('Chapter information is unavailable')
return [], info
in_file = info['filepath']
if self._force_keyframes and len(chapters) > 1:
in_file = self.force_keyframes(in_file, (c['start_time'] for c in chapters))
self.to_screen('Splitting video by chapters; %d chapters found' % len(chapters))
for idx, chapter in enumerate(chapters):
destination, opts = self._ffmpeg_args_for_chapter(idx + 1, chapter, info)
self.real_run_ffmpeg([(in_file, opts)], [(destination, ['-c', 'copy'])])
if in_file != info['filepath']:
os.remove(in_file)
return [], info
class FFmpegThumbnailsConvertorPP(FFmpegPostProcessor):
SUPPORTED_EXTS = ('jpg', 'png')
def __init__(self, downloader=None, format=None):
super(FFmpegThumbnailsConvertorPP, self).__init__(downloader)
self.format = format
@staticmethod
def is_webp(path):
with open(encodeFilename(path), 'rb') as f:
b = f.read(12)
return b[0:4] == b'RIFF' and b[8:] == b'WEBP'
def fixup_webp(self, info, idx=-1):
thumbnail_filename = info['thumbnails'][idx]['filepath']
_, thumbnail_ext = os.path.splitext(thumbnail_filename)
if thumbnail_ext:
thumbnail_ext = thumbnail_ext[1:].lower()
if thumbnail_ext != 'webp' and self.is_webp(thumbnail_filename):
self.to_screen('Correcting thumbnail "%s" extension to webp' % thumbnail_filename)
webp_filename = replace_extension(thumbnail_filename, 'webp')
os.replace(thumbnail_filename, webp_filename)
info['thumbnails'][idx]['filepath'] = webp_filename
info['__files_to_move'][webp_filename] = replace_extension(
info['__files_to_move'].pop(thumbnail_filename), 'webp')
@staticmethod
def _options(target_ext):
if target_ext == 'jpg':
return ['-bsf:v', 'mjpeg2jpeg']
return []
def convert_thumbnail(self, thumbnail_filename, target_ext):
thumbnail_conv_filename = replace_extension(thumbnail_filename, target_ext)
self.to_screen('Converting thumbnail "%s" to %s' % (thumbnail_filename, target_ext))
self.real_run_ffmpeg(
[(thumbnail_filename, ['-f', 'image2', '-pattern_type', 'none'])],
[(thumbnail_conv_filename.replace('%', '%%'), self._options(target_ext))])
return thumbnail_conv_filename
def run(self, info):
files_to_delete = []
has_thumbnail = False
for idx, thumbnail_dict in enumerate(info['thumbnails']):
if 'filepath' not in thumbnail_dict:
continue
has_thumbnail = True
self.fixup_webp(info, idx)
original_thumbnail = thumbnail_dict['filepath']
_, thumbnail_ext = os.path.splitext(original_thumbnail)
if thumbnail_ext:
thumbnail_ext = thumbnail_ext[1:].lower()
if thumbnail_ext == 'jpeg':
thumbnail_ext = 'jpg'
if thumbnail_ext == self.format:
self.to_screen('Thumbnail "%s" is already in the requested format' % original_thumbnail)
continue
thumbnail_dict['filepath'] = self.convert_thumbnail(original_thumbnail, self.format)
files_to_delete.append(original_thumbnail)
info['__files_to_move'][thumbnail_dict['filepath']] = replace_extension(
info['__files_to_move'][original_thumbnail], self.format)
if not has_thumbnail:
self.to_screen('There aren\'t any thumbnails to convert')
return files_to_delete, info
| 41.229331
| 137
| 0.583447
|
4a0a9650104ef8be16c5eef5e4c8fc4c68a16810
| 387
|
py
|
Python
|
alot_checkmail/__init__.py
|
tbjers/alot-plugin-checkmail
|
7e2461be2baf695c2a3cb58ea368dbd60f867441
|
[
"MIT"
] | null | null | null |
alot_checkmail/__init__.py
|
tbjers/alot-plugin-checkmail
|
7e2461be2baf695c2a3cb58ea368dbd60f867441
|
[
"MIT"
] | null | null | null |
alot_checkmail/__init__.py
|
tbjers/alot-plugin-checkmail
|
7e2461be2baf695c2a3cb58ea368dbd60f867441
|
[
"MIT"
] | null | null | null |
__productname__ = "alot-plugin-checkmail"
__version__ = "0.0.15"
__copyright__ = "Copyright (c) 2021 Torgny Bjers"
__author__ = "Torgny Bjers"
__author_email__ = "torgny@bjers.org"
__description__ = "Command wrapper with feedback for checking mail and other long-running tasks."
__url__ = "https://github.com/tbjers/alot-plugin-checkmail"
__license__ = "Licensed under the MIT license."
| 43
| 97
| 0.777778
|
4a0a97f1847cc94bb5e73b4db4d3a4eeb4f40112
| 1,612
|
py
|
Python
|
code/analysis/English/get_V-measure.py
|
tkc-morita/variational_inference_DP_mix_HDP_topic_ngram
|
95d6c8ab2956501fc82b416bf423ee57fe77c73f
|
[
"MIT"
] | 4
|
2021-03-27T18:28:23.000Z
|
2022-01-10T23:32:29.000Z
|
code/analysis/English/get_V-measure.py
|
stannam/variational_inference_DP_mix_HDP_topic_ngram
|
95d6c8ab2956501fc82b416bf423ee57fe77c73f
|
[
"MIT"
] | null | null | null |
code/analysis/English/get_V-measure.py
|
stannam/variational_inference_DP_mix_HDP_topic_ngram
|
95d6c8ab2956501fc82b416bf423ee57fe77c73f
|
[
"MIT"
] | 1
|
2022-01-10T23:45:54.000Z
|
2022-01-10T23:45:54.000Z
|
# coding: utf-8
import pandas as pd
import sklearn.metrics as skm
import argparse, os
def get_V_measure(df):
labels_true = df.actual_sublex
labels_pred = df.predicted_sublex
return skm.v_measure_score(labels_true, labels_pred)
def get_correct_sublex(data_path):
df_data = pd.read_csv(data_path, sep='\t', encoding='utf-8')
df_data = df_data[~df_data.origin.isnull()]
origin2ix=dict([('AngloSaxon', 0), ('OldNorse', 0), (u'Dutch', 0), (u'Latin', 1), (u'French', 1), (u'LatinatesOfGermanic', -1)])
df_data['actual_sublex']=df_data.origin.map(origin2ix)
return df_data
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('result_path', type=str, help='Path to the classification results.')
parser.add_argument('data_path', type=str, help='Path to the data, containing the grand truth classification info.')
parser.add_argument('-w', '--whole_data', action='store_true', help='Use the whole data rather than Anglo-Saxon and Latin alone.')
args = parser.parse_args()
df_pred = pd.read_csv(args.result_path)
df = get_correct_sublex(args.data_path)
remove_circumfix = lambda s: int(s.split('_')[1])
df['predicted_sublex'] = df_pred.most_probable_sublexicon.map(remove_circumfix)
if args.whole_data:
filename = 'v-measure_whole-Wiki.txt'
else:
filename = 'v-measure_AngloSaxon-Latin.txt'
df = df[df.origin.isin(['AngloSaxon','Latin'])]
df = df[df.actual_sublex!=-1]
v_measure = get_V_measure(df)
result_dir = os.path.split(args.result_path)[0]
with open(os.path.join(result_dir,filename), 'w') as f:
f.write('V-measure: %s' % str(v_measure))
| 32.24
| 131
| 0.73201
|
4a0a9a442beed2eaaf55b65333cdacfcef5d21a5
| 890
|
py
|
Python
|
pipeline/histology.py
|
xiaow2/orofacial_pipeline
|
fdfac5d1a2dd780f017966dc353f77eda1d21b93
|
[
"MIT"
] | null | null | null |
pipeline/histology.py
|
xiaow2/orofacial_pipeline
|
fdfac5d1a2dd780f017966dc353f77eda1d21b93
|
[
"MIT"
] | 3
|
2020-08-20T22:47:52.000Z
|
2020-09-16T21:06:09.000Z
|
pipeline/histology.py
|
xiaow2/orofacial_pipeline
|
fdfac5d1a2dd780f017966dc353f77eda1d21b93
|
[
"MIT"
] | 2
|
2020-07-31T22:12:02.000Z
|
2020-10-08T18:55:03.000Z
|
import datajoint as dj
from . import lab, experiment, ccf, ephys
from . import get_schema_name
[lab, experiment, ccf, ephys] # schema imports only
schema = dj.schema(get_schema_name('histology'))
@schema
class ElectrodeCCFPosition(dj.Imported):
definition = """
-> ephys.ProbeInsertion
"""
class ElectrodePosition(dj.Part):
definition = """
-> master
-> lab.ElectrodeConfig.Electrode
---
-> ccf.CCF
"""
@schema
class LabeledProbeTrack(dj.Imported):
definition = """
-> ephys.ProbeInsertion
---
labeling_date=NULL: date
dye_color=NULL: varchar(32)
"""
class Point(dj.Part):
definition = """
-> master
order: int
shank: int
---
ccf_x: float # (um)
ccf_y: float # (um)
ccf_z: float # (um)
"""
| 20.227273
| 52
| 0.552809
|
4a0a9bcb0bf0b7e66acb1b89dd234ee5957d1e6c
| 6,730
|
py
|
Python
|
setup.py
|
johnsonkee/mmocr_wxz
|
867b91664ea373873557743c2a4be23fa014b14f
|
[
"Apache-2.0"
] | null | null | null |
setup.py
|
johnsonkee/mmocr_wxz
|
867b91664ea373873557743c2a4be23fa014b14f
|
[
"Apache-2.0"
] | null | null | null |
setup.py
|
johnsonkee/mmocr_wxz
|
867b91664ea373873557743c2a4be23fa014b14f
|
[
"Apache-2.0"
] | null | null | null |
import glob
import os
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (CUDA_HOME, BuildExtension, CppExtension,
CUDAExtension)
def readme():
with open('README.md', encoding='utf-8') as f:
content = f.read()
return content
version_file = 'mmocr/version.py'
def get_version():
with open(version_file, 'r') as f:
exec(compile(f.read(), version_file, 'exec'))
import sys
# return short version for sdist
if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
return locals()['short_version']
else:
return locals()['__version__']
def parse_requirements(fname='requirements.txt', with_version=True):
"""Parse the package dependencies listed in a requirements file but strip
specific version information.
Args:
fname (str): Path to requirements file.
with_version (bool, default=False): If True, include version specs.
Returns:
info (list[str]): List of requirements items.
CommandLine:
python -c "import setup; print(setup.parse_requirements())"
"""
import sys
from os.path import exists
import re
require_fpath = fname
def parse_line(line):
"""Parse information from a line in a requirements text file."""
if line.startswith('-r '):
# Allow specifying requirements in other files
target = line.split(' ')[1]
for info in parse_require_file(target):
yield info
else:
info = {'line': line}
if line.startswith('-e '):
info['package'] = line.split('#egg=')[1]
else:
# Remove versioning from the package
pat = '(' + '|'.join(['>=', '==', '>']) + ')'
parts = re.split(pat, line, maxsplit=1)
parts = [p.strip() for p in parts]
info['package'] = parts[0]
if len(parts) > 1:
op, rest = parts[1:]
if ';' in rest:
# Handle platform specific dependencies
# http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
version, platform_deps = map(str.strip,
rest.split(';'))
info['platform_deps'] = platform_deps
else:
version = rest # NOQA
info['version'] = (op, version)
yield info
def parse_require_file(fpath):
with open(fpath, 'r') as f:
for line in f.readlines():
line = line.strip()
if line and not line.startswith('#'):
for info in parse_line(line):
yield info
def gen_packages_items():
if exists(require_fpath):
for info in parse_require_file(require_fpath):
parts = [info['package']]
if with_version and 'version' in info:
parts.extend(info['version'])
if not sys.version.startswith('3.4'):
# apparently package_deps are broken in 3.4
platform_deps = info.get('platform_deps')
if platform_deps is not None:
parts.append(';' + platform_deps)
item = ''.join(parts)
yield item
packages = list(gen_packages_items())
return packages
def get_rroi_align_extensions():
extensions_dir = 'mmocr/models/utils/ops/rroi_align/csrc/csc'
main_file = glob.glob(os.path.join(extensions_dir, '*.cpp'))
source_cpu = glob.glob(os.path.join(extensions_dir, 'cpu', '*.cpp'))
source_cuda = glob.glob(os.path.join(extensions_dir, 'cuda', '*.cu'))
sources = main_file + source_cpu
extension = CppExtension
extra_compile_args = {'cxx': []}
define_macros = []
if torch.cuda.is_available() and CUDA_HOME is not None:
extension = CUDAExtension
sources += source_cuda
define_macros += [('WITH_CUDA', None)]
extra_compile_args['nvcc'] = [
'-DCUDA_HAS_FP16=1',
'-D__CUDA_NO_HALF_OPERATORS__',
'-D__CUDA_NO_HALF_CONVERSIONS__',
'-D__CUDA_NO_HALF2_OPERATORS__',
]
print(sources)
include_dirs = [extensions_dir]
print('include_dirs', include_dirs, flush=True)
ext = extension(
name='mmocr.models.utils.ops.rroi_align.csrc',
sources=sources,
include_dirs=include_dirs,
define_macros=define_macros,
extra_compile_args=extra_compile_args,
)
return ext
if __name__ == '__main__':
library_dirs = [
lp for lp in os.environ.get('LD_LIBRARY_PATH', '').split(':')
if len(lp) > 1
]
cpp_root = 'mmocr/models/textdet/postprocess/'
setup(
name='mmocr',
version=get_version(),
description='Text Detection, OCR, and NLP Toolbox',
long_description=readme(),
keywords='Text Detection, OCR, KIE, NLP',
url='https://github.com/open-mmlab/mmocr',
packages=find_packages(exclude=('configs', 'tools', 'demo')),
package_data={'mmocr.ops': ['*/*.so']},
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
],
license='Apache License 2.0',
setup_requires=parse_requirements('requirements/build.txt'),
tests_require=parse_requirements('requirements/tests.txt'),
install_requires=parse_requirements('requirements/runtime.txt'),
extras_require={
'all': parse_requirements('requirements.txt'),
'tests': parse_requirements('requirements/tests.txt'),
'build': parse_requirements('requirements/build.txt'),
'optional': parse_requirements('requirements/optional.txt'),
},
ext_modules=[
CppExtension(
name='mmocr.models.textdet.postprocess.pan',
sources=[cpp_root + 'pan.cpp']),
CppExtension(
name='mmocr.models.textdet.postprocess.pse',
sources=[cpp_root + 'pse.cpp']),
get_rroi_align_extensions()
],
cmdclass={'build_ext': BuildExtension},
zip_safe=False)
| 36.378378
| 125
| 0.567162
|
4a0a9bf0f70bfa1accb5cd3b6840ef4e2d05b536
| 285
|
py
|
Python
|
python_python3/1961.py
|
mayconrebordao/uri-codes
|
1081c25ecaf0142f38c7ba287bd01490a1d34474
|
[
"MIT"
] | null | null | null |
python_python3/1961.py
|
mayconrebordao/uri-codes
|
1081c25ecaf0142f38c7ba287bd01490a1d34474
|
[
"MIT"
] | null | null | null |
python_python3/1961.py
|
mayconrebordao/uri-codes
|
1081c25ecaf0142f38c7ba287bd01490a1d34474
|
[
"MIT"
] | null | null | null |
a= input();
b =a.split(" ")
n = int (b[0])
m = int (b[1])
cont = 0
f=input();
r=f.split(" ")
ter= int(r[0])
for i in range (1,m):
if((int(r[i])-ter)>n):
cont+=1
elif ((ter-n)>int(r[i])):
cont+=1
ter=(int(r[i]))
#elif()
if(cont!=0):
print("GAME OVER")
else :
print("YOU WIN")
| 15
| 26
| 0.508772
|
4a0a9e67b071da2bf455fbf769820dc9cd8bf5d8
| 1,104
|
py
|
Python
|
grapple/types/media.py
|
ruisaraiva19/wagtail-grapple
|
1c674f1e2c8800adb9f51cd3497ff55f72f100b3
|
[
"MIT"
] | null | null | null |
grapple/types/media.py
|
ruisaraiva19/wagtail-grapple
|
1c674f1e2c8800adb9f51cd3497ff55f72f100b3
|
[
"MIT"
] | null | null | null |
grapple/types/media.py
|
ruisaraiva19/wagtail-grapple
|
1c674f1e2c8800adb9f51cd3497ff55f72f100b3
|
[
"MIT"
] | null | null | null |
import graphene
from graphene_django import DjangoObjectType
from wagtailmedia.models import Media, get_media_model
from ..registry import registry
from ..utils import get_media_item_url, resolve_queryset
from .structures import QuerySetList
class MediaObjectType(DjangoObjectType):
class Meta:
model = Media
exclude_fields = ("tags",)
url = graphene.String(required=True)
def resolve_url(self, info):
"""
Get Media file url.
"""
return get_media_item_url(self)
def MediaQuery():
registry.media[Media] = MediaObjectType
mdl = get_media_model()
model_type = registry.media[mdl]
class Mixin:
media = QuerySetList(
graphene.NonNull(model_type), enable_search=True, required=True
)
# Return all pages, ideally specific.
def resolve_media(self, info, **kwargs):
return resolve_queryset(mdl.objects.all(), info, **kwargs)
return Mixin
def get_media_type():
registry.media[Media] = MediaObjectType
mdl = get_media_model()
return registry.media[mdl]
| 23.489362
| 75
| 0.682065
|
4a0a9eda808a337b58e59554d23f4223e69e38ea
| 17,206
|
py
|
Python
|
napari/layers/vectors/_tests/test_vectors.py
|
Zac-HD/napari
|
102a7e8f845893c874d2b86f9371d41130100b89
|
[
"BSD-3-Clause"
] | null | null | null |
napari/layers/vectors/_tests/test_vectors.py
|
Zac-HD/napari
|
102a7e8f845893c874d2b86f9371d41130100b89
|
[
"BSD-3-Clause"
] | 2
|
2021-05-17T02:15:08.000Z
|
2022-03-12T21:19:52.000Z
|
napari/layers/vectors/_tests/test_vectors.py
|
Zac-HD/napari
|
102a7e8f845893c874d2b86f9371d41130100b89
|
[
"BSD-3-Clause"
] | null | null | null |
import numpy as np
import pandas as pd
import pytest
from vispy.color import get_colormap
from napari._tests.utils import check_layer_world_data_extent
from napari.layers import Vectors
from napari.utils.colormaps.standardize_color import transform_color
# Set random seed for testing
np.random.seed(0)
def test_random_vectors():
"""Test instantiating Vectors layer with random coordinate-like 2D data."""
shape = (10, 2, 2)
np.random.seed(0)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert np.all(layer.data == data)
assert layer.data.shape == shape
assert layer.ndim == shape[2]
assert layer._view_data.shape[2] == 2
def test_random_vectors_image():
"""Test instantiating Vectors layer with random image-like 2D data."""
shape = (20, 10, 2)
np.random.seed(0)
data = np.random.random(shape)
layer = Vectors(data)
assert layer.data.shape == (20 * 10, 2, 2)
assert layer.ndim == 2
assert layer._view_data.shape[2] == 2
def test_empty_vectors():
"""Test instantiating Vectors layer with empty coordinate-like 2D data."""
shape = (0, 2, 2)
data = np.empty(shape)
layer = Vectors(data)
assert np.all(layer.data == data)
assert layer.data.shape == shape
assert layer.ndim == shape[2]
assert layer._view_data.shape[2] == 2
def test_empty_vectors_with_properties():
"""Test instantiating Vectors layer with empty coordinate-like 2D data."""
shape = (0, 2, 2)
data = np.empty(shape)
properties = {'angle': np.array([0.5], dtype=float)}
layer = Vectors(data, properties=properties)
assert np.all(layer.data == data)
assert layer.data.shape == shape
assert layer.ndim == shape[2]
assert layer._view_data.shape[2] == 2
np.testing.assert_equal(layer._property_choices, properties)
def test_empty_layer_with_edge_colormap():
"""Test creating an empty layer where the edge color is a colormap"""
shape = (0, 2, 2)
data = np.empty(shape)
default_properties = {'angle': np.array([1.5], dtype=float)}
layer = Vectors(
data=data,
properties=default_properties,
edge_color='angle',
edge_colormap='grays',
)
assert layer.edge_color_mode == 'colormap'
# edge_color should remain empty when refreshing colors
layer.refresh_colors(update_color_mapping=True)
np.testing.assert_equal(layer.edge_color, np.empty((0, 4)))
def test_empty_layer_with_edge_color_cycle():
"""Test creating an empty layer where the edge color is a color cycle"""
shape = (0, 2, 2)
data = np.empty(shape)
default_properties = {'vector_type': np.array(['A'])}
layer = Vectors(
data=data,
properties=default_properties,
edge_color='vector_type',
)
assert layer.edge_color_mode == 'cycle'
# edge_color should remain empty when refreshing colors
layer.refresh_colors(update_color_mapping=True)
np.testing.assert_equal(layer.edge_color, np.empty((0, 4)))
def test_random_3D_vectors():
"""Test instantiating Vectors layer with random coordinate-like 3D data."""
shape = (10, 2, 3)
np.random.seed(0)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert np.all(layer.data == data)
assert layer.data.shape == shape
assert layer.ndim == shape[2]
assert layer._view_data.shape[2] == 2
def test_random_3D_vectors_image():
"""Test instantiating Vectors layer with random image-like 3D data."""
shape = (12, 20, 10, 3)
np.random.seed(0)
data = np.random.random(shape)
layer = Vectors(data)
assert layer.data.shape == (12 * 20 * 10, 2, 3)
assert layer.ndim == 3
assert layer._view_data.shape[2] == 2
@pytest.mark.filterwarnings("ignore:Passing `np.nan`:DeprecationWarning:numpy")
def test_empty_3D_vectors():
"""Test instantiating Vectors layer with empty coordinate-like 3D data."""
shape = (0, 2, 3)
data = np.empty(shape)
layer = Vectors(data)
assert np.all(layer.data == data)
assert layer.data.shape == shape
assert layer.ndim == shape[2]
assert layer._view_data.shape[2] == 2
def test_properties_dataframe():
"""test if properties can be provided as a DataFrame"""
shape = (10, 2)
np.random.seed(0)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
properties = {'vector_type': np.array(['A', 'B'] * int(shape[0] / 2))}
properties_df = pd.DataFrame(properties)
properties_df = properties_df.astype(properties['vector_type'].dtype)
layer = Vectors(data, properties=properties_df)
np.testing.assert_equal(layer.properties, properties)
# test adding a dataframe via the properties setter
properties_2 = {'vector_type2': np.array(['A', 'B'] * int(shape[0] / 2))}
properties_df2 = pd.DataFrame(properties_2)
layer.properties = properties_df2
np.testing.assert_equal(layer.properties, properties_2)
def test_adding_properties():
"""test adding properties to a Vectors layer"""
shape = (10, 2)
np.random.seed(0)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
properties = {'vector_type': np.array(['A', 'B'] * int(shape[0] / 2))}
layer = Vectors(data)
# properties should start empty
assert layer.properties == {}
# add properties
layer.properties = properties
np.testing.assert_equal(layer.properties, properties)
# removing a property that was the _edge_color_property should give a warning
layer._edge_color_property = 'vector_type'
properties_2 = {
'not_vector_type': np.array(['A', 'B'] * int(shape[0] / 2))
}
with pytest.warns(UserWarning):
layer.properties = properties_2
# adding properties with the wrong length should raise an exception
bad_properties = {'vector_type': np.array(['A'])}
with pytest.raises(ValueError):
layer.properties = bad_properties
def test_changing_data():
"""Test changing Vectors data."""
shape_a = (10, 2, 2)
np.random.seed(0)
data_a = np.random.random(shape_a)
data_a[:, 0, :] = 20 * data_a[:, 0, :]
shape_b = (16, 2, 2)
data_b = np.random.random(shape_b)
data_b[:, 0, :] = 20 * data_b[:, 0, :]
layer = Vectors(data_b)
layer.data = data_b
assert np.all(layer.data == data_b)
assert layer.data.shape == shape_b
assert layer.ndim == shape_b[2]
assert layer._view_data.shape[2] == 2
def test_name():
"""Test setting layer name."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.name == 'Vectors'
layer = Vectors(data, name='random')
assert layer.name == 'random'
layer.name = 'vcts'
assert layer.name == 'vcts'
def test_visiblity():
"""Test setting layer visibility."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.visible is True
layer.visible = False
assert layer.visible is False
layer = Vectors(data, visible=False)
assert layer.visible is False
layer.visible = True
assert layer.visible is True
def test_opacity():
"""Test setting layer opacity."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.opacity == 0.7
layer.opacity = 0.5
assert layer.opacity == 0.5
layer = Vectors(data, opacity=0.6)
assert layer.opacity == 0.6
layer.opacity = 0.3
assert layer.opacity == 0.3
def test_blending():
"""Test setting layer blending."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.blending == 'translucent'
layer.blending = 'additive'
assert layer.blending == 'additive'
layer = Vectors(data, blending='additive')
assert layer.blending == 'additive'
layer.blending = 'opaque'
assert layer.blending == 'opaque'
def test_edge_width():
"""Test setting edge width."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.edge_width == 1
layer.edge_width = 2
assert layer.edge_width == 2
layer = Vectors(data, edge_width=3)
assert layer.edge_width == 3
def test_invalid_edge_color():
"""Test providing an invalid edge color raises an exception"""
np.random.seed(0)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
with pytest.raises(ValueError):
layer.edge_color = 5
def test_edge_color_direct():
"""Test setting edge color."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
np.testing.assert_allclose(
layer.edge_color, np.repeat([[1, 0, 0, 1]], data.shape[0], axis=0)
)
# set edge color as an RGB array
layer.edge_color = [0, 0, 1]
np.testing.assert_allclose(
layer.edge_color, np.repeat([[0, 0, 1, 1]], data.shape[0], axis=0)
)
# set edge color as an RGBA array
layer.edge_color = [0, 1, 0, 0.5]
np.testing.assert_allclose(
layer.edge_color, np.repeat([[0, 1, 0, 0.5]], data.shape[0], axis=0)
)
# set all edge colors directly
edge_colors = np.random.random((data.shape[0], 4))
layer.edge_color = edge_colors
np.testing.assert_allclose(layer.edge_color, edge_colors)
def test_edge_color_cycle():
"""Test creating Vectors where edge color is set by a color cycle"""
np.random.seed(0)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
properties = {'vector_type': np.array(['A', 'B'] * int(shape[0] / 2))}
color_cycle = ['red', 'blue']
layer = Vectors(
data,
properties=properties,
edge_color='vector_type',
edge_color_cycle=color_cycle,
)
np.testing.assert_equal(layer.properties, properties)
edge_color_array = transform_color(color_cycle * int(shape[0] / 2))
assert np.all(layer.edge_color == edge_color_array)
def test_edge_color_colormap():
"""Test creating Vectors where edge color is set by a colormap """
shape = (10, 2)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
properties = {'angle': np.array([0, 1.5] * int(shape[0] / 2))}
layer = Vectors(
data,
properties=properties,
edge_color='angle',
edge_colormap='gray',
)
assert layer.properties == properties
assert layer.edge_color_mode == 'colormap'
edge_color_array = transform_color(['black', 'white'] * int(shape[0] / 2))
assert np.all(layer.edge_color == edge_color_array)
# change the color cycle - edge_color should not change
layer.edge_color_cycle = ['red', 'blue']
assert np.all(layer.edge_color == edge_color_array)
# adjust the clims
layer.edge_contrast_limits = (0, 3)
layer.refresh_colors(update_color_mapping=False)
np.testing.assert_allclose(layer.edge_color[-1], [0.5, 0.5, 0.5, 1])
# change the colormap
new_colormap = 'viridis'
layer.edge_colormap = new_colormap
assert layer.edge_colormap.name == new_colormap
# test adding a colormap with a vispy Colormap object
layer.edge_colormap = get_colormap('gray')
assert 'unnamed colormap' in layer.edge_colormap.name
def test_edge_color_map_non_numeric_property():
"""Test setting edge_color as a color map of a
non-numeric property raises an error
"""
np.random.seed(0)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
properties = {'vector_type': np.array(['A', 'B'] * int(shape[0] / 2))}
color_cycle = ['red', 'blue']
initial_color = [0, 1, 0, 1]
layer = Vectors(
data,
properties=properties,
edge_color=initial_color,
edge_color_cycle=color_cycle,
edge_colormap='gray',
)
# layer should start out in direct edge color mode with all green vectors
assert layer.edge_color_mode == 'direct'
np.testing.assert_allclose(
layer.edge_color, np.repeat([initial_color], shape[0], axis=0)
)
# switching to colormap mode should raise an error because the 'vector_type' is non-numeric
layer.edge_color = 'vector_type'
with pytest.raises(TypeError):
layer.edge_color_mode = 'colormap'
@pytest.mark.filterwarnings("ignore:elementwise comparis:FutureWarning:numpy")
def test_switching_edge_color_mode():
"""Test transitioning between all color modes"""
np.random.seed(0)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
properties = {
'magnitude': np.arange(shape[0]),
'vector_type': np.array(['A', 'B'] * int(shape[0] / 2)),
}
color_cycle = ['red', 'blue']
initial_color = [0, 1, 0, 1]
layer = Vectors(
data,
properties=properties,
edge_color=initial_color,
edge_color_cycle=color_cycle,
edge_colormap='gray',
)
# layer should start out in direct edge color mode with all green vectors
assert layer.edge_color_mode == 'direct'
np.testing.assert_allclose(
layer.edge_color, np.repeat([initial_color], shape[0], axis=0)
)
# there should not be an edge_color_property
assert layer._edge_color_property == ''
# transitioning to colormap should raise a warning
# because there isn't an edge color property yet and
# the first property in Vectors.properties is being automatically selected
with pytest.warns(RuntimeWarning):
layer.edge_color_mode = 'colormap'
assert layer._edge_color_property == next(iter(properties))
np.testing.assert_allclose(layer.edge_color[-1], [1, 1, 1, 1])
# switch to color cycle
layer.edge_color_mode = 'cycle'
layer.edge_color = 'vector_type'
edge_color_array = transform_color(color_cycle * int(shape[0] / 2))
np.testing.assert_allclose(layer.edge_color, edge_color_array)
# switch back to direct, edge_colors shouldn't change
edge_colors = layer.edge_color
layer.edge_color_mode = 'direct'
np.testing.assert_allclose(layer.edge_color, edge_colors)
def test_properties_color_mode_without_properties():
"""Test that switching to a colormode requiring
properties without properties defined raises an exceptions
"""
np.random.seed(0)
shape = (10, 2, 2)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.properties == {}
with pytest.raises(ValueError):
layer.edge_color_mode = 'colormap'
with pytest.raises(ValueError):
layer.edge_color_mode = 'cycle'
def test_length():
"""Test setting length."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert layer.length == 1
layer.length = 2
assert layer.length == 2
layer = Vectors(data, length=3)
assert layer.length == 3
def test_thumbnail():
"""Test the image thumbnail for square data."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 18 * data[:, 0, :] + 1
data[0, :, :] = [0, 0]
data[-1, 0, :] = [20, 20]
data[-1, 1, :] = [0, 0]
layer = Vectors(data)
layer._update_thumbnail()
assert layer.thumbnail.shape == layer._thumbnail_shape
def test_big_thumbail():
"""Test the image thumbnail with n_vectors > _max_vectors_thumbnail"""
np.random.seed(0)
n_vectors = int(1.5 * Vectors._max_vectors_thumbnail)
data = np.random.random((n_vectors, 2, 2))
data[:, 0, :] = 18 * data[:, 0, :] + 1
data[0, :, :] = [0, 0]
data[-1, 0, :] = [20, 20]
data[-1, 1, :] = [0, 0]
layer = Vectors(data)
layer._update_thumbnail()
assert layer.thumbnail.shape == layer._thumbnail_shape
def test_value():
"""Test getting the value of the data at the current coordinates."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
value = layer.get_value((0,) * 2)
assert value is None
def test_message():
"""Test converting value and coords to message."""
np.random.seed(0)
data = np.random.random((10, 2, 2))
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
msg = layer.get_status((0,) * 2)
assert type(msg) == str
def test_world_data_extent():
"""Test extent after applying transforms."""
# data input format is start position, then length.
data = [[(7, -5, -3), (1, -1, 2)], [(0, 0, 0), (4, 30, 12)]]
min_val = (0, -6, -3)
max_val = (8, 30, 12)
layer = Vectors(np.array(data))
extent = np.array((min_val, max_val))
check_layer_world_data_extent(layer, extent, (3, 1, 1), (10, 20, 5))
| 31.22686
| 95
| 0.639079
|
4a0a9fc57dbad30d00d3ae78737a3e953440fb18
| 4,210
|
py
|
Python
|
grad/naive_max_caps_dim.py
|
XxuChen/Capsule-Specific-Attacks
|
7e5a25814ce0d26c4632df2a9e57d18d3435d18f
|
[
"MIT"
] | null | null | null |
grad/naive_max_caps_dim.py
|
XxuChen/Capsule-Specific-Attacks
|
7e5a25814ce0d26c4632df2a9e57d18d3435d18f
|
[
"MIT"
] | null | null | null |
grad/naive_max_caps_dim.py
|
XxuChen/Capsule-Specific-Attacks
|
7e5a25814ce0d26c4632df2a9e57d18d3435d18f
|
[
"MIT"
] | null | null | null |
# Copyright 2018 Xu Chen All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain 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 language governing permissions and
# limitations under the License.
# ==============================================================================
"""Naively maximizing the length of every dimension of the most activated capsule."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def compute_grads(tower_idx):
"""Compute the gradients of every dimension of the most activated
capsule of the last capsule layer w.r.t. the input tensor.
Args:
tower_idx: given tower index, which should be 0 since we are using
the first tower in any case.
Returns:
grads: the gradients of every dimension of the most activated capsule
w.r.t. the input.
batched_images: placeholder for batched image tensor
caps_norms_tensor: predicted normalized logits of the model.
"""
print('{0} Naively Maximizing Dimensions of the Most Activated Capsule {0}'.format('*'*15))
"""Get related tensors"""
# input batched images tensor
batched_images = tf.get_collection('tower_%d_batched_images' % tower_idx)[0]
# visualization related tensors
visual_tensors = tf.get_collection('tower_%d_visual' % tower_idx)
# get target tensor
caps_out_tensor = visual_tensors[-2] # (?, num_cap_types, num_atoms) (?, 10, 16)
caps_norms_tensor = visual_tensors[-1] # (?, num_cap_types) (?, 10)
"""Report the tensor information"""
print('='*10)
for i, vt in enumerate(visual_tensors):
if i == len(visual_tensors) - 1:
print('visual tensor name: {} (target)'.format(vt.name))
else:
print('visual tensor name: {}'.format(vt.name))
print('='*10)
# shorten tensor prefix name
caps_out_name_prefix = '/'.join(caps_out_tensor.name.split('/')[:-1])
print(caps_out_name_prefix)
print(caps_out_tensor.get_shape()) # (?, num_cap_types, num_atoms) (?, 10, 16)
"""Split the tensor according to which capsule it is"""
caps_split_D1_list = tf.split(
caps_out_tensor, num_or_size_splits=caps_out_tensor.get_shape()[1],
axis=1, name=caps_out_name_prefix + '/class_split')
"""Split the tensor according to which dimension it is"""
caps_split_D2_list = []
for splited_by_D1_t in caps_split_D1_list:
temp = tf.split(
splited_by_D1_t, num_or_size_splits=splited_by_D1_t.get_shape()[2],
axis=2, name='-'.join(splited_by_D1_t.name.split(':')[:-1]) + '/dim_split')
caps_split_D2_list.append(temp)
# flatten caps_split_D2_list
caps_split_D2_list = [item for sub in caps_split_D2_list for item in sub]
# squeeze out dimension 2
caps_split_D2_list = [tf.squeeze(t, axis=2) for t in caps_split_D2_list]
"""Compute gradients"""
res_grads = []
for i, caps_single_dim_t in enumerate(caps_split_D2_list):
# process name
caps_single_dim_t_name = '_'.join(caps_single_dim_t.name.split(':'))
# define objective function
obj_func = caps_single_dim_t
# compute gradients
caps_single_dim_grads = tf.gradients(obj_func, batched_images, name='gradients/' + caps_single_dim_t_name)
# append to resultant list
res_grads.append(caps_single_dim_grads)
# print process information
print('Done processing {0} ---- {1}/{2} '.format(
caps_single_dim_t_name, i+1, len(caps_split_D2_list)))
print('')
"""Flatten the list"""
res_grads = [item for sub in res_grads for item in sub]
print('Gradients computing completed!')
return res_grads, batched_images, caps_norms_tensor
| 42.959184
| 114
| 0.677672
|
4a0aa030136afaa9fde15cd02815be21b7a917e0
| 632
|
py
|
Python
|
recipes/qhull/all/test_package/conanfile.py
|
rockandsalt/conan-center-index
|
d739adcec3e4dd4c250eff559ceb738e420673dd
|
[
"MIT"
] | 562
|
2019-09-04T12:23:43.000Z
|
2022-03-29T16:41:43.000Z
|
recipes/qhull/all/test_package/conanfile.py
|
rockandsalt/conan-center-index
|
d739adcec3e4dd4c250eff559ceb738e420673dd
|
[
"MIT"
] | 9,799
|
2019-09-04T12:02:11.000Z
|
2022-03-31T23:55:45.000Z
|
recipes/qhull/all/test_package/conanfile.py
|
rockandsalt/conan-center-index
|
d739adcec3e4dd4c250eff559ceb738e420673dd
|
[
"MIT"
] | 1,126
|
2019-09-04T11:57:46.000Z
|
2022-03-31T16:43:38.000Z
|
import os
from conans import ConanFile, CMake, tools
class TestPackageConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake", "cmake_find_package_multi"
def build(self):
cmake = CMake(self)
cmake.definitions["QHULL_REENTRANT"] = self.options["qhull"].reentrant
cmake.definitions["QHULL_SHARED"] = self.options["qhull"].shared
cmake.configure()
cmake.build()
def test(self):
if not tools.cross_building(self.settings):
bin_path = os.path.join("bin", "test_package")
self.run(bin_path, run_environment=True)
| 31.6
| 78
| 0.655063
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.