file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
search_https_body_hash_to_ip.py | import argparse
import json
import logging
import os
from censys_maltego import Censys
from maltego_trx.transform import DiscoverableTransform
log_file_path = os.path.dirname(os.path.realpath(__file__))
log_file_name = 'censys_maltego_transform.log'
logging.basicConfig(filename=os.path.join(log_file_path, log_file_name), level=logging.INFO)
def get_credentials():
try:
credentials_path = os.path.dirname(os.path.realpath(__file__))
credentials_file = '.env'
cred_dict = None
with open(os.path.join(credentials_path, credentials_file), 'r') as creds_file:
cred_dict = json.loads(creds_file.read())
return cred_dict
except Exception as e:
logging.critical("Please enter your credentials in the .env file in the transforms directory.")
raise e
class | (DiscoverableTransform):
@classmethod
def create_entities(cls, request, response):
env_config = get_credentials()
api_id, api_secret = env_config.get('censys_api_id'), env_config.get('censys_api_secret')
ev = request.Value
ep = request.Properties
response = Censys(api_id, api_secret, max_pages=env_config.get('max_pages', 1)).search_https_body_hash_to_ip(
body_text=ev,
object_properties=ep
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--censys_api_id",
required=False,
metavar='XXXXXXXXXX',
help="(optional) You must provide your Censys API ID here or as an environmental variable CENSYS_API_ID")
parser.add_argument("--censys_api_secret",
required=False,
metavar='XXXXXXXXXX',
help="(optional) You must provide your Censys API SECRET here or as an environmental variable CENSYS_API_SECRET")
parser.add_argument('entity_value')
parser.add_argument('entity_properties')
args = parser.parse_args()
censys_api_id = os.getenv('CENSYS_API_ID', args.censys_api_id)
censys_api_secret = os.getenv('CENSYS_API_SECRET', args.censys_api_secret)
ev = args.entity_value
ep = args.entity_properties
Censys(censys_api_id, censys_api_secret).search_https_body_hash_to_ip(
body_text=ev, object_properties=ep
)
| search_https_body_hash_to_ip |
basic.js | const path = require('path'),
ifd = require(path.join(process.cwd(), 'dist/ifd.js')); | return val % 2 === 0;
}
});
const test = customIfd(
[undefined, 1],
[NaN, 3],
[4, 'four'],
[true, 5]
);
module.exports = {
exp: function (should) {
should.equal(test, 'four');
}
}; |
const customIfd = ifd({
create: true,
identity: function (val) { |
postprocess.py | # -*- coding: utf-8 -*-
"""
Functions used to format and clean any intermediate results loaded in or
returned by a bigfish method.
"""
import numpy as np
from scipy import ndimage as ndi
from .utils import check_array, check_parameter, get_offset_value
from skimage.measure import regionprops, find_contours
from skimage.draw import polygon_perimeter
# ### Transcription sites ###
def remove_transcription_site(mask_nuc, spots_in_foci, foci):
"""We define a transcription site as a foci detected in the nucleus.
Parameters
----------
mask_nuc : np.ndarray, bool
Binary mask of the nuclei with shape (y, x).
spots_in_foci : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci.
foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
Returns
-------
spots_in_foci_cleaned : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci. Transcription sites are removed.
foci_cleaned : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index. Transcription sites are removed.
"""
# check parameters
check_array(mask_nuc,
ndim=2,
dtype=[bool],
allow_nan=False)
check_array(spots_in_foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
# remove foci inside nuclei
mask_transcription_site = mask_nuc[foci[:, 1], foci[:, 2]]
foci_cleaned = foci[~mask_transcription_site]
# filter spots in transcription sites
spots_to_keep = foci_cleaned[:, 4]
mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)
spots_in_foci_cleaned = spots_in_foci[mask_spots_to_keep]
return spots_in_foci_cleaned, foci_cleaned
# ### Cell extraction ###
def extract_spots_from_frame(spots, z_lim=None, y_lim=None, x_lim=None):
"""Get spots coordinates within a given frame.
Parameters
----------
spots : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 3)
or (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus
the index of the foci if necessary.
z_lim : tuple[int, int]
Minimum and maximum coordinate of the frame along the z axis.
y_lim : tuple[int, int]
Minimum and maximum coordinate of the frame along the y axis.
x_lim : tuple[int, int]
Minimum and maximum coordinate of the frame along the x axis.
Returns
-------
extracted_spots : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 3)
or (nb_spots, 4). One coordinate per dimension (zyx coordinates) plus
the index of the foci if necessary.
"""
# check parameters
check_array(spots,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_parameter(z_lim=(tuple, type(None)),
y_lim=(tuple, type(None)),
x_lim=(tuple, type(None)))
# extract spots
extracted_spots = spots.copy()
if z_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 0] < z_lim[1]]
extracted_spots = extracted_spots[z_lim[0] < extracted_spots[:, 0]]
extracted_spots[:, 0] -= z_lim[0]
if y_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 1] < y_lim[1]]
extracted_spots = extracted_spots[y_lim[0] < extracted_spots[:, 1]]
extracted_spots[:, 1] -= y_lim[0]
if x_lim is not None:
extracted_spots = extracted_spots[extracted_spots[:, 2] < x_lim[1]]
extracted_spots = extracted_spots[x_lim[0] < extracted_spots[:, 2]]
extracted_spots[:, 2] -= x_lim[0]
return extracted_spots
def extract_coordinates_image(cyt_labelled, nuc_labelled, spots_out, spots_in,
foci):
"""Extract relevant coordinates from an image, based on segmentation and
detection results.
For each cell in an image we return the coordinates of the cytoplasm, the
nucleus, the RNA spots and information about the detected foci. We extract
2-d coordinates for the cell and 3-d coordinates for the spots and foci.
Parameters
----------
cyt_labelled : np.ndarray, np.uint or np.int
Labelled cytoplasms image with shape (y, x).
nuc_labelled : np.ndarray, np.uint or np.int
Labelled nuclei image with shape (y, x).
spots_out : np.ndarray, np.int64
Coordinate of the spots detected outside foci, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus a
default index (-1 for mRNAs spotted outside a foci).
spots_in : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci.
foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
Returns
-------
results : List[(cyt_coord, nuc_coord, rna_coord, cell_foci, cell)]
- cyt_coord : np.ndarray, np.int64
Coordinates of the cytoplasm border with shape (nb_points, 2).
- nuc_coord : np.ndarray, np.int64
Coordinates of the nuclei border with shape (nb_points, 2).
- rna_coord : np.ndarray, np.int64
Coordinates of the RNA spots with shape (nb_spots, 4). One
coordinate per dimension (zyx dimension), plus the index of a
potential foci.
- cell_foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
- cell : Tuple[int]
Box coordinate of the cell in the original image (min_y, min_x,
max_y and max_x).
"""
# check parameters
check_array(cyt_labelled,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64],
allow_nan=True)
check_array(nuc_labelled,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64],
allow_nan=True)
check_array(spots_out,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(spots_in,
ndim=2,
dtype=[np.int64],
allow_nan=False)
check_array(foci,
ndim=2,
dtype=[np.int64],
allow_nan=False)
# initialize results
results = []
borders = np.zeros(cyt_labelled.shape, dtype=bool)
borders[:, 0] = True
borders[0, :] = True
borders[:, cyt_labelled.shape[1] - 1] = True
borders[cyt_labelled.shape[0] - 1, :] = True
cells = regionprops(cyt_labelled)
for cell in cells:
# get information about the cell
label = cell.label
(min_y, min_x, max_y, max_x) = cell.bbox
# get masks of the cell
cyt = cyt_labelled.copy()
cyt = (cyt == label)
nuc = nuc_labelled.copy()
nuc = (nuc == label)
# check if cell is not cropped by the borders
if _check_cropped_cell(cyt, borders):
continue
# check if nucleus is in the cytoplasm
if not _check_nucleus_in_cell(cyt, nuc):
continue
# get boundaries coordinates
cyt_coord, nuc_coord = _get_boundaries_coordinates(cyt, nuc)
# filter foci
foci_cell, spots_in_foci_cell = _extract_foci(foci, spots_in, cyt)
# get rna coordinates
spots_out_foci_cell = _extract_spots_outside_foci(cyt, spots_out)
rna_coord = np.concatenate([spots_out_foci_cell, spots_in_foci_cell],
axis=0)
# filter cell without enough spots
if len(rna_coord) < 30:
continue
# initialize cell coordinates
cyt_coord[:, 0] -= min_y
cyt_coord[:, 1] -= min_x
nuc_coord[:, 0] -= min_y
nuc_coord[:, 1] -= min_x
rna_coord[:, 1] -= min_y
rna_coord[:, 2] -= min_x
foci_cell[:, 1] -= min_y
foci_cell[:, 2] -= min_x
results.append((cyt_coord, nuc_coord, rna_coord, foci_cell, cell.bbox))
return results
def _check_cropped_cell(cell_cyt_mask, border_frame):
"""
Check if a cell is cropped by the border frame.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell cytoplasm.
border_frame : np.ndarray, bool
Binary mask of the border frame.
Returns
-------
_ : bool
True if cell is cropped.
"""
# check cell is not cropped by the borders
crop = cell_cyt_mask & border_frame
if np.any(crop):
return True
else:
return False
def _check_nucleus_in_cell(cell_cyt_mask, cell_nuc_mask):
"""
Check if the nucleus is properly contained in the cell cytoplasm.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell cytoplasm.
cell_nuc_mask : np.ndarray, bool
Binary mask of the nucleus cytoplasm.
Returns
-------
_ : bool
True if the nucleus is in the cell.
"""
diff = cell_cyt_mask | cell_nuc_mask
if np.any(diff != cell_cyt_mask):
return False
else:
return True
def _get_boundaries_coordinates(cell_cyt_mask, cell_nuc_mask):
"""
Find boundaries coordinates for cytoplasm and nucleus.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Mask of the cell cytoplasm.
cell_nuc_mask : np.ndarray, bool
Mask of the cell nucleus.
Returns
-------
cyt_coord : np.ndarray, np.int64
Coordinates of the cytoplasm in 2-d (yx dimension).
nuc_coord : np.ndarray, np.int64
Coordinates of the nucleus in 2-d (yx dimension).
"""
cyt_coord = np.array([], dtype=np.int64).reshape((0, 2))
nuc_coord = np.array([], dtype=np.int64).reshape((0, 2))
# cyt coordinates
cell_cyt_coord = find_contours(cell_cyt_mask, level=0)
if len(cell_cyt_coord) == 0:
pass
elif len(cell_cyt_coord) == 1:
cyt_coord = cell_cyt_coord[0].astype(np.int64)
else:
m = 0
for coord in cell_cyt_coord:
if len(coord) > m:
m = len(coord)
cyt_coord = coord.astype(np.int64)
# nuc coordinates
cell_nuc_coord = find_contours(cell_nuc_mask, level=0)
if len(cell_nuc_coord) == 0:
pass
elif len(cell_nuc_coord) == 1:
nuc_coord = cell_nuc_coord[0].astype(np.int64)
else:
m = 0
for coord in cell_nuc_coord:
if len(coord) > m:
m = len(coord)
nuc_coord = coord.astype(np.int64)
return cyt_coord, nuc_coord
def | (foci, spots_in_foci, cell_cyt_mask):
"""
Extract foci and related spots detected in a specific cell.
Parameters
----------
foci : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
spots_in_foci : : np.ndarray, np.int64
Coordinate of the spots detected inside foci, with shape (nb_spots, 4).
One coordinate per dimension (zyx coordinates) plus the index of the
foci.
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell with shape (y, x).
Returns
-------
spots_in_foci_cell : np.ndarray, np.int64
Coordinate of the spots detected inside foci in the cell, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus the
index of the foci.
foci_cell : np.ndarray, np.int64
Array with shape (nb_foci, 5). One coordinate per dimension for the
foci centroid (zyx coordinates), the number of RNAs detected in the
foci and its index.
"""
# filter foci
mask_foci_cell = cell_cyt_mask[foci[:, 1], foci[:, 2]]
if mask_foci_cell.sum() == 0:
foci_cell = np.array([], dtype=np.int64).reshape((0, 5))
spots_in_foci_cell = np.array([], dtype=np.int64).reshape((0, 4))
return foci_cell, spots_in_foci_cell
foci_cell = foci[mask_foci_cell]
# filter spots in foci
spots_to_keep = foci_cell[:, 4]
mask_spots_to_keep = np.isin(spots_in_foci[:, 3], spots_to_keep)
spots_in_foci_cell = spots_in_foci[mask_spots_to_keep]
return foci_cell, spots_in_foci_cell
def _extract_spots_outside_foci(cell_cyt_mask, spots_out_foci):
"""
Extract spots detected outside foci, in a specific cell.
Parameters
----------
cell_cyt_mask : np.ndarray, bool
Binary mask of the cell with shape (y, x).
spots_out_foci : np.ndarray, np.int64
Coordinate of the spots detected outside foci, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus a
default index (-1 for mRNAs spotted outside a foci).
Returns
-------
spots_out_foci_cell : np.ndarray, np.int64
Coordinate of the spots detected outside foci in the cell, with shape
(nb_spots, 4). One coordinate per dimension (zyx coordinates) plus the
index of the foci.
"""
# get coordinates of rna outside foci
mask_spots_to_keep = cell_cyt_mask[spots_out_foci[:, 1],
spots_out_foci[:, 2]]
spots_out_foci_cell = spots_out_foci[mask_spots_to_keep]
return spots_out_foci_cell
# ### Segmentation postprocessing ###
# TODO add from_binary_surface_to_binary_boundaries
def center_binary_mask(cyt, nuc=None, rna=None):
"""Center a 2-d binary mask (surface or boundaries) and pad it.
One mask should be at least provided ('cyt'). If others masks are provided
('nuc' and 'rna'), they will be transformed like the main mask. All the
provided masks should have the same shape. If others coordinates are
provided, the values will be transformed, but an array of coordinates with
the same format is returned
Parameters
----------
cyt : np.ndarray, np.uint or np.int or bool
Binary image of cytoplasm with shape (y, x).
nuc : np.ndarray, np.uint or np.int or bool
Binary image of nucleus with shape (y, x) or array of nucleus
coordinates with shape (nb_points, 2).
rna : np.ndarray, np.uint or np.int or bool
Binary image of mRNAs localization with shape (y, x) or array of mRNAs
coordinates with shape (nb_points, 2) or (nb_points, 3).
Returns
-------
cyt_centered : np.ndarray, np.uint or np.int or bool
Centered binary image of cytoplasm with shape (y, x).
nuc_centered : np.ndarray, np.uint or np.int or bool
Centered binary image of nucleus with shape (y, x).
rna_centered : np.ndarray, np.uint or np.int or bool
Centered binary image of mRNAs localizations with shape (y, x).
"""
# check parameters
check_array(cyt,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
if nuc is not None:
check_array(nuc,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
if rna is not None:
check_array(rna,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
# initialize parameter
nuc_centered, rna_centered = None, None
marge = get_offset_value()
# center the binary mask of the cell
coord = np.nonzero(cyt)
coord = np.column_stack(coord)
min_y, max_y = coord[:, 0].min(), coord[:, 0].max()
min_x, max_x = coord[:, 1].min(), coord[:, 1].max()
shape_y = max_y - min_y + 1
shape_x = max_x - min_x + 1
cyt_centered_shape = (shape_y + 2 * marge, shape_x + 2 * marge)
cyt_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = cyt[min_y:max_y + 1, min_x:max_x + 1]
cyt_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
# center the binary mask of the nucleus with the same transformation
if nuc is not None:
if nuc.shape == 2:
nuc_centered = nuc.copy()
nuc_centered[:, 0] = nuc_centered[:, 0] - min_y + marge
nuc_centered[:, 1] = nuc_centered[:, 1] - min_x + marge
elif nuc.shape == cyt.shape:
nuc_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = nuc[min_y:max_y + 1, min_x:max_x + 1]
nuc_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
else:
raise ValueError("mRNAs mask should have the same shape than "
"cytoplasm mask and coordinates should be in 2-d")
# center the binary mask of the mRNAs with the same transformation
if rna is not None:
if rna.shape[1] == 3:
rna_centered = rna.copy()
rna_centered[:, 1] = rna_centered[:, 1] - min_y + marge
rna_centered[:, 2] = rna_centered[:, 2] - min_x + marge
elif rna.shape[1] == 2:
rna_centered = rna.copy()
rna_centered[:, 0] = rna_centered[:, 0] - min_y + marge
rna_centered[:, 1] = rna_centered[:, 1] - min_x + marge
elif rna.shape == cyt.shape:
rna_centered = np.zeros(cyt_centered_shape, dtype=bool)
crop = rna[min_y:max_y + 1, min_x:max_x + 1]
rna_centered[marge:shape_y + marge, marge:shape_x + marge] = crop
else:
raise ValueError("mRNAs mask should have the same shape than "
"cytoplasm mask and coordinates should be in 2-d "
"or 3-d")
return cyt_centered, nuc_centered, rna_centered
def from_surface_to_coord(binary_surface):
"""Extract coordinates from a 2-d binary matrix.
The resulting coordinates represent the external boundaries of the object.
Parameters
----------
binary_surface : np.ndarray, np.uint or np.int or bool
Binary image with shape (y, x).
Returns
-------
coord : np.ndarray, np.int64
Array of boundaries coordinates with shape (nb_points, 2).
"""
# check parameters
check_array(binary_surface,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
# from binary surface to 2D coordinates boundaries
coord = find_contours(binary_surface, level=0)[0].astype(np.int64)
return coord
def complete_coord_boundaries(coord):
"""Complete a 2-d coordinates array, by generating/interpolating missing
points.
Parameters
----------
coord : np.ndarray, np.int64
Array of coordinates to complete, with shape (nb_points, 2).
Returns
-------
coord_completed : np.ndarray, np.int64
Completed coordinates arrays, with shape (nb_points, 2).
"""
# check parameters
check_array(coord,
ndim=2,
dtype=[np.int64])
# for each array in the list, complete its coordinates using the scikit
# image method 'polygon_perimeter'
coord_y, coord_x = polygon_perimeter(coord[:, 0], coord[:, 1])
coord_y = coord_y[:, np.newaxis]
coord_x = coord_x[:, np.newaxis]
coord_completed = np.concatenate((coord_y, coord_x), axis=-1)
return coord_completed
def _from_coord_to_boundaries(coord_cyt, coord_nuc=None, coord_rna=None):
"""Convert 2-d coordinates to a binary matrix with the boundaries of the
object.
As we manipulate the coordinates of the external boundaries, the relative
binary matrix has two extra pixels in each dimension. We compensate by
reducing the marge by one in order to keep the same shape for the frame.
If others coordinates are provided, the relative binary matrix is build
with the same shape as the main coordinates.
Parameters
----------
coord_cyt : np.ndarray, np.int64
Array of cytoplasm boundaries coordinates with shape (nb_points, 2).
coord_nuc : np.ndarray, np.int64
Array of nucleus boundaries coordinates with shape (nb_points, 2).
coord_rna : np.ndarray, np.int64
Array of mRNAs coordinates with shape (nb_points, 2) or
(nb_points, 3).
Returns
-------
cyt : np.ndarray, np.uint or np.int or bool
Binary image of cytoplasm boundaries with shape (y, x).
nuc : np.ndarray, np.uint or np.int or bool
Binary image of nucleus boundaries with shape (y, x).
rna : np.ndarray, np.uint or np.int or bool
Binary image of mRNAs localizations with shape (y, x).
"""
# initialize parameter
nuc, rna = None, None
marge = get_offset_value()
marge -= 1
# from 2D coordinates boundaries to binary boundaries
max_y = coord_cyt[:, 0].max()
max_x = coord_cyt[:, 1].max()
min_y = coord_cyt[:, 0].min()
min_x = coord_cyt[:, 1].min()
shape_y = max_y - min_y + 1
shape_x = max_x - min_x + 1
image_shape = (shape_y + 2 * marge, shape_x + 2 * marge)
coord_cyt[:, 0] = coord_cyt[:, 0] - min_y + marge
coord_cyt[:, 1] = coord_cyt[:, 1] - min_x + marge
cyt = np.zeros(image_shape, dtype=bool)
cyt[coord_cyt[:, 0], coord_cyt[:, 1]] = True
# transform nucleus coordinates with the same parameters
if coord_nuc is not None:
nuc = np.zeros(image_shape, dtype=bool)
coord_nuc[:, 0] = coord_nuc[:, 0] - min_y + marge
coord_nuc[:, 1] = coord_nuc[:, 1] - min_x + marge
nuc[coord_nuc[:, 0], coord_nuc[:, 1]] = True
# transform mRNAs coordinates with the same parameters
if coord_rna is not None:
rna = np.zeros(image_shape, dtype=bool)
if coord_rna.shape[1] == 3:
coord_rna[:, 1] = coord_rna[:, 1] - min_y + marge
coord_rna[:, 2] = coord_rna[:, 2] - min_x + marge
rna[coord_rna[:, 1], coord_rna[:, 2]] = True
else:
coord_rna[:, 0] = coord_rna[:, 0] - min_y + marge
coord_rna[:, 1] = coord_rna[:, 1] - min_x + marge
rna[coord_rna[:, 0], coord_rna[:, 1]] = True
return cyt, nuc, rna
def from_boundaries_to_surface(binary_boundaries):
"""Fill in the binary matrix representing the boundaries of an object.
Parameters
----------
binary_boundaries : np.ndarray, np.uint or np.int or bool
Binary image with shape (y, x).
Returns
-------
binary_surface : np.ndarray, np.uint or np.int or bool
Binary image with shape (y, x).
"""
# TODO check dtype input & output
# check parameters
check_array(binary_boundaries,
ndim=2,
dtype=[np.uint8, np.uint16, np.int64, bool])
# from binary boundaries to binary surface
binary_surface = ndi.binary_fill_holes(binary_boundaries)
return binary_surface
def from_coord_to_surface(coord_cyt, coord_nuc=None, coord_rna=None):
"""Convert 2-d coordinates to a binary matrix with the surface of the
object.
As we manipulate the coordinates of the external boundaries, the relative
binary matrix has two extra pixels in each dimension. We compensate by
keeping only the inside pixels of the object surface.
If others coordinates are provided, the relative binary matrix is build
with the same shape as the main coordinates.
Parameters
----------
coord_cyt : np.ndarray, np.int64
Array of cytoplasm boundaries coordinates with shape (nb_points, 2).
coord_nuc : np.ndarray, np.int64
Array of nucleus boundaries coordinates with shape (nb_points, 2).
coord_rna : np.ndarray, np.int64
Array of mRNAs coordinates with shape (nb_points, 2) or
(nb_points, 3).
Returns
-------
cyt_surface : np.ndarray, np.uint or np.int or bool
Binary image of cytoplasm surface with shape (y, x).
nuc_surface : np.ndarray, np.uint or np.int or bool
Binary image of nucleus surface with shape (y, x).
rna : np.ndarray, np.uint or np.int or bool
Binary image of mRNAs localizations with shape (y, x).
"""
# check parameters
check_array(coord_cyt,
ndim=2,
dtype=[np.int64])
if coord_nuc is not None:
check_array(coord_nuc,
ndim=2,
dtype=[np.int64])
if coord_rna is not None:
check_array(coord_rna,
ndim=2,
dtype=[np.int64])
# from coordinates to binary boundaries
cyt, nuc, rna = _from_coord_to_boundaries(coord_cyt, coord_nuc, coord_rna)
# from binary boundaries to binary surface
cyt_surface = from_boundaries_to_surface(cyt)
nuc_surface = from_boundaries_to_surface(nuc)
return cyt_surface, nuc_surface, rna
| _extract_foci |
influxdb_test.py | """Tests for the ``/auth/tokens/influxdb`` route."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import ANY
import jwt
import pytest
from _pytest.logging import LogCaptureFixture
from httpx import AsyncClient
from gafaelfawr.config import Config
from gafaelfawr.factory import ComponentFactory
from ..support.constants import TEST_HOSTNAME
from ..support.headers import assert_unauthorized_is_correct
from ..support.logging import parse_log
from ..support.settings import configure
from ..support.tokens import create_session_token
@pytest.mark.asyncio
async def test_influxdb(
client: AsyncClient,
config: Config,
factory: ComponentFactory,
caplog: LogCaptureFixture,
) -> None:
token_data = await create_session_token(factory)
assert token_data.expires
influxdb_secret = config.issuer.influxdb_secret
assert influxdb_secret
caplog.clear()
r = await client.get(
"/auth/tokens/influxdb/new",
headers={"Authorization": f"bearer {token_data.token}"},
)
assert r.status_code == 200
data = r.json()
assert data == {"token": ANY}
influxdb_token = data["token"]
header = jwt.get_unverified_header(influxdb_token)
assert header == {"alg": "HS256", "typ": "JWT"}
claims = jwt.decode(influxdb_token, influxdb_secret, algorithms=["HS256"])
assert claims == {
"username": token_data.username,
"exp": int(token_data.expires.timestamp()),
"iat": ANY,
}
assert parse_log(caplog) == [
{
"event": "Issued InfluxDB token",
"influxdb_username": token_data.username,
"httpRequest": {
"requestMethod": "GET",
"requestUrl": (
f"https://{TEST_HOSTNAME}/auth/tokens/influxdb/new"
),
"remoteIp": "127.0.0.1",
},
"scope": "user:token",
"severity": "info",
"token": token_data.token.key,
"token_source": "bearer",
"user": token_data.username,
}
]
@pytest.mark.asyncio
async def test_no_auth(client: AsyncClient, config: Config) -> None:
r = await client.get("/auth/tokens/influxdb/new")
assert_unauthorized_is_correct(r, config)
@pytest.mark.asyncio
async def test_not_configured(
tmp_path: Path,
client: AsyncClient,
factory: ComponentFactory,
caplog: LogCaptureFixture,
) -> None:
config = await configure(tmp_path, "oidc")
factory.reconfigure(config)
token_data = await create_session_token(factory)
caplog.clear()
r = await client.get(
"/auth/tokens/influxdb/new",
headers={"Authorization": f"bearer {token_data.token}"},
)
assert r.status_code == 404
assert r.json()["detail"]["type"] == "not_supported"
assert parse_log(caplog) == [
{
"error": "No InfluxDB issuer configuration",
"event": "Not configured",
"httpRequest": {
"requestMethod": "GET",
"requestUrl": (
f"https://{TEST_HOSTNAME}/auth/tokens/influxdb/new"
),
"remoteIp": "127.0.0.1",
},
"scope": "user:token",
"severity": "warning",
"token": token_data.token.key,
"token_source": "bearer",
"user": token_data.username,
}
]
@pytest.mark.asyncio
async def | (
tmp_path: Path,
client: AsyncClient,
factory: ComponentFactory,
caplog: LogCaptureFixture,
) -> None:
config = await configure(tmp_path, "influxdb-username")
factory.reconfigure(config)
token_data = await create_session_token(factory)
assert token_data.expires
influxdb_secret = config.issuer.influxdb_secret
assert influxdb_secret
caplog.clear()
r = await client.get(
"/auth/tokens/influxdb/new",
headers={"Authorization": f"bearer {token_data.token}"},
)
assert r.status_code == 200
data = r.json()
claims = jwt.decode(data["token"], influxdb_secret, algorithms=["HS256"])
assert claims == {
"username": "influxdb-user",
"exp": int(token_data.expires.timestamp()),
"iat": ANY,
}
assert parse_log(caplog) == [
{
"event": "Issued InfluxDB token",
"influxdb_username": "influxdb-user",
"httpRequest": {
"requestMethod": "GET",
"requestUrl": (
f"https://{TEST_HOSTNAME}/auth/tokens/influxdb/new"
),
"remoteIp": "127.0.0.1",
},
"scope": "user:token",
"severity": "info",
"token": token_data.token.key,
"token_source": "bearer",
"user": token_data.username,
}
]
| test_influxdb_force_username |
es_utils.py | from elasticsearch import Elasticsearch # type: ignore
from elasticsearch.client import IndicesClient # type: ignore
from elasticsearch.helpers import bulk # type: ignore
import logging
from config import CONFIG_DICT
LOGGER = logging.getLogger(__name__)
ELASTICSEARCH_NODES = [CONFIG_DICT['ELASTICSEARCH_URI']]
elasticsearch_client = Elasticsearch(ELASTICSEARCH_NODES)
indices_client = IndicesClient(elasticsearch_client)
def ensure_mapping_exists(index_name, doc_type, mapping):
if index_name not in elasticsearch_client.indices.status()['indices']:
LOGGER.info(
"Index '{}' not found in elasticsearch. Creating...".format(index_name)
)
elasticsearch_client.index(index=index_name, doc_type=doc_type, body={})
else:
LOGGER.info("Index '{}' with doc type '{}' already exists".format(index_name, doc_type))
LOGGER.info("Ensuring mapping exists for index '{}', doc type '{}'".format(
index_name, doc_type
))
indices_client.put_mapping(
index=index_name, doc_type=doc_type, body=mapping,
)
def execute_elasticsearch_actions(actions):
return bulk(elasticsearch_client, actions)
def search(query_dict, index_name, doc_type):
result = elasticsearch_client.search(
index=index_name, doc_type=doc_type, body=query_dict
)
return result['hits']['hits']
def get_upsert_action(index_name, doc_type, document, id):
return {
'doc_as_upsert': True,
'_op_type': 'update',
'_index': index_name,
'_type': doc_type,
'_id': id,
'doc': document,
} | return {
'_op_type': 'delete',
'_index': index_name,
'_type': doc_type,
'_id': id,
}
def get_cluster_info():
return elasticsearch_client.info() |
def get_delete_action(index_name, doc_type, id): |
projects.js | import React from "react"
import styles from "./projects.module.css"
import Layout from "../components/layout"
import image1 from "../img/proj-css-colors.png"
import image2 from "../img/proj-figma-photo01.png"
import image3 from "../img/proj-superhero4hire-01-croplight.png"
import image4 from "../img/proj-laptopProject.jpg" |
/* const Project = props => (
<div className={styles.project}>
<img src={props.avatar} className={styles.avatar} alt="" />
<div className={styles.description}>
<h3 className={styles.projectname}>{props.projectname}</h3>
<p className={styles.excerpt}>{props.excerpt}</p>
</div>
</div>
) */
export default () => (
<Layout>
<br></br>
<h1>What I've Done</h1>
<h4>CSS Colors website - December 2018</h4>
<div>
<img
src={image1}
alt="xxx" />
<p>A school project I did with a study buddie within our studies at Nackademin</p>
<a href="#" target="_blank" class="visit-site-btn">View</a>
</div>
<h4>Photographer mockup - January 2019</h4>
<div>
<img
src={image2}
alt="xxx" />
<p>School project to make a full on working mockup of a website</p>
<a href="#" target="_blank" class="visit-site-btn">View</a>
</div>
<h4>Superhero 4 hire - February 2019</h4>
<div>
<img
src={image3}
alt="xxx" />
<p>School project made with three other study buddies at Nackademin</p>
<a href="#" target="_blank" class="visit-site-btn">View</a>
</div>
<h4>Superhero 4 hire - February 2019</h4>
<div>
<img
src={image4}
alt="xxx" />
<p>Coming soon...</p>
<a href="#" target="_blank" class="visit-site-btn">View</a>
</div>
<h4>Superhero 4 hire - February 2019</h4>
<div>
<img
src={image5}
alt="xxx" />
<p>Coming soon...</p>
<a href="#" target="_blank" class="visit-site-btn">View</a>
</div>
<h4>Superhero 4 hire - February 2019</h4>
<div>
<img
src={image6}
alt="xxx" />
<p>Coming soon...</p>
<a href="#" target="_blank" class="visit-site-btn">View</a>
</div>
</Layout>
)
{/* <img
src={image1}
alt="Group of pandas eating bamboo"
/> */}
{/* <Project
projectname="CSS Colors website - December 2018"
avatar="https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg"
excerpt="A school project I did with a study buddie within our studies at Nackademin"
/>
<Project
projectname="Photographer mockup - January 2019"
avatar="https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg"
excerpt="School project to make a full on working mockup of a website"
/>
<Project
projectname="Superhero 4 hire - February 2019"
avatar="https://s3.amazonaws.com/uifaces/faces/twitter/adellecharles/128.jpg"
excerpt="School project made with three other study buddies"
/>
<Project
projectname="Coming soon..."
avatar="https://s3.amazonaws.com/uifaces/faces/twitter/vladarbatov/128.jpg"
excerpt="2019 - More is coming..."
/> */} | import image5 from "../img/proj-bookshelf.jpg"
import image6 from "../img/projectDesk.jpg" |
user.js | const Discord = require("discord.js");
const { getReadableTime } = require("quick-ms");
// eslint-disable-next-line no-unused-vars
exports.execute = async (client, message, args) => {
let fullname = args.join(" ").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
let info;
if(args[0]) {
info = args[0].match(/^<@!?(\d+)>/)
|| message.guild.members.cache.find(m => m.user.username.match(new RegExp(fullname, "ui")))
|| message.guild.members.cache.find(m => m.id.match(new RegExp(fullname, "ui")))
|| message.guild.members.cache.find(m => { if (m.nickname) { return m.nickname.match(new RegExp(fullname, "ui")); } });
if (Array.isArray(info)) info = message.guild.members.cache.get(info[1]);
try {
if(!info) info = await client.users.fetch(fullname);
} catch(e) {}
if(!info) return message.channel.send("No user found.");
info = await client.users.cache.get(info.id) || await client.users.fetch(info.id);
} else {
info = message.author;
}
let member = message.guild.members.cache.get(info.id);
if(!member) {
let embed = new Discord.MessageEmbed()
.setTitle(info.tag + (info.flags && info.flags.has("SYSTEM") ? " :regional_indicator_s::regional_indicator_y::regional_indicator_s::regional_indicator_t::regional_indicator_e::regional_indicator_m:" : (info.bot ? " :regional_indicator_b::regional_indicator_o::regional_indicator_t:" : "")))
.setThumbnail(info.displayAvatarURL({dynamic: true}))
.setDescription("Ping: " + info.toString());
if(info.flags && info.flags.toArray().length) {
embed.addField("Badges", info.flags.toArray().map(v => v.toLowerCase().replace(/_/g, " ")).join(", ").replace(/\b(.)/g, c => c.toUpperCase()));
}
embed.addField("Id", info.id, true);
embed.addField("Bot Permission", client.perm({author: info}) + " | " + client.config.perms.find(p => p.level === client.perm({author: info})).name, true);
embed.addField("Created", client.formatDate(info.createdAt) + `\n(${getReadableTime(Date.now() - info.createdAt).split(", ").splice(0,3).join(", ")} ago)`);
embed.setFooter(`Requested by ${message.author.tag}`);
embed.setTimestamp();
return message.channel.send(embed);
}
let roles = "";
member.roles.cache.forEach(role => { if (role.name === "@everyone") return; roles += `<@&${role.id}> `; });
let status = ({
"online": ":green_circle:",
"idle": ":yellow_circle:",
"dnd": ":red_circle:",
"offline": ":black_circle:"
})[info.presence.status];
let boosting = (member.premiumSince ? `Since ${client.formatDate(member.premiumSince)}` : "Not boosting :(");
| presence += `__*${act.name}*__\n`
+ (act.details ? act.details + "\n" : "")
+ (act.state ? act.state + "\n" : "")
+ "\n";
});
presence = presence.substring(0, presence.length - 1);
}
let embed = new Discord.MessageEmbed()
.setTitle(info.tag + (info.flags && info.flags.has("SYSTEM") ?
" :regional_indicator_s::regional_indicator_y::regional_indicator_s::regional_indicator_t::regional_indicator_e::regional_indicator_m: "
: (info.bot ? " :regional_indicator_b::regional_indicator_o::regional_indicator_t: " : " "))
+ status
)
.setThumbnail(info.displayAvatarURL({dynamic: true}))
.setColor(member.displayHexColor)
.setDescription("Ping: " + info.toString() + "\n\n" + presence);
if(info.flags && info.flags.toArray().length) {
embed.addField("Badges", info.flags.toArray().map(v => v.toLowerCase().replace(/_/g, " ")).join(", ").replace(/\b(.)/g, c => c.toUpperCase()));
}
embed
.addField("Join Position", (message.guild.members.cache.array().sort((m, m2) => { return m.joinedTimestamp - m2.joinedTimestamp; }).map(m => m.id).indexOf(info.id) + 1) + "/" + message.guild.memberCount, true)
.addField("Boosting", boosting, true)
.addField("Id", info.id)
.addField("Created", client.formatDate(info.createdAt) + `\n(${getReadableTime(Date.now() - info.createdAt).split(", ").splice(0,3).join(", ")} ago)`, true)
.addField("Joined", client.formatDate(member.joinedAt) + `\n(${getReadableTime(Date.now() - member.joinedAt).split(", ").splice(0,3).join(", ")} ago)`, true)
.addField("Bot Permission", client.perm({guild: message.guild, author: info, member}) + " | " + client.config.perms.find(p => p.level === client.perm({guild: message.guild, author: info, member})).name)
.addField("Roles", roles)
.setFooter(`Requested by ${message.author.tag}`)
.setTimestamp();
message.channel.send(embed);
};
exports.data = {
permissions: 280576,
guildOnly: true,
aliases: ["info", "userinfo", "whois"],
name: "user",
desc: "Gives you info about a user.",
usage: "user [user]",
perm: 0
}; | let presence = "";
if(info.presence.activities.length != 0) {
presence = "**Statuses:**\n";
info.presence.activities.forEach(act => { |
manager_test.go | // Copyright 2022 Tigris Data, 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.
package transaction
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestManager(t *testing.T) {
t.Run("manager_creation", func(t *testing.T) {
m := NewManager(nil)
require.NotNil(t, m.tracker)
}) | t.Run("manager_get_tx", func(t *testing.T) {
m := NewManager(nil)
tx, err := m.GetTx(nil)
require.Nil(t, tx)
require.Equal(t, ErrTxCtxMissing, err)
})
} | |
18.js | (window.webpackJsonpLIB=window.webpackJsonpLIB||[]).push([[18],{412:function(e,o,t){"use strict";t.r(o),t.d(o,"Modals",(function(){return r})),t.d(o,"ModalAbort",(function(){return c}));var a=t(95),n=t(202),d=t(158),i=t(201),l=a.b`#background{
display: none;
}
#background[active]{
background: rgba(0, 0, 0, 0.75);
position: absolute;
z-index: 100;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
justify-content: center;
align-items: center;
}
#content{
width: 30em;
padding: 1em;
border: 1px solid #000;
background-color: #eee;
}
#yes{
float: right;
background-color: #5e5;
}
#no{
float: left;
background-color: #e55;
}
form{
padding: 1em 0;
}
.modal {
display: none;
}
.modal[active] {
display: block; | height:100%;
}`;let r;!function(e){e.GENERIC="generic"}(r||(r={}));class c extends Error{}class s extends n.a{static get styles(){return[i.a,l]}render(){var e;let o=null===(e=d.a.modal)||void 0===e?void 0:e.template;return a.c`
<div id="background" ?active="${null!==d.a.modal}">
<div id="content">
<modal-generic id="${r.GENERIC}" class="modal" ?active="${o===r.GENERIC}"></modal-generic>
</div>
</div>
`}updated(){if(d.a.modal){var e;const o=d.a.modal.template;(null===(e=this.shadowRoot)||void 0===e?void 0:e.getElementById(o)).data=d.a.modal.data}}firstUpdated(){window.onkeydown=e=>{const o=["Escape"];if(d.a.reportOpen||o.push("Enter"),d.a.modal&&o.includes(e.key)){var t;const o=d.a.modal.template,a=null===(t=this.shadowRoot)||void 0===t?void 0:t.getElementById(o);a&&a.onKeyDown&&a.onKeyDown(e.key),e.preventDefault()}}}}window.customElements.define("c4f-modal",s)}}]); | |
udp_network_amd64.go | //go:build !windows && !windows
// +build !windows,!windows
// Copyright 2015 flannel 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.
package udp
import (
"fmt"
"net"
"os"
"sync"
"syscall"
"github.com/flannel-io/flannel/backend"
"github.com/flannel-io/flannel/pkg/ip"
"github.com/flannel-io/flannel/subnet"
"github.com/vishvananda/netlink"
"golang.org/x/net/context"
log "k8s.io/klog"
)
const (
encapOverhead = 28 // 20 bytes IP hdr + 8 bytes UDP hdr
)
type network struct {
backend.SimpleNetwork
port int
ctl *os.File
ctl2 *os.File
tun *os.File
conn *net.UDPConn
tunNet ip.IP4Net
sm subnet.Manager
}
func newNetwork(sm subnet.Manager, extIface *backend.ExternalInterface, port int, nw ip.IP4Net, l *subnet.Lease) (*network, error) {
n := &network{
SimpleNetwork: backend.SimpleNetwork{
SubnetLease: l,
ExtIface: extIface,
},
port: port,
sm: sm,
}
n.tunNet = nw
if err := n.initTun(); err != nil {
return nil, err
}
var err error
n.conn, err = net.ListenUDP("udp4", &net.UDPAddr{IP: extIface.IfaceAddr, Port: port})
if err != nil {
return nil, fmt.Errorf("failed to start listening on UDP socket: %v", err)
}
n.ctl, n.ctl2, err = newCtlSockets()
if err != nil {
return nil, fmt.Errorf("failed to create control socket: %v", err)
}
return n, nil
}
func (n *network) Run(ctx context.Context) {
defer func() {
n.tun.Close()
n.conn.Close()
n.ctl.Close()
n.ctl2.Close()
}()
// one for each goroutine below
wg := sync.WaitGroup{}
defer wg.Wait()
wg.Add(1)
go func() {
runCProxy(n.tun, n.conn, n.ctl2, n.tunNet.IP, n.MTU())
wg.Done()
}()
log.Info("Watching for new subnet leases")
evts := make(chan []subnet.Event)
wg.Add(1)
go func() {
subnet.WatchLeases(ctx, n.sm, n.SubnetLease, evts)
wg.Done()
}()
for {
evtBatch, ok := <-evts
if !ok {
log.Infof("evts chan closed")
stopProxy(n.ctl)
return
}
n.processSubnetEvents(evtBatch)
}
}
func (n *network) MTU() int {
return n.ExtIface.Iface.MTU - encapOverhead
}
func newCtlSockets() (*os.File, *os.File, error) {
fds, err := syscall.Socketpair(syscall.AF_UNIX, syscall.SOCK_SEQPACKET, 0)
if err != nil {
return nil, nil, err
}
f1 := os.NewFile(uintptr(fds[0]), "ctl")
f2 := os.NewFile(uintptr(fds[1]), "ctl")
return f1, f2, nil
}
func (n *network) initTun() error {
var tunName string
var err error
n.tun, tunName, err = ip.OpenTun("flannel%d")
if err != nil {
return fmt.Errorf("failed to open TUN device: %v", err)
}
err = configureIface(tunName, n.tunNet, n.MTU())
return err
}
func | (ifname string, ipn ip.IP4Net, mtu int) error {
iface, err := netlink.LinkByName(ifname)
if err != nil {
return fmt.Errorf("failed to lookup interface %v", ifname)
}
// Ensure that the device has a /32 address so that no broadcast routes are created.
// This IP is just used as a source address for host to workload traffic (so
// the return path for the traffic has an address on the flannel network to use as the destination)
ipnLocal := ipn
ipnLocal.PrefixLen = 32
err = netlink.AddrAdd(iface, &netlink.Addr{IPNet: ipnLocal.ToIPNet(), Label: ""})
if err != nil {
return fmt.Errorf("failed to add IP address %v to %v: %v", ipnLocal.String(), ifname, err)
}
err = netlink.LinkSetMTU(iface, mtu)
if err != nil {
return fmt.Errorf("failed to set MTU for %v: %v", ifname, err)
}
err = netlink.LinkSetUp(iface)
if err != nil {
return fmt.Errorf("failed to set interface %v to UP state: %v", ifname, err)
}
// explicitly add a route since there might be a route for a subnet already
// installed by Docker and then it won't get auto added
err = netlink.RouteAdd(&netlink.Route{
LinkIndex: iface.Attrs().Index,
Scope: netlink.SCOPE_UNIVERSE,
Dst: ipn.Network().ToIPNet(),
})
if err != nil && err != syscall.EEXIST {
return fmt.Errorf("failed to add route (%v -> %v): %v", ipn.Network().String(), ifname, err)
}
return nil
}
func (n *network) processSubnetEvents(batch []subnet.Event) {
for _, evt := range batch {
switch evt.Type {
case subnet.EventAdded:
log.Info("Subnet added: ", evt.Lease.Subnet)
setRoute(n.ctl, evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, n.port)
case subnet.EventRemoved:
log.Info("Subnet removed: ", evt.Lease.Subnet)
removeRoute(n.ctl, evt.Lease.Subnet)
default:
log.Error("Internal error: unknown event type: ", int(evt.Type))
}
}
}
| configureIface |
store.rs | use graph_mock::MockMetricsRegistry;
use hex_literal::hex;
use lazy_static::lazy_static;
use std::str::FromStr;
use std::time::Duration;
use std::{collections::HashSet, sync::Mutex};
use test_store::*;
use graph::components::store::{
BlockStore as _, EntityFilter, EntityKey, EntityOrder, EntityQuery, EntityType, StatusStore,
SubscriptionManager as _,
};
use graph::data::store::scalar;
use graph::data::subgraph::schema::*;
use graph::data::subgraph::*;
use graph::prelude::*;
use graph_store_postgres::layout_for_tests::STRING_PREFIX_SIZE;
use graph_store_postgres::Store as DieselStore;
use web3::types::{Address, H256};
const USER_GQL: &str = "
interface ColorAndAge {
id: ID!,
age: Int,
favorite_color: String
}
type User implements ColorAndAge @entity {
id: ID!,
name: String,
bin_name: Bytes,
email: String,
age: Int,
seconds_age: BigInt,
weight: BigDecimal,
coffee: Boolean,
favorite_color: String
}
type Person implements ColorAndAge @entity {
id: ID!,
name: String,
age: Int,
favorite_color: String
}
type Manual @entity {
id: ID!,
text: String
}
";
const USER: &str = "User";
lazy_static! {
static ref TEST_SUBGRAPH_ID_STRING: String = String::from("testsubgraph");
static ref TEST_SUBGRAPH_ID: SubgraphDeploymentId =
SubgraphDeploymentId::new(TEST_SUBGRAPH_ID_STRING.as_str()).unwrap();
static ref TEST_SUBGRAPH_SCHEMA: Schema =
Schema::parse(USER_GQL, TEST_SUBGRAPH_ID.clone()).expect("Failed to parse user schema");
static ref TEST_BLOCK_0_PTR: EthereumBlockPointer = (
H256::from(hex!(
"bd34884280958002c51d3f7b5f853e6febeba33de0f40d15b0363006533c924f"
)),
0u64
)
.into();
static ref TEST_BLOCK_1_PTR: EthereumBlockPointer = (
H256::from(hex!(
"8511fa04b64657581e3f00e14543c1d522d5d7e771b54aa3060b662ade47da13"
)),
1u64
)
.into();
static ref TEST_BLOCK_2_PTR: EthereumBlockPointer = (
H256::from(hex!(
"b98fb783b49de5652097a989414c767824dff7e7fd765a63b493772511db81c1"
)),
2u64
)
.into();
static ref TEST_BLOCK_3_PTR: EthereumBlockPointer = (
H256::from(hex!(
"977c084229c72a0fa377cae304eda9099b6a2cb5d83b25cdf0f0969b69874255"
)),
3u64
)
.into();
static ref TEST_BLOCK_3A_PTR: EthereumBlockPointer = (
H256::from(hex!(
"d163aec0592c7cb00c2700ab65dcaac93289f5d250b3b889b39198b07e1fbe4a"
)),
3u64
)
.into();
static ref TEST_BLOCK_4_PTR: EthereumBlockPointer = (
H256::from(hex!(
"007a03cdf635ebb66f5e79ae66cc90ca23d98031665649db056ff9c6aac2d74d"
)),
4u64
)
.into();
static ref TEST_BLOCK_4A_PTR: EthereumBlockPointer = (
H256::from(hex!(
"8fab27e9e9285b0a39110f4d9877f05d0f43d2effa157e55f4dcc49c3cf8cbd7"
)),
4u64
)
.into();
static ref TEST_BLOCK_5_PTR: EthereumBlockPointer = (
H256::from(hex!(
"e8b3b02b936c4a4a331ac691ac9a86e197fb7731f14e3108602c87d4dac55160"
)),
5u64
)
.into();
}
/// Test harness for running database integration tests.
fn run_test<R, F>(test: F)
where
F: FnOnce(Arc<DieselStore>) -> R + Send + 'static,
R: std::future::Future<Output = ()> + Send + 'static,
{
run_test_sequentially(
|| (),
|store, ()| async move {
// Reset state before starting
remove_test_data(store.clone());
// Seed database with test data
insert_test_data(store.clone());
// Run test
test(store).await
},
);
}
/// Inserts test data into the store.
///
/// Inserts data in test blocks `GENESIS_PTR`, `TEST_BLOCK_1_PTR`, and
/// `TEST_BLOCK_2_PTR`
fn insert_test_data(store: Arc<DieselStore>) {
let manifest = SubgraphManifest {
id: TEST_SUBGRAPH_ID.clone(),
location: "/ipfs/test".to_owned(),
spec_version: "1".to_owned(),
features: Default::default(),
description: None,
repository: None,
schema: TEST_SUBGRAPH_SCHEMA.clone(),
data_sources: vec![],
graft: None,
templates: vec![],
};
// Create SubgraphDeploymentEntity
let deployment = SubgraphDeploymentEntity::new(&manifest, false, None);
let name = SubgraphName::new("test/store").unwrap();
let node_id = NodeId::new("test").unwrap();
store
.create_subgraph_deployment(
name,
&TEST_SUBGRAPH_SCHEMA,
deployment,
node_id,
NETWORK_NAME.to_string(),
SubgraphVersionSwitchingMode::Instant,
)
.unwrap();
let test_entity_1 = create_test_entity(
"1",
USER,
"Johnton",
"[email protected]",
67 as i32,
184.4,
false,
None,
);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*GENESIS_PTR,
vec![test_entity_1],
)
.unwrap();
let test_entity_2 = create_test_entity(
"2",
USER,
"Cindini",
"[email protected]",
43 as i32,
159.1,
true,
Some("red"),
);
let test_entity_3_1 = create_test_entity(
"3",
USER,
"Shaqueeena",
"[email protected]",
28 as i32,
111.7,
false,
Some("blue"),
);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_1_PTR,
vec![test_entity_2, test_entity_3_1],
)
.unwrap();
let test_entity_3_2 = create_test_entity(
"3",
USER,
"Shaqueeena",
"[email protected]",
28 as i32,
111.7,
false,
None,
);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_2_PTR,
vec![test_entity_3_2],
)
.unwrap();
}
/// Creates a test entity.
fn create_test_entity(
id: &str,
entity_type: &str,
name: &str,
email: &str,
age: i32,
weight: f64,
coffee: bool,
favorite_color: Option<&str>,
) -> EntityOperation {
let mut test_entity = Entity::new();
test_entity.insert("id".to_owned(), Value::String(id.to_owned()));
test_entity.insert("name".to_owned(), Value::String(name.to_owned()));
let bin_name = scalar::Bytes::from_str(&hex::encode(name)).unwrap();
test_entity.insert("bin_name".to_owned(), Value::Bytes(bin_name));
test_entity.insert("email".to_owned(), Value::String(email.to_owned()));
test_entity.insert("age".to_owned(), Value::Int(age));
test_entity.insert(
"seconds_age".to_owned(),
Value::BigInt(BigInt::from(age) * 31557600.into()),
);
test_entity.insert("weight".to_owned(), Value::BigDecimal(weight.into()));
test_entity.insert("coffee".to_owned(), Value::Bool(coffee));
test_entity.insert(
"favorite_color".to_owned(),
favorite_color
.map(|s| Value::String(s.to_owned()))
.unwrap_or(Value::Null),
);
EntityOperation::Set {
key: EntityKey::data(
TEST_SUBGRAPH_ID.clone(),
entity_type.to_owned(),
id.to_owned(),
),
data: test_entity,
}
}
/// Removes test data from the database behind the store.
fn remove_test_data(store: Arc<DieselStore>) {
store
.delete_all_entities_for_test_use_only()
.expect("deleting test entities succeeds");
}
fn get_entity_count(store: Arc<DieselStore>, subgraph_id: &SubgraphDeploymentId) -> u64 {
let info = store
.status(status::Filter::Deployments(vec![subgraph_id.to_string()]))
.unwrap();
let info = info.first().unwrap();
info.entity_count
}
#[test]
fn delete_entity() {
run_test(|store| async move {
let entity_key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "3".to_owned());
// Check that there is an entity to remove.
store.get(entity_key.clone()).unwrap().unwrap();
let count = get_entity_count(store.clone(), &TEST_SUBGRAPH_ID);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![EntityOperation::Remove {
key: entity_key.clone(),
}],
)
.unwrap();
assert_eq!(
count,
get_entity_count(store.clone(), &TEST_SUBGRAPH_ID) + 1
);
// Check that that the deleted entity id is not present
assert!(store.get(entity_key).unwrap().is_none());
})
}
/// Check that user 1 was inserted correctly
#[test]
fn get_entity_1() {
run_test(|store| async move {
let key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "1".to_owned());
let result = store.get(key).unwrap();
let mut expected_entity = Entity::new();
expected_entity.insert("__typename".to_owned(), USER.into());
expected_entity.insert("id".to_owned(), "1".into());
expected_entity.insert("name".to_owned(), "Johnton".into());
expected_entity.insert(
"bin_name".to_owned(),
Value::Bytes("Johnton".as_bytes().into()),
);
expected_entity.insert("email".to_owned(), "[email protected]".into());
expected_entity.insert("age".to_owned(), Value::Int(67 as i32));
expected_entity.insert(
"seconds_age".to_owned(),
Value::BigInt(BigInt::from(2114359200)),
);
expected_entity.insert("weight".to_owned(), Value::BigDecimal(184.4.into()));
expected_entity.insert("coffee".to_owned(), Value::Bool(false));
// "favorite_color" was set to `Null` earlier and should be absent
// Check that the expected entity was returned
assert_eq!(result, Some(expected_entity));
})
}
/// Check that user 3 was updated correctly
#[test]
fn get_entity_3() {
run_test(|store| async move {
let key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "3".to_owned());
let result = store.get(key).unwrap();
let mut expected_entity = Entity::new();
expected_entity.insert("__typename".to_owned(), USER.into());
expected_entity.insert("id".to_owned(), "3".into());
expected_entity.insert("name".to_owned(), "Shaqueeena".into());
expected_entity.insert(
"bin_name".to_owned(),
Value::Bytes("Shaqueeena".as_bytes().into()),
);
expected_entity.insert("email".to_owned(), "[email protected]".into());
expected_entity.insert("age".to_owned(), Value::Int(28 as i32));
expected_entity.insert(
"seconds_age".to_owned(),
Value::BigInt(BigInt::from(883612800)),
);
expected_entity.insert("weight".to_owned(), Value::BigDecimal(111.7.into()));
expected_entity.insert("coffee".to_owned(), Value::Bool(false));
// "favorite_color" was set to `Null` earlier and should be absent
// Check that the expected entity was returned
assert_eq!(result, Some(expected_entity));
})
}
#[test]
fn insert_entity() {
run_test(|store| async move {
let entity_key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "7".to_owned());
let test_entity = create_test_entity(
"7",
USER,
"Wanjon",
"[email protected]",
76 as i32,
111.7,
true,
Some("green"),
);
let count = get_entity_count(store.clone(), &TEST_SUBGRAPH_ID);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![test_entity],
)
.unwrap();
assert_eq!(
count + 1,
get_entity_count(store.clone(), &TEST_SUBGRAPH_ID)
);
// Check that new record is in the store
store.get(entity_key).unwrap().unwrap();
})
}
#[test]
fn update_existing() {
run_test(|store| async move {
let entity_key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "1".to_owned());
let op = create_test_entity(
"1",
USER,
"Wanjon",
"[email protected]",
76 as i32,
111.7,
true,
Some("green"),
);
let mut new_data = match op {
EntityOperation::Set { ref data, .. } => data.clone(),
_ => unreachable!(),
};
// Verify that the entity before updating is different from what we expect afterwards
assert_ne!(store.get(entity_key.clone()).unwrap().unwrap(), new_data);
// Set test entity; as the entity already exists an update should be performed
let count = get_entity_count(store.clone(), &TEST_SUBGRAPH_ID);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![op],
)
.unwrap();
assert_eq!(count, get_entity_count(store.clone(), &TEST_SUBGRAPH_ID));
// Verify that the entity in the store has changed to what we have set.
let bin_name = match new_data.get("bin_name") {
Some(Value::Bytes(bytes)) => bytes.clone(),
_ => unreachable!(),
};
new_data.insert("__typename".to_owned(), USER.into());
new_data.insert("bin_name".to_owned(), Value::Bytes(bin_name));
assert_eq!(store.get(entity_key).unwrap(), Some(new_data));
})
}
#[test]
fn partially_update_existing() {
run_test(|store| async move {
let entity_key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "1".to_owned());
let partial_entity = Entity::from(vec![
("id", Value::from("1")),
("name", Value::from("Johnny Boy")),
("email", Value::Null),
]);
let original_entity = store
.get(entity_key.clone())
.unwrap()
.expect("entity not found");
// Set test entity; as the entity already exists an update should be performed
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![EntityOperation::Set {
key: entity_key.clone(),
data: partial_entity.clone(),
}],
)
.unwrap();
// Obtain the updated entity from the store
let updated_entity = store.get(entity_key).unwrap().expect("entity not found");
// Verify that the values of all attributes we have set were either unset
// (in the case of Value::Null) or updated to the new values
assert_eq!(updated_entity.get("id"), partial_entity.get("id"));
assert_eq!(updated_entity.get(USER), partial_entity.get(USER));
assert_eq!(updated_entity.get("email"), None);
// Verify that all attributes we have not set have remained at their old values
assert_eq!(updated_entity.get("age"), original_entity.get("age"));
assert_eq!(updated_entity.get("weight"), original_entity.get("weight"));
assert_eq!(updated_entity.get("coffee"), original_entity.get("coffee"));
})
}
struct QueryChecker {
store: Arc<DieselStore>,
}
impl QueryChecker {
fn new(store: Arc<DieselStore>) -> Self {
Self { store }
}
fn check(self, expected_entity_ids: Vec<&str>, query: EntityQuery) -> Self {
let expected_entity_ids: Vec<String> =
expected_entity_ids.into_iter().map(str::to_owned).collect();
let entities = self
.store
.find(query)
.expect("store.find failed to execute query");
let entity_ids: Vec<_> = entities
.into_iter()
.map(|entity| match entity.get("id") {
Some(Value::String(id)) => id.to_owned(),
Some(_) => panic!("store.find returned entity with non-string ID attribute"),
None => panic!("store.find returned entity with no ID attribute"),
})
.collect();
assert_eq!(entity_ids, expected_entity_ids);
self
}
}
fn user_query() -> EntityQuery |
trait EasyOrder {
fn asc(self, attr: &str) -> Self;
fn desc(self, attr: &str) -> Self;
}
impl EasyOrder for EntityQuery {
fn asc(self, attr: &str) -> Self {
// The ValueType doesn't matter since relational layouts ignore it
self.order(EntityOrder::Ascending(attr.to_owned(), ValueType::String))
}
fn desc(self, attr: &str) -> Self {
// The ValueType doesn't matter since relational layouts ignore it
self.order(EntityOrder::Descending(attr.to_owned(), ValueType::String))
}
}
#[test]
fn find() {
run_test(|store| async move {
// Filter tests with string attributes
QueryChecker::new(store.clone())
.check(
vec!["2"],
user_query().filter(EntityFilter::Contains("name".into(), "ind".into())),
)
.check(
vec!["2"],
user_query().filter(EntityFilter::Equal("name".to_owned(), "Cindini".into())),
)
.check(
vec!["1", "3"],
user_query()
.filter(EntityFilter::Not("name".to_owned(), "Cindini".into()))
.asc("name"),
)
.check(
vec!["3"],
user_query().filter(EntityFilter::GreaterThan("name".to_owned(), "Kundi".into())),
)
.check(
vec!["2", "1"],
user_query()
.filter(EntityFilter::LessThan("name".to_owned(), "Kundi".into()))
.asc("name"),
)
.check(
vec!["1", "2"],
user_query()
.filter(EntityFilter::LessThan("name".to_owned(), "Kundi".into()))
.desc("name"),
)
.check(
vec!["1"],
user_query()
.filter(EntityFilter::LessThan("name".to_owned(), "ZZZ".into()))
.desc("name")
.first(1)
.skip(1),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::And(vec![
EntityFilter::LessThan("name".to_owned(), "Cz".into()),
EntityFilter::Equal("name".to_owned(), "Cindini".into()),
]))
.desc("name"),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::EndsWith("name".to_owned(), "ini".into()))
.desc("name"),
)
.check(
vec!["3", "1"],
user_query()
.filter(EntityFilter::NotEndsWith("name".to_owned(), "ini".into()))
.desc("name"),
)
.check(
vec!["1"],
user_query()
.filter(EntityFilter::In("name".to_owned(), vec!["Johnton".into()]))
.desc("name"),
)
.check(
vec!["1", "2"],
user_query()
.filter(EntityFilter::NotIn(
"name".to_owned(),
vec!["Shaqueeena".into()],
))
.desc("name"),
);
// Filter tests with float attributes
QueryChecker::new(store.clone())
.check(
vec!["1"],
user_query().filter(EntityFilter::Equal(
"weight".to_owned(),
Value::BigDecimal(184.4.into()),
)),
)
.check(
vec!["3", "2"],
user_query()
.filter(EntityFilter::Not(
"weight".to_owned(),
Value::BigDecimal(184.4.into()),
))
.desc("name"),
)
.check(
vec!["1"],
user_query().filter(EntityFilter::GreaterThan(
"weight".to_owned(),
Value::BigDecimal(160.0.into()),
)),
)
.check(
vec!["2", "3"],
user_query()
.filter(EntityFilter::LessThan(
"weight".to_owned(),
Value::BigDecimal(160.0.into()),
))
.asc("name"),
)
.check(
vec!["3", "2"],
user_query()
.filter(EntityFilter::LessThan(
"weight".to_owned(),
Value::BigDecimal(160.0.into()),
))
.desc("name"),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::LessThan(
"weight".to_owned(),
Value::BigDecimal(161.0.into()),
))
.desc("name")
.first(1)
.skip(1),
)
.check(
vec!["3", "1"],
user_query()
.filter(EntityFilter::In(
"weight".to_owned(),
vec![
Value::BigDecimal(184.4.into()),
Value::BigDecimal(111.7.into()),
],
))
.desc("name")
.first(5),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::NotIn(
"weight".to_owned(),
vec![
Value::BigDecimal(184.4.into()),
Value::BigDecimal(111.7.into()),
],
))
.desc("name")
.first(5),
);
// Filter tests with int attributes
QueryChecker::new(store.clone())
.check(
vec!["1"],
user_query()
.filter(EntityFilter::Equal("age".to_owned(), Value::Int(67 as i32)))
.desc("name"),
)
.check(
vec!["3", "2"],
user_query()
.filter(EntityFilter::Not("age".to_owned(), Value::Int(67 as i32)))
.desc("name"),
)
.check(
vec!["1"],
user_query().filter(EntityFilter::GreaterThan(
"age".to_owned(),
Value::Int(43 as i32),
)),
)
.check(
vec!["2", "1"],
user_query()
.filter(EntityFilter::GreaterOrEqual(
"age".to_owned(),
Value::Int(43 as i32),
))
.asc("name"),
)
.check(
vec!["2", "3"],
user_query()
.filter(EntityFilter::LessThan(
"age".to_owned(),
Value::Int(50 as i32),
))
.asc("name"),
)
.check(
vec!["2", "3"],
user_query()
.filter(EntityFilter::LessOrEqual(
"age".to_owned(),
Value::Int(43 as i32),
))
.asc("name"),
)
.check(
vec!["3", "2"],
user_query()
.filter(EntityFilter::LessThan(
"age".to_owned(),
Value::Int(50 as i32),
))
.desc("name"),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::LessThan(
"age".to_owned(),
Value::Int(67 as i32),
))
.desc("name")
.first(1)
.skip(1),
)
.check(
vec!["1", "2"],
user_query()
.filter(EntityFilter::In(
"age".to_owned(),
vec![Value::Int(67 as i32), Value::Int(43 as i32)],
))
.desc("name")
.first(5),
)
.check(
vec!["3"],
user_query()
.filter(EntityFilter::NotIn(
"age".to_owned(),
vec![Value::Int(67 as i32), Value::Int(43 as i32)],
))
.desc("name")
.first(5),
);
// Filter tests with bool attributes
QueryChecker::new(store.clone())
.check(
vec!["2"],
user_query()
.filter(EntityFilter::Equal("coffee".to_owned(), Value::Bool(true)))
.desc("name"),
)
.check(
vec!["1", "3"],
user_query()
.filter(EntityFilter::Not("coffee".to_owned(), Value::Bool(true)))
.asc("name"),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::In(
"coffee".to_owned(),
vec![Value::Bool(true)],
))
.desc("name")
.first(5),
)
.check(
vec!["3", "1"],
user_query()
.filter(EntityFilter::NotIn(
"coffee".to_owned(),
vec![Value::Bool(true)],
))
.desc("name")
.first(5),
);
// Misc filter tests
QueryChecker::new(store)
.check(
vec!["1"],
user_query()
.filter(EntityFilter::Equal(
"bin_name".to_owned(),
Value::Bytes("Johnton".as_bytes().into()),
))
.desc("name"),
)
.check(
vec!["3", "1"],
user_query()
.filter(EntityFilter::Equal(
"favorite_color".to_owned(),
Value::Null,
))
.desc("name"),
)
.check(
vec!["3", "1"],
user_query()
.filter(EntityFilter::Equal(
"favorite_color".to_owned(),
Value::Null,
))
.desc("name"),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::Not("favorite_color".to_owned(), Value::Null))
.desc("name"),
)
.check(
vec!["2"],
user_query()
.filter(EntityFilter::NotIn(
"favorite_color".to_owned(),
vec![Value::Null],
))
.desc("name"),
)
.check(vec!["3", "2", "1"], user_query().asc("weight"))
.check(vec!["1", "2", "3"], user_query().desc("weight"))
.check(vec!["1", "2", "3"], user_query().asc("id"))
.check(vec!["3", "2", "1"], user_query().desc("id"))
.check(vec!["3", "2", "1"], user_query().asc("age"))
.check(vec!["1", "2", "3"], user_query().desc("age"))
.check(vec!["2", "1", "3"], user_query().asc("name"))
.check(vec!["3", "1", "2"], user_query().desc("name"))
.check(
vec!["1", "2"],
user_query()
.filter(EntityFilter::And(vec![EntityFilter::Or(vec![
EntityFilter::Equal("id".to_owned(), Value::from("1")),
EntityFilter::Equal("id".to_owned(), Value::from("2")),
])]))
.asc("id"),
);
});
}
fn make_entity_change(
entity_type: &str,
entity_id: &str,
op: EntityChangeOperation,
) -> EntityChange {
EntityChange {
subgraph_id: TEST_SUBGRAPH_ID.clone(),
entity_type: EntityType::data(entity_type.to_owned()),
entity_id: entity_id.to_owned(),
operation: op,
}
}
// Get as events until we've seen all the expected events or we time out waiting
async fn check_events(
stream: StoreEventStream<impl Stream<Item = Arc<StoreEvent>, Error = ()> + Send>,
expected: Vec<StoreEvent>,
) {
fn as_set(events: Vec<Arc<StoreEvent>>) -> HashSet<EntityChange> {
events.into_iter().fold(HashSet::new(), |mut set, event| {
set.extend(event.changes.iter().map(|change| change.clone()));
set
})
}
let expected = Mutex::new(as_set(
expected.into_iter().map(|event| Arc::new(event)).collect(),
));
// Capture extra changes here; this is only needed for debugging, really.
// It's permissible that we get more changes than we expected because of
// how store events group changes together
let extra: Mutex<HashSet<EntityChange>> = Mutex::new(HashSet::new());
// Get events from the store until we've either seen all the changes we
// expected or we timed out waiting for them
stream
.take_while(|event| {
let mut expected = expected.lock().unwrap();
for change in &event.changes {
if !expected.remove(&change) {
extra.lock().unwrap().insert(change.clone());
}
}
future::ok(!expected.is_empty())
})
.collect()
.timeout(Duration::from_secs(3))
.await
.expect(&format!(
"timed out waiting for events\n still waiting for {:?}\n got extra events {:?}",
expected.lock().unwrap().clone(),
extra.lock().unwrap().clone()
))
.expect("something went wrong getting events");
// Check again that we really got everything
assert_eq!(HashSet::new(), expected.lock().unwrap().clone());
}
// Subscribe to store events
fn subscribe(
subgraph: &SubgraphDeploymentId,
entity_type: &str,
) -> StoreEventStream<impl Stream<Item = Arc<StoreEvent>, Error = ()> + Send> {
let subscription = SUBSCRIPTION_MANAGER.subscribe(vec![SubscriptionFilter::Entities(
subgraph.clone(),
EntityType::data(entity_type.to_owned()),
)]);
StoreEventStream::new(subscription)
}
async fn check_basic_revert(
store: Arc<DieselStore>,
expected: StoreEvent,
subgraph_id: &SubgraphDeploymentId,
entity_type: &str,
) {
let this_query = user_query()
.filter(EntityFilter::Equal(
"name".to_owned(),
Value::String("Shaqueeena".to_owned()),
))
.desc("name");
let subscription = subscribe(subgraph_id, entity_type);
let state = store
.deployment_state_from_id(subgraph_id.to_owned())
.expect("can get deployment state");
assert_eq!(subgraph_id, &state.id);
// Revert block 3
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_1_PTR)
.unwrap();
let returned_entities = store
.find(this_query.clone())
.expect("store.find operation failed");
// There should be 1 user returned in results
assert_eq!(1, returned_entities.len());
// Check if the first user in the result vector has email "[email protected]"
let returned_name = returned_entities[0].get(&"email".to_owned());
let test_value = Value::String("[email protected]".to_owned());
assert!(returned_name.is_some());
assert_eq!(&test_value, returned_name.unwrap());
let state = store
.deployment_state_from_id(subgraph_id.to_owned())
.expect("can get deployment state");
assert_eq!(subgraph_id, &state.id);
check_events(subscription, vec![expected]).await
}
#[test]
fn revert_block_basic_user() {
run_test(|store| async move {
let expected = StoreEvent::new(vec![make_entity_change(
USER,
"3",
EntityChangeOperation::Set,
)]);
let count = get_entity_count(store.clone(), &TEST_SUBGRAPH_ID);
check_basic_revert(store.clone(), expected, &TEST_SUBGRAPH_ID, USER).await;
assert_eq!(count, get_entity_count(store.clone(), &TEST_SUBGRAPH_ID));
})
}
#[test]
fn revert_block_with_delete() {
run_test(|store| async move {
let this_query = user_query()
.filter(EntityFilter::Equal(
"name".to_owned(),
Value::String("Cindini".to_owned()),
))
.desc("name");
// Delete entity with id=2
let del_key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "2".to_owned());
// Process deletion
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![EntityOperation::Remove { key: del_key }],
)
.unwrap();
let subscription = subscribe(&TEST_SUBGRAPH_ID, USER);
// Revert deletion
let count = get_entity_count(store.clone(), &TEST_SUBGRAPH_ID);
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_2_PTR)
.unwrap();
assert_eq!(
count + 1,
get_entity_count(store.clone(), &TEST_SUBGRAPH_ID)
);
// Query after revert
let returned_entities = store
.find(this_query.clone())
.expect("store.find operation failed");
// There should be 1 entity returned in results
assert_eq!(1, returned_entities.len());
// Check if "[email protected]" is in result set
let returned_name = returned_entities[0].get(&"email".to_owned());
let test_value = Value::String("[email protected]".to_owned());
assert!(returned_name.is_some());
assert_eq!(&test_value, returned_name.unwrap());
// Check that the subscription notified us of the changes
let expected = StoreEvent::new(vec![make_entity_change(
USER,
"2",
EntityChangeOperation::Set,
)]);
// The last event is the one for the reversion
check_events(subscription, vec![expected]).await
})
}
#[test]
fn revert_block_with_partial_update() {
run_test(|store| async move {
let entity_key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "1".to_owned());
let partial_entity = Entity::from(vec![
("id", Value::from("1")),
("name", Value::from("Johnny Boy")),
("email", Value::Null),
]);
let original_entity = store
.get(entity_key.clone())
.unwrap()
.expect("missing entity");
// Set test entity; as the entity already exists an update should be performed
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![EntityOperation::Set {
key: entity_key.clone(),
data: partial_entity.clone(),
}],
)
.unwrap();
let subscription = subscribe(&TEST_SUBGRAPH_ID, USER);
// Perform revert operation, reversing the partial update
let count = get_entity_count(store.clone(), &TEST_SUBGRAPH_ID);
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_2_PTR)
.unwrap();
assert_eq!(count, get_entity_count(store.clone(), &TEST_SUBGRAPH_ID));
// Obtain the reverted entity from the store
let reverted_entity = store
.get(entity_key.clone())
.unwrap()
.expect("missing entity");
// Verify that the entity has been returned to its original state
assert_eq!(reverted_entity, original_entity);
// Check that the subscription notified us of the changes
let expected = StoreEvent::new(vec![make_entity_change(
USER,
"1",
EntityChangeOperation::Set,
)]);
check_events(subscription, vec![expected]).await
})
}
fn mock_data_source() -> DataSource {
DataSource {
kind: String::from("ethereum/contract"),
name: String::from("example data source"),
network: Some(String::from("mainnet")),
source: Source {
address: Some(Address::from_str("0123123123012312312301231231230123123123").unwrap()),
abi: String::from("123123"),
start_block: 0,
},
mapping: Mapping {
kind: String::from("ethereum/events"),
api_version: String::from("0.1.0"),
language: String::from("wasm/assemblyscript"),
entities: vec![],
abis: vec![],
event_handlers: vec![],
call_handlers: vec![],
block_handlers: vec![],
link: Link {
link: "link".to_owned(),
},
runtime: Arc::new(Vec::new()),
},
context: None,
creation_block: None,
}
}
#[test]
fn revert_block_with_dynamic_data_source_operations() {
run_test(|store| async move {
// Create operations to add a user
let user_key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), "1".to_owned());
let partial_entity = Entity::from(vec![
("id", Value::from("1")),
("name", Value::from("Johnny Boy")),
("email", Value::Null),
]);
// Get the original user for comparisons
let original_user = store
.get(user_key.clone())
.unwrap()
.expect("missing entity");
// Create operations to add a dynamic data source
let data_source = mock_data_source();
let dynamic_ds = DynamicEthereumContractDataSourceEntity::from((
&TEST_SUBGRAPH_ID.clone(),
&data_source,
&TEST_BLOCK_4_PTR.clone(),
));
let mut ops = vec![EntityOperation::Set {
key: user_key.clone(),
data: partial_entity.clone(),
}];
ops.extend(dynamic_ds.write_entity_operations(&*TEST_SUBGRAPH_ID, "dynamic-data-source"));
// Add user and dynamic data source to the store
transact_entity_operations(&store, TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_3_PTR, ops)
.unwrap();
// Verify that the user is no longer the original
assert_ne!(
store
.get(user_key.clone())
.unwrap()
.expect("missing entity"),
original_user
);
// Verify that the dynamic data source exists afterwards
let dynamic_ds_key = EntityKey::metadata(
TEST_SUBGRAPH_ID.clone(),
MetadataType::DynamicEthereumContractDataSource,
String::from("dynamic-data-source"),
);
store
.get(dynamic_ds_key.clone())
.unwrap()
.expect("dynamic data source entity wasn't written to store");
let subscription = subscribe(&TEST_SUBGRAPH_ID, USER);
// Revert block that added the user and the dynamic data source
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_2_PTR)
.expect("revert block operations failed unexpectedly");
// Verify that the user is the original again
assert_eq!(
store
.get(user_key.clone())
.unwrap()
.expect("missing entity"),
original_user
);
// Verify that the dynamic data source is gone after the reversion
assert!(store.get(dynamic_ds_key.clone()).unwrap().is_none());
// Verify that the right change events were emitted for the reversion
let expected_events = vec![StoreEvent {
tag: 3,
changes: HashSet::from_iter(
vec![EntityChange {
subgraph_id: SubgraphDeploymentId::new("testsubgraph").unwrap(),
entity_type: EntityType::data(USER.into()),
entity_id: "1".into(),
operation: EntityChangeOperation::Set,
}]
.into_iter(),
),
}];
check_events(subscription, expected_events).await
})
}
#[test]
fn entity_changes_are_fired_and_forwarded_to_subscriptions() {
run_test(|store| async move {
let subgraph_id = SubgraphDeploymentId::new("EntityChangeTestSubgraph").unwrap();
let schema =
Schema::parse(USER_GQL, subgraph_id.clone()).expect("Failed to parse user schema");
let manifest = SubgraphManifest {
id: subgraph_id.clone(),
location: "/ipfs/test".to_owned(),
spec_version: "1".to_owned(),
features: Default::default(),
description: None,
repository: None,
schema: schema.clone(),
data_sources: vec![],
graft: None,
templates: vec![],
};
// Create SubgraphDeploymentEntity
let deployment = SubgraphDeploymentEntity::new(&manifest, false, Some(*TEST_BLOCK_0_PTR));
let name = SubgraphName::new("test/entity-changes-are-fired").unwrap();
let node_id = NodeId::new("test").unwrap();
store
.create_subgraph_deployment(
name,
&schema,
deployment,
node_id,
NETWORK_NAME.to_string(),
SubgraphVersionSwitchingMode::Instant,
)
.unwrap();
let subscription = subscribe(&subgraph_id, USER);
// Add two entities to the store
let added_entities = vec![
(
"1".to_owned(),
Entity::from(vec![
("id", Value::from("1")),
("name", Value::from("Johnny Boy")),
]),
),
(
"2".to_owned(),
Entity::from(vec![
("id", Value::from("2")),
("name", Value::from("Tessa")),
]),
),
];
transact_entity_operations(
&store,
subgraph_id.clone(),
*TEST_BLOCK_1_PTR,
added_entities
.iter()
.map(|(id, data)| EntityOperation::Set {
key: EntityKey::data(subgraph_id.clone(), USER.to_owned(), id.to_owned()),
data: data.to_owned(),
})
.collect(),
)
.unwrap();
// Update an entity in the store
let updated_entity = Entity::from(vec![
("id", Value::from("1")),
("name", Value::from("Johnny")),
]);
let update_op = EntityOperation::Set {
key: EntityKey::data(subgraph_id.clone(), USER.to_owned(), "1".to_owned()),
data: updated_entity.clone(),
};
// Delete an entity in the store
let delete_op = EntityOperation::Remove {
key: EntityKey::data(subgraph_id.clone(), USER.to_owned(), "2".to_owned()),
};
// Commit update & delete ops
transact_entity_operations(
&store,
subgraph_id.clone(),
*TEST_BLOCK_2_PTR,
vec![update_op, delete_op],
)
.unwrap();
// We're expecting two events to be written to the subscription stream
let user_type = EntityType::data(USER.to_owned());
let expected = vec![
StoreEvent::new(vec![
EntityChange {
subgraph_id: subgraph_id.clone(),
entity_type: user_type.clone(),
entity_id: added_entities[0].clone().0,
operation: EntityChangeOperation::Set,
},
EntityChange {
subgraph_id: subgraph_id.clone(),
entity_type: user_type.clone(),
entity_id: added_entities[1].clone().0,
operation: EntityChangeOperation::Set,
},
]),
StoreEvent::new(vec![
EntityChange {
subgraph_id: subgraph_id.clone(),
entity_type: user_type.clone(),
entity_id: "1".to_owned(),
operation: EntityChangeOperation::Set,
},
EntityChange {
subgraph_id: subgraph_id.clone(),
entity_type: user_type.clone(),
entity_id: added_entities[1].clone().0,
operation: EntityChangeOperation::Removed,
},
]),
];
check_events(subscription, expected).await
})
}
#[test]
fn throttle_subscription_delivers() {
run_test(|store| async move {
let subscription = subscribe(&TEST_SUBGRAPH_ID, USER).throttle_while_syncing(
&*LOGGER,
store
.clone()
.query_store(TEST_SUBGRAPH_ID.clone().into(), true)
.unwrap(),
TEST_SUBGRAPH_ID.clone(),
Duration::from_millis(500),
);
let user4 = create_test_entity(
"4",
USER,
"Steve",
"[email protected]",
72 as i32,
120.7,
false,
None,
);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![user4],
)
.unwrap();
let expected = StoreEvent::new(vec![make_entity_change(
USER,
"4",
EntityChangeOperation::Set,
)]);
check_events(subscription, vec![expected]).await
})
}
#[test]
fn throttle_subscription_throttles() {
run_test(|store| async move {
// Throttle for a very long time (30s)
let subscription = subscribe(&TEST_SUBGRAPH_ID, USER).throttle_while_syncing(
&*LOGGER,
store
.clone()
.query_store(TEST_SUBGRAPH_ID.clone().into(), true)
.unwrap(),
TEST_SUBGRAPH_ID.clone(),
Duration::from_secs(30),
);
let user4 = create_test_entity(
"4",
USER,
"Steve",
"[email protected]",
72 as i32,
120.7,
false,
None,
);
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![user4],
)
.unwrap();
// Make sure we time out waiting for the subscription
let res = subscription
.take(1)
.collect()
.timeout(Duration::from_millis(500))
.await;
assert!(res.is_err());
})
}
#[test]
fn subgraph_schema_types_have_subgraph_id_directive() {
run_test(|store| async move {
let schema = store
.api_schema(&TEST_SUBGRAPH_ID)
.expect("test subgraph should have a schema");
for typedef in schema
.document()
.definitions
.iter()
.filter_map(|def| match def {
s::Definition::TypeDefinition(typedef) => Some(typedef),
_ => None,
})
{
// Verify that all types have a @subgraphId directive on them
let directive = match typedef {
s::TypeDefinition::Object(t) => &t.directives,
s::TypeDefinition::Interface(t) => &t.directives,
s::TypeDefinition::Enum(t) => &t.directives,
s::TypeDefinition::Scalar(t) => &t.directives,
s::TypeDefinition::Union(t) => &t.directives,
s::TypeDefinition::InputObject(t) => &t.directives,
}
.iter()
.find(|directive| directive.name == "subgraphId")
.expect("all subgraph schema types should have a @subgraphId directive");
// Verify that all @subgraphId directives match the subgraph
assert_eq!(
directive.arguments,
[(
String::from("id"),
s::Value::String(TEST_SUBGRAPH_ID_STRING.to_string())
)]
);
}
})
}
#[test]
fn handle_large_string_with_index() {
const NAME: &str = "name";
const ONE: &str = "large_string_one";
const TWO: &str = "large_string_two";
fn make_insert_op(id: &str, name: &str) -> EntityModification {
let mut data = Entity::new();
data.set("id", id);
data.set(NAME, name);
let key = EntityKey::data(TEST_SUBGRAPH_ID.clone(), USER.to_owned(), id.to_owned());
EntityModification::Insert { key, data }
};
run_test(|store| async move {
// We have to produce a massive string (1_000_000 chars) because
// the repeated text compresses so well. This leads to an error
// 'index row requires 11488 bytes, maximum size is 8191' if
// used with a btree index without size limitation
let long_text = std::iter::repeat("Quo usque tandem")
.take(62500)
.collect::<String>();
let other_text = long_text.clone() + "X";
let metrics_registry = Arc::new(MockMetricsRegistry::new());
let stopwatch_metrics = StopwatchMetrics::new(
Logger::root(slog::Discard, o!()),
TEST_SUBGRAPH_ID.clone(),
metrics_registry.clone(),
);
store
.transact_block_operations(
TEST_SUBGRAPH_ID.clone(),
*TEST_BLOCK_3_PTR,
vec![
make_insert_op(ONE, &long_text),
make_insert_op(TWO, &other_text),
],
stopwatch_metrics,
Vec::new(),
)
.expect("Failed to insert large text");
let query = user_query()
.first(5)
.filter(EntityFilter::Equal(
NAME.to_owned(),
long_text.clone().into(),
))
.asc(NAME);
let ids = store
.find(query)
.expect("Could not find entity")
.iter()
.map(|e| e.id())
.collect::<Result<Vec<_>, _>>()
.expect("Found entities without an id");
assert_eq!(vec![ONE], ids);
// Make sure we check the full string and not just a prefix
let mut prefix = long_text.clone();
prefix.truncate(STRING_PREFIX_SIZE);
let query = user_query()
.first(5)
.filter(EntityFilter::LessOrEqual(NAME.to_owned(), prefix.into()))
.asc(NAME);
let ids = store
.find(query)
.expect("Could not find entity")
.iter()
.map(|e| e.id())
.collect::<Result<Vec<_>, _>>()
.expect("Found entities without an id");
// Users with name 'Cindini' and 'Johnton'
assert_eq!(vec!["2", "1"], ids);
})
}
#[derive(Clone)]
struct WindowQuery(EntityQuery, Arc<DieselStore>);
impl WindowQuery {
fn new(store: &Arc<DieselStore>) -> Self {
WindowQuery(
user_query()
.filter(EntityFilter::GreaterThan("age".into(), Value::from(0)))
.first(10),
store.clone(),
)
.default_window()
}
fn default_window(mut self) -> Self {
let entity_types = match self.0.collection {
EntityCollection::All(entity_types) => entity_types,
EntityCollection::Window(_) => {
unreachable!("we do not use this method with a windowed collection")
}
};
let windows = entity_types
.into_iter()
.map(|child_type| {
let attribute = WindowAttribute::Scalar("favorite_color".to_owned());
let link = EntityLink::Direct(attribute, ChildMultiplicity::Many);
let ids = vec!["red", "green", "yellow", "blue"]
.into_iter()
.map(String::from)
.collect();
EntityWindow {
child_type,
link,
ids,
}
})
.collect();
self.0.collection = EntityCollection::Window(windows);
self
}
fn first(self, first: u32) -> Self {
WindowQuery(self.0.first(first), self.1)
}
fn skip(self, skip: u32) -> Self {
WindowQuery(self.0.skip(skip), self.1)
}
fn asc(self, attr: &str) -> Self {
WindowQuery(
self.0
.order(EntityOrder::Ascending(attr.to_owned(), ValueType::String)),
self.1,
)
}
fn desc(self, attr: &str) -> Self {
WindowQuery(
self.0
.order(EntityOrder::Descending(attr.to_owned(), ValueType::String)),
self.1,
)
}
fn unordered(self) -> Self {
WindowQuery(self.0.order(EntityOrder::Unordered), self.1)
}
fn above(self, age: i32) -> Self {
WindowQuery(
self.0
.filter(EntityFilter::GreaterThan("age".into(), Value::from(age))),
self.1,
)
}
fn against_color_and_age(self) -> Self {
let mut query = self.0;
query.collection = EntityCollection::All(vec![USER.to_owned(), "Person".to_owned()]);
WindowQuery(query, self.1).default_window()
}
fn expect(&self, mut expected_ids: Vec<&str>, qid: &str) {
let query = self.0.clone();
let store = &self.1;
let unordered = matches!(query.order, EntityOrder::Unordered);
let mut entity_ids = store
.find(query)
.expect("store.find failed to execute query")
.into_iter()
.map(|entity| match entity.get("id") {
Some(Value::String(id)) => id.to_owned(),
Some(_) => panic!("store.find returned entity with non-string ID attribute"),
None => panic!("store.find returned entity with no ID attribute"),
})
.collect::<Vec<_>>();
if unordered {
entity_ids.sort();
expected_ids.sort();
}
assert_eq!(expected_ids, entity_ids, "Failed query: {}", qid);
}
}
#[test]
fn window() {
fn make_color_end_age(entity_type: &str, id: &str, color: &str, age: i32) -> EntityOperation {
let mut entity = Entity::new();
entity.set("id", id.to_owned());
entity.set("age", age);
entity.set("favorite_color", color);
EntityOperation::Set {
key: EntityKey::data(
TEST_SUBGRAPH_ID.clone(),
entity_type.to_owned(),
id.to_owned(),
),
data: entity,
}
}
fn make_user(id: &str, color: &str, age: i32) -> EntityOperation {
make_color_end_age(USER, id, color, age)
}
fn make_person(id: &str, color: &str, age: i32) -> EntityOperation {
make_color_end_age("Person", id, color, age)
}
let ops = vec![
make_user("4", "green", 34),
make_user("5", "green", 17),
make_user("6", "green", 41),
make_user("7", "red", 25),
make_user("8", "red", 45),
make_user("9", "yellow", 37),
make_user("10", "blue", 27),
make_user("11", "blue", 19),
make_person("p1", "green", 12),
make_person("p2", "red", 15),
];
run_test(|store| async move {
transact_entity_operations(&store, TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_3_PTR, ops)
.expect("Failed to create test users");
// Get the first 2 entries in each 'color group'
WindowQuery::new(&store)
.first(2)
.expect(vec!["10", "11", "4", "5", "2", "7", "9"], "q1");
WindowQuery::new(&store)
.first(1)
.expect(vec!["10", "4", "2", "9"], "q2");
WindowQuery::new(&store)
.first(1)
.skip(1)
.expect(vec!["11", "5", "7"], "q3");
WindowQuery::new(&store)
.first(1)
.skip(1)
.desc("id")
.expect(vec!["10", "5", "7"], "q4");
WindowQuery::new(&store)
.first(1)
.skip(1)
.desc("favorite_color")
.expect(vec!["11", "5", "7"], "q5");
WindowQuery::new(&store)
.first(1)
.skip(1)
.desc("favorite_color")
.above(25)
.expect(vec!["6", "8"], "q6");
// Check queries for interfaces
WindowQuery::new(&store)
.first(1)
.skip(1)
.desc("favorite_color")
.above(12)
.against_color_and_age()
.expect(vec!["11", "5", "7"], "q7");
WindowQuery::new(&store)
.first(1)
.asc("age")
.above(12)
.against_color_and_age()
.expect(vec!["11", "5", "p2", "9"], "q8");
WindowQuery::new(&store)
.unordered()
.above(12)
.against_color_and_age()
.expect(
vec!["10", "11", "2", "4", "5", "6", "7", "8", "9", "p2"],
"q9",
);
});
}
#[test]
fn find_at_block() {
fn shaqueeena_at_block(block: BlockNumber, email: &'static str) {
run_test(move |store| async move {
let mut query = user_query()
.filter(EntityFilter::Equal("name".to_owned(), "Shaqueeena".into()))
.desc("name");
query.block = block;
let entities = store
.find(query)
.expect("store.find failed to execute query");
assert_eq!(1, entities.len());
let entity = entities.first().unwrap();
assert_eq!(Some(&Value::from(email)), entity.get("email"));
})
}
shaqueeena_at_block(1, "[email protected]");
shaqueeena_at_block(2, "[email protected]");
shaqueeena_at_block(7000, "[email protected]");
}
#[test]
fn cleanup_cached_blocks() {
run_test(|store| async move {
// This test is somewhat silly in that there is nothing to clean up.
// The main purpose for this test is to ensure that the SQL query
// we run in `cleanup_cached_blocks` to figure out the first block
// that should be removed is syntactically correct
let chain_store = store
.block_store()
.chain_store(NETWORK_NAME)
.expect("fake chain store");
let cleaned = chain_store
.cleanup_cached_blocks(10)
.expect("cleanup succeeds");
assert_eq!((0, 0), cleaned);
})
}
#[test]
fn reorg_tracking() {
fn update_john(store: &Arc<DieselStore>, age: i32, block: &EthereumBlockPointer) {
let test_entity_1 = create_test_entity(
"1",
USER,
"Johnton",
"[email protected]",
age,
184.4,
false,
None,
);
transact_entity_operations(
store,
TEST_SUBGRAPH_ID.clone(),
block.clone(),
vec![test_entity_1],
)
.unwrap();
}
macro_rules! check_state {
($store:expr,
$reorg_count: expr,
$max_reorg_depth:expr,
$latest_ethereum_block_number:expr) => {
let subgraph_id = TEST_SUBGRAPH_ID.to_owned();
let state = &$store
.deployment_state_from_id(subgraph_id.clone())
.expect("can get deployment state");
assert_eq!(&subgraph_id, &state.id, "subgraph_id");
assert_eq!($reorg_count, state.reorg_count, "reorg_count");
assert_eq!($max_reorg_depth, state.max_reorg_depth, "max_reorg_depth");
assert_eq!(
$latest_ethereum_block_number, state.latest_ethereum_block_number,
"latest_ethereum_block_number"
);
};
}
// Check that reorg_count, max_reorg_depth, and latest_ethereum_block_number
// are reported correctly in DeploymentState
run_test(|store| async move {
check_state!(store, 0, 0, 2);
// Jump to block 4
transact_entity_operations(
&store,
TEST_SUBGRAPH_ID.clone(),
TEST_BLOCK_4_PTR.clone(),
vec![],
)
.unwrap();
check_state!(store, 0, 0, 4);
// Back to block 3
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_3_PTR)
.unwrap();
check_state!(store, 1, 1, 3);
// Back to block 2
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_2_PTR)
.unwrap();
check_state!(store, 2, 2, 2);
// Forward to block 3
update_john(&store, 70, &TEST_BLOCK_3_PTR);
check_state!(store, 2, 2, 3);
// Forward to block 4
update_john(&store, 71, &TEST_BLOCK_4_PTR);
check_state!(store, 2, 2, 4);
// Forward to block 5
update_john(&store, 72, &TEST_BLOCK_5_PTR);
check_state!(store, 2, 2, 5);
// Revert all the way back to block 2
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_4_PTR)
.unwrap();
check_state!(store, 3, 2, 4);
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_3_PTR)
.unwrap();
check_state!(store, 4, 2, 3);
store
.revert_block_operations(TEST_SUBGRAPH_ID.clone(), *TEST_BLOCK_2_PTR)
.unwrap();
check_state!(store, 5, 3, 2);
})
}
| {
EntityQuery::new(
TEST_SUBGRAPH_ID.clone(),
BLOCK_NUMBER_MAX,
EntityCollection::All(vec![USER.to_owned()]),
)
} |
push.js | console.log('[Application] Start push listening');
const messaging = firebase.messaging();
messaging.requestPermission().then(function () {
console.log('Permission granted');
return messaging.getToken().then(function (currentToken) {
if (currentToken) {
console.log(currentToken);
return currentToken;
} else {
console.warn('Nenhum id disponível, Solicite permissão para gerar um');
}
});
});
messaging.getToken()
.then(function () {
if (currentToken) { | }
})
.catch(function (error) {
console.warn('Get token err: ', error);
}); | console.log(currentToken);
return currentToken;
} else {
console.warn('Nenhum id disponível, Solicite permissão para gerar um'); |
lrucache.py | """
146. LRU Cache
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if
the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already present.
When the cache reached its capacity, it should invalidate the least recently
used item before inserting a new item.
The cache is initialized with a positive capacity.
Follow up:
Could you do both operations in O(1) time complexity?
"""
# Node for doubly linked list
class DoubleNode:
def __init__(self, key, value):
|
class LRUCache:
# Assign to the cache two nodes for head and tail and a dict
def __init__(self, capacity):
self.dict = {}
self.capacity = capacity
self.head = DoubleNode(0,0)
self.tail = DoubleNode(0,0)
self.head.next = self.tail
self.tail.prev = self.head
# When accessing something in cache, remove (if exists)
# and add to right before the tail
def get(self, key):
if key in self.dict:
tnode = self.dict[key]
self._remove(tnode)
self._add(tnode)
return tnode.value
else:
return -1
# When putting something in cache, check for capacity
# and then attach to just before the tail
def put(self, key, value):
if key in self.dict:
self._remove(self.dict[key])
del self.dict[key]
if len(self.dict) == self.capacity:
lru = self.head.next
self._remove(lru)
del self.dict[lru.key]
newnode = DoubleNode(key, value)
self.dict[key] = newnode
self._add(newnode)
# Add to cache helper function: always adds to just before the tail
def _add(self, node):
p = self.tail.prev
p.next = node
node.prev = p
node.next = self.tail
self.tail.prev = node
# Remove node helper: set the previous's next to next
# and next's previous to previous
def _remove(self, node):
node.prev.next = node.next
node.next.prev = node.prev
# Runtime: 224 ms, faster than 44.14% of Python3 online submissions for LRU Cache.
# Memory Usage: 22.4 MB, less than 6.06% of Python3 online submissions for LRU Cache.
if __name__ == '__main__':
cache = LRUCache(2)
cache.put(1,1)
cache.put(2,2)
print(cache.get(1))
cache.put(3,3)
print(cache.get(2))
cache.put(4,4)
print(cache.get(1))
print(cache.get(3))
print(cache.get(4)) | self.prev = None
self.next = None
self.key = key
self.value = value |
main.ts | import { ValidationPipe } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import {
DocumentBuilder,
ExpressSwaggerCustomOptions,
SwaggerModule,
} from '@nestjs/swagger';
import { AppModule } from './app.module';
async function | () {
const app = await NestFactory.create(AppModule);
app.setGlobalPrefix('api');
app.useGlobalPipes(new ValidationPipe({ transform: true }));
const options: ExpressSwaggerCustomOptions = {
customSiteTitle: 'meals api',
customfavIcon: '',
};
const config = new DocumentBuilder()
.setTitle('meals api')
.setDescription('The meals API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('', app, document, options);
const configService = app.get(ConfigService);
const port = configService.get('PORT');
await app.listen(port || 3000);
}
bootstrap();
| bootstrap |
server.rs | use iron::error::HttpError;
use iron::Listening;
use iron::prelude::*;
use persistent::State;
use router::Router;
use provider::Provider;
use routes;
use utils;
use types::ProviderState;
pub fn | <T>(prov: Box<T>) -> Result<Listening, HttpError>
where
T: Provider + 'static + Send + Sync,
{
// create a chain with a route map
let mut chain = Chain::new(setup_route_map::<T>());
let provider_state = ProviderState { prov };
// this object manages thread-safe access to the shared provider state
let safe_provider_state = State::<ProviderState<T>>::one(provider_state);
// add a "before" middleware for injecting our provider state
chain.link_before(safe_provider_state);
// start the web server
let port = utils::get_env_integral("PORT", Ok(3000u16));
Iron::new(chain).http(format!("0.0.0.0:{}", port))
}
fn setup_route_map<T>() -> Router
where
T: Provider + 'static + Send + Sync,
{
router!(
index: get "/" => routes::default,
create_pod: post "/createPod" => routes::create_pod::<T>,
update_pod: put "/updatePod" => routes::update_pod::<T>,
delete_pod: delete "/deletePod" => routes::delete_pod::<T>,
get_pod: get "/getPod" => routes::get_pod::<T>,
get_container_logs: get "/getContainerLogs" => routes::get_container_logs::<T>,
get_pod_status: get "/getPodStatus" => routes::get_pod_status::<T>,
get_pods: get "/getPods" => routes::get_pods::<T>,
capacity: get "/capacity" => routes::capacity::<T>,
node_conditions: get "/nodeConditions" => routes::node_conditions::<T>,
node_addresses: get "/nodeAddresses" => routes::node_addresses::<T>,
node_daemon_endpoints: get "/nodeDaemonEndpoints" => routes::node_daemon_endpoints::<T>,
operating_system: get "/operatingSystem" => routes::operating_system::<T>,
)
}
| start_server |
Main.js | webpackJsonp([0],{
/***/ 83:
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = __webpack_require__(82);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(32);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Main = function (_Component) {
_inherits(Main, _Component);
function Main() {
_classCallCheck(this, Main);
return _possibleConstructorReturn(this, (Main.__proto__ || Object.getPrototypeOf(Main)).apply(this, arguments));
}
_createClass(Main, [{
key: "render",
value: function render() {
return _react2.default.createElement(
"div",
{ className: "main" },
_react2.default.createElement(
"h1",
null,
"Hello World"
),
_react2.default.createElement(
"h2",
null,
"This is my first react app"
),
_react2.default.createElement(
"h3",
null,
"Sup"
)
);
}
}]);
return Main;
}(_react.Component);
var app = document.getElementById("app");
_reactDom2.default.render(_react2.default.createElement(Main, null), app);
/***/ }) |
},[83]); | |
props-util.ts | import type { Slots, VNode } from 'vue';
export function getPropsSlot(
slots: Slots, | return props[prop] ?? slots[prop]?.();
} | props: unknown,
prop = 'default'
): VNode | string | undefined { |
client_base.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""Contains classes and functions that a SAML2.0 Service Provider (SP) may use
to conclude its tasks.
"""
import threading
import six
from saml2.entity import Entity
from saml2.mdstore import destinations
from saml2.profile import paos, ecp
from saml2.saml import NAMEID_FORMAT_TRANSIENT
from saml2.samlp import AuthnQuery, RequestedAuthnContext
from saml2.samlp import NameIDMappingRequest
from saml2.samlp import AttributeQuery
from saml2.samlp import AuthzDecisionQuery
from saml2.samlp import AuthnRequest
import saml2
import time
from saml2.soap import make_soap_enveloped_saml_thingy
from six.moves.urllib.parse import parse_qs
from six.moves.urllib.parse import urlencode
from six.moves.urllib.parse import urlparse
from saml2.s_utils import signature
from saml2.s_utils import UnravelError
from saml2.s_utils import do_attributes
from saml2 import samlp, BINDING_SOAP, SAMLError
from saml2 import saml
from saml2 import soap
from saml2.population import Population
from saml2.response import AttributeResponse, StatusError
from saml2.response import AuthzResponse
from saml2.response import AssertionIDResponse
from saml2.response import AuthnQueryResponse
from saml2.response import NameIDMappingResponse
from saml2.response import AuthnResponse
from saml2 import BINDING_HTTP_REDIRECT
from saml2 import BINDING_HTTP_POST
from saml2 import BINDING_PAOS
import logging
logger = logging.getLogger(__name__)
SSO_BINDING = saml2.BINDING_HTTP_REDIRECT
FORM_SPEC = """<form method="post" action="%s">
<input type="hidden" name="SAMLRequest" value="%s" />
<input type="hidden" name="RelayState" value="%s" />
<input type="submit" value="Submit" />
</form>"""
LAX = False
ECP_SERVICE = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:ecp"
ACTOR = "http://schemas.xmlsoap.org/soap/actor/next"
MIME_PAOS = "application/vnd.paos+xml"
class IdpUnspecified(SAMLError):
pass
class VerifyError(SAMLError):
pass
class SignOnError(SAMLError):
pass
class LogoutError(SAMLError):
pass
class NoServiceDefined(SAMLError):
pass
class Base(Entity):
""" The basic pySAML2 service provider class """
def __init__(self, config=None, identity_cache=None, state_cache=None,
virtual_organization="", config_file="", msg_cb=None):
"""
:param config: A saml2.config.Config instance
:param identity_cache: Where the class should store identity information
:param state_cache: Where the class should keep state information
:param virtual_organization: A specific virtual organization
"""
Entity.__init__(self, "sp", config, config_file, virtual_organization,
msg_cb=msg_cb)
self.users = Population(identity_cache)
self.lock = threading.Lock()
# for server state storage
if state_cache is None:
self.state = {} # in memory storage
else:
self.state = state_cache
self.logout_requests_signed = False
self.allow_unsolicited = False
self.authn_requests_signed = False
self.want_assertions_signed = False
self.want_response_signed = False
for foo in ["allow_unsolicited", "authn_requests_signed",
"logout_requests_signed", "want_assertions_signed",
"want_response_signed"]:
v = self.config.getattr(foo, "sp")
if v is True or v == 'true':
setattr(self, foo, True)
self.artifact2response = {}
#
# Private methods
#
def _relay_state(self, session_id):
vals = [session_id, str(int(time.time()))]
if self.config.secret is None:
vals.append(signature("", vals))
else:
vals.append(signature(self.config.secret, vals))
return "|".join(vals)
def _sso_location(self, entityid=None, binding=BINDING_HTTP_REDIRECT):
if entityid:
# verify that it's in the metadata
srvs = self.metadata.single_sign_on_service(entityid, binding)
if srvs:
return destinations(srvs)[0]
else:
logger.info("_sso_location: %s, %s", entityid, binding)
raise IdpUnspecified("No IdP to send to given the premises")
# get the idp location from the metadata. If there is more than one
# IdP in the configuration raise exception
eids = self.metadata.with_descriptor("idpsso")
if len(eids) > 1:
raise IdpUnspecified("Too many IdPs to choose from: %s" % eids)
try:
srvs = self.metadata.single_sign_on_service(list(eids.keys())[0],
binding)
return destinations(srvs)[0]
except IndexError:
raise IdpUnspecified("No IdP to send to given the premises")
def sso_location(self, entityid=None, binding=BINDING_HTTP_REDIRECT):
return self._sso_location(entityid, binding)
def _my_name(self):
return self.config.name
#
# Public API
#
def add_vo_information_about_user(self, name_id):
""" Add information to the knowledge I have about the user. This is
for Virtual organizations.
:param name_id: The subject identifier
:return: A possibly extended knowledge.
"""
ava = {}
try:
(ava, _) = self.users.get_identity(name_id)
except KeyError:
pass
# is this a Virtual Organization situation
if self.vorg:
if self.vorg.do_aggregation(name_id):
# Get the extended identity
ava = self.users.get_identity(name_id)[0]
return ava
# noinspection PyUnusedLocal
@staticmethod
def is_session_valid(_session_id):
""" Place holder. Supposed to check if the session is still valid.
"""
return True
def service_urls(self, binding=BINDING_HTTP_POST):
_res = self.config.endpoint("assertion_consumer_service", binding, "sp")
if _res:
return _res
else:
return None
def create_authn_request(self, destination, vorg="", scoping=None,
binding=saml2.BINDING_HTTP_POST,
nameid_format=None,
service_url_binding=None, message_id=0,
consent=None, extensions=None, sign=None,
allow_create=None, sign_prepare=False, sign_alg=None,
digest_alg=None, **kwargs):
""" Creates an authentication request.
:param destination: Where the request should be sent.
:param vorg: The virtual organization the service belongs to.
:param scoping: The scope of the request
:param binding: The protocol to use for the Response !!
:param nameid_format: Format of the NameID
:param service_url_binding: Where the reply should be sent dependent
on reply binding.
:param message_id: The identifier for this request
:param consent: Whether the principal have given her consent
:param extensions: Possible extensions
:param sign: Whether the request should be signed or not.
:param sign_prepare: Whether the signature should be prepared or not.
:param allow_create: If the identity provider is allowed, in the course
of fulfilling the request, to create a new identifier to represent
the principal.
:param kwargs: Extra key word arguments
:return: tuple of request ID and <samlp:AuthnRequest> instance
"""
client_crt = None
if "client_crt" in kwargs:
client_crt = kwargs["client_crt"]
args = {}
try:
args["assertion_consumer_service_url"] = kwargs[
"assertion_consumer_service_urls"][0]
del kwargs["assertion_consumer_service_urls"]
except KeyError:
try:
args["assertion_consumer_service_url"] = kwargs[
"assertion_consumer_service_url"]
del kwargs["assertion_consumer_service_url"]
except KeyError:
try:
args["assertion_consumer_service_index"] = str(
kwargs["assertion_consumer_service_index"])
del kwargs["assertion_consumer_service_index"]
except KeyError:
if service_url_binding is None:
service_urls = self.service_urls(binding)
else:
service_urls = self.service_urls(service_url_binding)
args["assertion_consumer_service_url"] = service_urls[0]
try:
args["provider_name"] = kwargs["provider_name"]
except KeyError:
if binding == BINDING_PAOS:
pass
else:
args["provider_name"] = self._my_name()
# Allow argument values either as class instances or as dictionaries
# all of these have cardinality 0..1
_msg = AuthnRequest()
for param in ["scoping", "requested_authn_context", "conditions",
"subject"]:
try:
_item = kwargs[param]
except KeyError:
pass
else:
del kwargs[param]
# either class instance or argument dictionary
if isinstance(_item, _msg.child_class(param)):
args[param] = _item
elif isinstance(_item, dict):
args[param] = RequestedAuthnContext(**_item)
else:
raise ValueError("%s or wrong type expected %s" % (_item,
param))
try:
args["name_id_policy"] = kwargs["name_id_policy"]
del kwargs["name_id_policy"]
except KeyError:
if allow_create is None:
allow_create = self.config.getattr("name_id_format_allow_create", "sp")
if allow_create is None:
allow_create = "false"
else:
if allow_create is True:
allow_create = "true"
else:
allow_create = "false"
if nameid_format == "":
name_id_policy = None
else:
if nameid_format is None:
nameid_format = self.config.getattr("name_id_format", "sp")
# If no nameid_format has been set in the configuration
# or passed in then transient is the default.
if nameid_format is None:
nameid_format = NAMEID_FORMAT_TRANSIENT
# If a list has been configured or passed in choose the
# first since NameIDPolicy can only have one format specified.
elif isinstance(nameid_format, list):
nameid_format = nameid_format[0]
# Allow a deployer to signal that no format should be specified
# in the NameIDPolicy by passing in or configuring the string 'None'.
elif nameid_format == 'None':
nameid_format = None
name_id_policy = samlp.NameIDPolicy(allow_create=allow_create,
format=nameid_format)
if name_id_policy and vorg:
try:
name_id_policy.sp_name_qualifier = vorg
name_id_policy.format = saml.NAMEID_FORMAT_PERSISTENT
except KeyError:
pass
args["name_id_policy"] = name_id_policy
try:
nsprefix = kwargs["nsprefix"]
except KeyError:
nsprefix = None
if kwargs:
_args, extensions = self._filter_args(AuthnRequest(), extensions,
**kwargs)
args.update(_args)
try:
del args["id"]
except KeyError:
pass
if sign is None:
sign = self.authn_requests_signed
if (sign and self.sec.cert_handler.generate_cert()) or \
client_crt is not None:
with self.lock:
self.sec.cert_handler.update_cert(True, client_crt)
if client_crt is not None:
sign_prepare = True
return self._message(AuthnRequest, destination, message_id,
consent, extensions, sign, sign_prepare,
protocol_binding=binding,
scoping=scoping, nsprefix=nsprefix,
sign_alg=sign_alg, digest_alg=digest_alg,
**args)
return self._message(AuthnRequest, destination, message_id, consent,
extensions, sign, sign_prepare,
protocol_binding=binding,
scoping=scoping, nsprefix=nsprefix,
sign_alg=sign_alg, digest_alg=digest_alg, **args)
def create_attribute_query(self, destination, name_id=None,
attribute=None, message_id=0, consent=None,
extensions=None, sign=False, sign_prepare=False, sign_alg=None,
digest_alg=None,
**kwargs):
""" Constructs an AttributeQuery
:param destination: To whom the query should be sent
:param name_id: The identifier of the subject
:param attribute: A dictionary of attributes and values that is
asked for. The key are one of 4 variants:
3-tuple of name_format,name and friendly_name,
2-tuple of name_format and name,
1-tuple with name or
just the name as a string.
:param sp_name_qualifier: The unique identifier of the
service provider or affiliation of providers for whom the
identifier was generated.
:param name_qualifier: The unique identifier of the identity
provider that generated the identifier.
:param format: The format of the name ID
:param message_id: The identifier of the session
:param consent: Whether the principal have given her consent
:param extensions: Possible extensions
:param sign: Whether the query should be signed or not.
:param sign_prepare: Whether the Signature element should be added.
:return: Tuple of request ID and an AttributeQuery instance
"""
if name_id is None:
if "subject_id" in kwargs:
name_id = saml.NameID(text=kwargs["subject_id"])
for key in ["sp_name_qualifier", "name_qualifier",
"format"]:
try:
setattr(name_id, key, kwargs[key])
except KeyError:
pass
else:
raise AttributeError("Missing required parameter")
elif isinstance(name_id, six.string_types):
name_id = saml.NameID(text=name_id)
for key in ["sp_name_qualifier", "name_qualifier", "format"]:
try:
setattr(name_id, key, kwargs[key])
except KeyError:
pass
subject = saml.Subject(name_id=name_id)
if attribute:
attribute = do_attributes(attribute)
try:
nsprefix = kwargs["nsprefix"]
except KeyError:
nsprefix = None
return self._message(AttributeQuery, destination, message_id, consent,
extensions, sign, sign_prepare, subject=subject,
attribute=attribute, nsprefix=nsprefix,
sign_alg=sign_alg, digest_alg=digest_alg)
# MUST use SOAP for
# AssertionIDRequest, SubjectQuery,
# AuthnQuery, AttributeQuery, or AuthzDecisionQuery
def create_authz_decision_query(self, destination, action,
evidence=None, resource=None, subject=None,
message_id=0, consent=None, extensions=None,
sign=None, sign_alg=None, digest_alg=None, **kwargs):
""" Creates an authz decision query.
:param destination: The IdP endpoint
:param action: The action you want to perform (has to be at least one)
:param evidence: Why you should be able to perform the action
:param resource: The resource you want to perform the action on
:param subject: Who wants to do the thing
:param message_id: Message identifier
:param consent: If the principal gave her consent to this request
:param extensions: Possible request extensions
:param sign: Whether the request should be signed or not.
:return: AuthzDecisionQuery instance
"""
return self._message(AuthzDecisionQuery, destination, message_id,
consent, extensions, sign, action=action,
evidence=evidence, resource=resource,
subject=subject, sign_alg=sign_alg,
digest_alg=digest_alg, **kwargs)
def create_authz_decision_query_using_assertion(self, destination,
assertion, action=None,
resource=None, | """ Makes an authz decision query based on a previously received
Assertion.
:param destination: The IdP endpoint to send the request to
:param assertion: An Assertion instance
:param action: The action you want to perform (has to be at least one)
:param resource: The resource you want to perform the action on
:param subject: Who wants to do the thing
:param message_id: Message identifier
:param consent: If the principal gave her consent to this request
:param extensions: Possible request extensions
:param sign: Whether the request should be signed or not.
:return: AuthzDecisionQuery instance
"""
if action:
if isinstance(action, six.string_types):
_action = [saml.Action(text=action)]
else:
_action = [saml.Action(text=a) for a in action]
else:
_action = None
return self.create_authz_decision_query(
destination, _action, saml.Evidence(assertion=assertion),
resource, subject, message_id=message_id, consent=consent,
extensions=extensions, sign=sign, nsprefix=nsprefix)
@staticmethod
def create_assertion_id_request(assertion_id_refs, **kwargs):
"""
:param assertion_id_refs:
:return: One ID ref
"""
if isinstance(assertion_id_refs, six.string_types):
return 0, assertion_id_refs
else:
return 0, assertion_id_refs[0]
def create_authn_query(self, subject, destination=None, authn_context=None,
session_index="", message_id=0, consent=None,
extensions=None, sign=False, nsprefix=None, sign_alg=None,
digest_alg=None):
"""
:param subject: The subject its all about as a <Subject> instance
:param destination: The IdP endpoint to send the request to
:param authn_context: list of <RequestedAuthnContext> instances
:param session_index: a specified session index
:param message_id: Message identifier
:param consent: If the principal gave her consent to this request
:param extensions: Possible request extensions
:param sign: Whether the request should be signed or not.
:return:
"""
return self._message(AuthnQuery, destination, message_id, consent,
extensions, sign, subject=subject,
session_index=session_index,
requested_authn_context=authn_context,
nsprefix=nsprefix, sign_alg=sign_alg,
digest_alg=digest_alg)
def create_name_id_mapping_request(self, name_id_policy,
name_id=None, base_id=None,
encrypted_id=None, destination=None,
message_id=0, consent=None,
extensions=None, sign=False,
nsprefix=None, sign_alg=None, digest_alg=None):
"""
:param name_id_policy:
:param name_id:
:param base_id:
:param encrypted_id:
:param destination:
:param message_id: Message identifier
:param consent: If the principal gave her consent to this request
:param extensions: Possible request extensions
:param sign: Whether the request should be signed or not.
:return:
"""
# One of them must be present
assert name_id or base_id or encrypted_id
if name_id:
return self._message(NameIDMappingRequest, destination, message_id,
consent, extensions, sign,
name_id_policy=name_id_policy, name_id=name_id,
nsprefix=nsprefix, sign_alg=sign_alg,
digest_alg=digest_alg)
elif base_id:
return self._message(NameIDMappingRequest, destination, message_id,
consent, extensions, sign,
name_id_policy=name_id_policy, base_id=base_id,
nsprefix=nsprefix, sign_alg=sign_alg,
digest_alg=digest_alg)
else:
return self._message(NameIDMappingRequest, destination, message_id,
consent, extensions, sign,
name_id_policy=name_id_policy,
encrypted_id=encrypted_id, nsprefix=nsprefix,
sign_alg=sign_alg, digest_alg=digest_alg)
# ======== response handling ===========
def parse_authn_request_response(self, xmlstr, binding, outstanding=None,
outstanding_certs=None, conv_info=None):
""" Deal with an AuthnResponse
:param xmlstr: The reply as a xml string
:param binding: Which binding that was used for the transport
:param outstanding: A dictionary with session IDs as keys and
the original web request from the user before redirection
as values.
:param outstanding_certs:
:param conv_info: Information about the conversation.
:return: An response.AuthnResponse or None
"""
try:
_ = self.config.entityid
except KeyError:
raise SAMLError("Missing entity_id specification")
resp = None
if xmlstr:
kwargs = {
"outstanding_queries": outstanding,
"outstanding_certs": outstanding_certs,
"allow_unsolicited": self.allow_unsolicited,
"want_assertions_signed": self.want_assertions_signed,
"want_response_signed": self.want_response_signed,
"return_addrs": self.service_urls(binding=binding),
"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters,
"allow_unknown_attributes":
self.config.allow_unknown_attributes,
'conv_info': conv_info
}
try:
resp = self._parse_response(xmlstr, AuthnResponse,
"assertion_consumer_service",
binding, **kwargs)
except StatusError as err:
logger.error("SAML status error: %s", err)
raise
except UnravelError:
return None
except Exception as err:
logger.error("XML parse error: %s", err)
raise
if resp is None:
return None
elif isinstance(resp, AuthnResponse):
if resp.assertion is not None and len(
resp.response.encrypted_assertion) == 0:
self.users.add_information_about_person(resp.session_info())
logger.info("--- ADDED person info ----")
pass
else:
logger.error("Response type not supported: %s",
saml2.class_name(resp))
return resp
# ------------------------------------------------------------------------
# SubjectQuery, AuthnQuery, RequestedAuthnContext, AttributeQuery,
# AuthzDecisionQuery all get Response as response
def parse_authz_decision_query_response(self, response,
binding=BINDING_SOAP):
""" Verify that the response is OK
"""
kwargs = {"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters}
return self._parse_response(response, AuthzResponse, "", binding,
**kwargs)
def parse_authn_query_response(self, response, binding=BINDING_SOAP):
""" Verify that the response is OK
"""
kwargs = {"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters}
return self._parse_response(response, AuthnQueryResponse, "", binding,
**kwargs)
def parse_assertion_id_request_response(self, response, binding):
""" Verify that the response is OK
"""
kwargs = {"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters}
res = self._parse_response(response, AssertionIDResponse, "", binding,
**kwargs)
return res
# ------------------------------------------------------------------------
def parse_attribute_query_response(self, response, binding):
kwargs = {"entity_id": self.config.entityid,
"attribute_converters": self.config.attribute_converters}
return self._parse_response(response, AttributeResponse,
"attribute_consuming_service", binding,
**kwargs)
def parse_name_id_mapping_request_response(self, txt, binding=BINDING_SOAP):
"""
:param txt: SOAP enveloped SAML message
:param binding: Just a placeholder, it's always BINDING_SOAP
:return: parsed and verified <NameIDMappingResponse> instance
"""
return self._parse_response(txt, NameIDMappingResponse, "", binding)
# ------------------- ECP ------------------------------------------------
def create_ecp_authn_request(self, entityid=None, relay_state="",
sign=False, **kwargs):
""" Makes an authentication request.
:param entityid: The entity ID of the IdP to send the request to
:param relay_state: A token that can be used by the SP to know
where to continue the conversation with the client
:param sign: Whether the request should be signed or not.
:return: SOAP message with the AuthnRequest
"""
# ----------------------------------------
# <paos:Request>
# ----------------------------------------
my_url = self.service_urls(BINDING_PAOS)[0]
# must_understand and act according to the standard
#
paos_request = paos.Request(must_understand="1", actor=ACTOR,
response_consumer_url=my_url,
service=ECP_SERVICE)
# ----------------------------------------
# <ecp:RelayState>
# ----------------------------------------
relay_state = ecp.RelayState(actor=ACTOR, must_understand="1",
text=relay_state)
# ----------------------------------------
# <samlp:AuthnRequest>
# ----------------------------------------
try:
authn_req = kwargs["authn_req"]
try:
req_id = authn_req.id
except AttributeError:
req_id = 0 # Unknown but since it's SOAP it doesn't matter
except KeyError:
try:
_binding = kwargs["binding"]
except KeyError:
_binding = BINDING_SOAP
kwargs["binding"] = _binding
logger.debug("entityid: %s, binding: %s", entityid, _binding)
# The IDP publishes support for ECP by using the SOAP binding on
# SingleSignOnService
_, location = self.pick_binding("single_sign_on_service",
[_binding], entity_id=entityid)
req_id, authn_req = self.create_authn_request(
location, service_url_binding=BINDING_PAOS, **kwargs)
# ----------------------------------------
# The SOAP envelope
# ----------------------------------------
soap_envelope = make_soap_enveloped_saml_thingy(authn_req,
[paos_request,
relay_state])
return req_id, "%s" % soap_envelope
def parse_ecp_authn_response(self, txt, outstanding=None):
rdict = soap.class_instances_from_soap_enveloped_saml_thingies(txt,
[paos,
ecp,
samlp])
_relay_state = None
for item in rdict["header"]:
if item.c_tag == "RelayState" and \
item.c_namespace == ecp.NAMESPACE:
_relay_state = item
response = self.parse_authn_request_response(rdict["body"],
BINDING_PAOS, outstanding)
return response, _relay_state
@staticmethod
def can_handle_ecp_response(response):
try:
accept = response.headers["accept"]
except KeyError:
try:
accept = response.headers["Accept"]
except KeyError:
return False
if MIME_PAOS in accept:
return True
else:
return False
# ----------------------------------------------------------------------
# IDP discovery
# ----------------------------------------------------------------------
@staticmethod
def create_discovery_service_request(url, entity_id, **kwargs):
"""
Created the HTTP redirect URL needed to send the user to the
discovery service.
:param url: The URL of the discovery service
:param entity_id: The unique identifier of the service provider
:param return: The discovery service MUST redirect the user agent
to this location in response to this request
:param policy: A parameter name used to indicate the desired behavior
controlling the processing of the discovery service
:param returnIDParam: A parameter name used to return the unique
identifier of the selected identity provider to the original
requester.
:param isPassive: A boolean value True/False that controls
whether the discovery service is allowed to visibly interact with
the user agent.
:return: A URL
"""
args = {"entityID": entity_id}
for key in ["policy", "returnIDParam"]:
try:
args[key] = kwargs[key]
except KeyError:
pass
try:
args["return"] = kwargs["return_url"]
except KeyError:
try:
args["return"] = kwargs["return"]
except KeyError:
pass
if "isPassive" in kwargs:
if kwargs["isPassive"]:
args["isPassive"] = "true"
else:
args["isPassive"] = "false"
params = urlencode(args)
return "%s?%s" % (url, params)
@staticmethod
def parse_discovery_service_response(url="", query="",
returnIDParam="entityID"):
"""
Deal with the response url from a Discovery Service
:param url: the url the user was redirected back to or
:param query: just the query part of the URL.
:param returnIDParam: This is where the identifier of the IdP is
place if it was specified in the query. Default is 'entityID'
:return: The IdP identifier or "" if none was given
"""
if url:
part = urlparse(url)
qsd = parse_qs(part[4])
elif query:
qsd = parse_qs(query)
else:
qsd = {}
try:
return qsd[returnIDParam][0]
except KeyError:
return "" | subject=None, message_id=0,
consent=None,
extensions=None,
sign=False, nsprefix=None): |
_index.ts | import mongoose = require("mongoose");
import User from "./schemas/user";
import IU from "./schemas/IUser";
const mongoDBURI = "<%= dbcon %>";
class | {
constructor() {
mongoose.connect(mongoDBURI);
mongoose.Promise = global.Promise;
mongoose.connection.on(
"error",
console.error.bind(console, "MongoDB connection error: ")
);
}
public getAllUsers(): Promise<IU[]> {
return new Promise((resolve, reject) => {
const query = User.find({}).sort("-createdAt");
query.exec((err, data) => {
if (err) {
reject("Some Error, Contact DAL Developer.");
}
console.log(data[0]);
resolve(data);
});
});
}
public addUser(user: any): Promise<IU> {
const b = new User(user);
return new Promise((resolve, reject) => {
b.save(err => {
if (err) {
reject("Some Error, Contact DAL Developer.");
}
resolve(b);
});
});
}
}
export default new DataAccess();
| DataAccess |
wsgi.py | """
WSGI config for games project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "games.settings")
application = get_wsgi_application() | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
""" |
__init__.py | # Copyright 2016-2017 Dirk Thomas
# Copyright 2017 Open Source Robotics Foundation, 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.
from keymint_cli.plugin_system import instantiate_extensions
from keymint_cli.plugin_system import PLUGIN_SYSTEM_VERSION
from keymint_cli.plugin_system import satisfies_version
class VerbExtension:
"""
The interface for verb extensions.
The following properties must be defined:
* `NAME` (will be set to the entry point name)
The following methods must be defined:
* `main`
"""
NAME = None
EXTENSION_POINT_VERSION = '0.1'
def __init__(self):
super(VerbExtension, self).__init__()
satisfies_version(PLUGIN_SYSTEM_VERSION, '^0.1')
def get_verb_extensions(name):
|
def add_task_arguments(parser, task_name):
plugins = get_verb_extensions(task_name)
for plugin_name, plugin in plugins.items():
group = parser.add_argument_group(
title="Arguments for '{plugin_name}' packages"
.format_map(locals()))
func = getattr(plugin, 'add_%s_arguments' % task_name, None)
if func:
func(group)
| extensions = instantiate_extensions(name)
for name, extension in extensions.items():
extension.NAME = name
return extensions |
label.py | """
fastgame.widget.label
Fastgame文本组件。
"""
from typing import Tuple
import pygame
import fastgame
from fastgame.exceptions import *
from fastgame.utils.color import *
__all__ = ['Label']
class Label(pygame.sprite.Sprite):
def __init__(self, text: str, font: str = None, size: int = 16, use_sys_font: bool = False,
color: ColorType = BLACK, bgcolor: ColorType = None, antialias: bool = True,
bold=False, italic=False, **kwargs):
"""
Fastgame文本组件类。
粗体和斜体仅在使用系统字体时有效。
:param text: 文本内容。
:param font: 字体文件路径或字体名。
:param size: 文本大小
:param use_sys_font: 是否使用系统字体。
:param color: 文本前景色。
:param bgcolor: 文本背景色。
:param antialias: 是否使用抗锯齿。
:param bold: 是否加粗。
:param italic: 是否斜体。
"""
super().__init__()
if 'fgcolor' in kwargs:
color = kwargs['fgcolor']
if 'foreground_color' in kwargs:
color = kwargs['foreground_color']
if 'background_color' in kwargs:
bgcolor = kwargs['background_color']
self.text = text
self.font = (
pygame.font.SysFont(font, size, bold=bold, italic=italic)
if use_sys_font else
pygame.font.Font(font, size)
)
if not fastgame.games:
raise NotCreatedGameError('did not create FastGame object')
game = fastgame.games[-1]
self.screen = game.window
self.image = self.font.render(self.text, antialias, color, bgcolor)
self.rect = self.image.get_rect()
self._show = True
self.fgcolor = color
self.bgcolor = bgcolor
self.antialias = antialias
@property
def position(self):
return self.rect.x, self.rect.y
@position.setter
def position(self, pos: Tuple[int, int]):
self.rect.x, self.rect.y = pos
def update(self):
"""
在窗口上更新此文本。
必须在被Fastgame.update装饰过的函数中调用。
:return: 无。
:rtype | elf.screen.blit(self.image, self.rect)
def hide(self):
self._show = False
def show(self):
self._show = True
def collide_other(self, sprite: pygame.sprite.Sprite):
"""
检测此角色是否碰到了另一角色。
判断方法基于两个角色的矩形碰撞!
当有非长方形的角色参与检测,会出现看似没有碰撞,检测却是碰撞的情况!
:param sprite: 另一角色。
:return: 是否碰撞。
:rtype: bool
"""
return pygame.sprite.collide_rect(self, sprite)
def set_style(self, color: ColorType = BLACK, bgcolor: ColorType = None, antialias: bool = True, **kwargs):
"""
设置字体风格。
:param color: 文本前景色。
:param bgcolor: 文本背景色。
:param antialias: 是否使用抗锯齿。
"""
if 'fgcolor' in kwargs:
color = kwargs['fgcolor']
if 'foreground_color' in kwargs:
color = kwargs['foreground_color']
if 'background_color' in kwargs:
bgcolor = kwargs['background_color']
self.image = self.font.render(self.text, antialias, color, bgcolor)
temp_rect = self.rect.copy()
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = temp_rect.x, temp_rect.y
def collide_edge(self):
"""
检测此角色是否碰到了边缘。
判断方法基于角色矩形!
当有非长方形的角色参与检测,会出现看似没有碰撞,检测却是碰撞的情况!
:return: 是否碰撞左右边缘、是否碰撞上下边缘。
:rtype: Tuple[bool, bool]
"""
screen_rect = self.screen.get_rect()
width, height = screen_rect.width, screen_rect.height
return (self.rect.x <= 0 or self.rect.right >= width), \
(self.rect.y <= 0 or self.rect.bottom >= height)
def move_to_mouse(self):
"""
移动至鼠标指针的位置。
:return: 无。
:rtype: None
"""
self.rect.x, self.rect.y = pygame.mouse.get_pos()
def add_x(self, add: int):
"""
增加X坐标。
:param add: 增加的X坐标,可以为负数。
:return: 无。
:rtype: None
"""
self.rect.x += add
def add_y(self, add: int):
"""
增加Y坐标。
:param add: 增加的Y坐标,可以为负数。
:return: 无。
:rtype: None
"""
self.rect.y += add
def set_x(self, x: int):
"""
设置X坐标。
:param x: X坐标,可以为负数。
:return: 无。
:rtype: None
"""
self.rect.x = x
def set_y(self, y: int):
"""
设置Y坐标。
:param y: Y坐标,可以为负数。
:return: 无。
:rtype: None
"""
self.rect.y = y
def move_to(self, x: int, y: int):
"""
移动坐标至某点。
:param x: X坐标,可以为负数。
:param y: Y坐标,可以为负数。
:return: 无。
:rtype: None
"""
self.rect.x, self.rect.y = x, y
def resize(self, size: Tuple[int, int]):
"""
缩放此文本。
:param size: 图片大小。
:return: 无。
:rtype: None
"""
temp = self.rect.copy()
self.width, self.height = size
self.image = pygame.transform.scale(self.image, size)
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = temp.x, temp.y
del temp
def set_text(self, text: str):
"""
设置文字。
:param text: 文本内容。
"""
self.text = text
self.image = self.font.render(self.text, self.antialias, self.fgcolor, self.bgcolor)
temp = self.rect.copy()
self.rect = self.image.get_rect()
self.rect.x, self.rect.y = temp.x, temp.y
| : None
"""
s |
views.py | import datetime
from pathlib import Path
import functools
import calendar
import os
from flask import Flask, render_template, jsonify, url_for, Response, abort, g, redirect
from flask import send_from_directory
import ics
from arca import Arca
from naucse import models
from naucse.urlconverters import register_url_converters
from naucse.templates import setup_jinja_env
app = Flask('naucse')
app.config['JSON_AS_ASCII'] = False
@app.before_request
def _get_model():
"""Set `g.model` to the root of the naucse model
A single model is used (and stored in app config).
In debug mode (elsa serve), the model is re-initialized for each request,
so changes are picked up.
In non-debug mode (elsa freeze), the model is initialized once, and
frozen (so all course data is requested and rendered upfront).
"""
freezing = os.environ.get('NAUCSE_FREEZE', not app.config['DEBUG'])
initialize = True
try:
g.model = app.config['NAUCSE_MODEL']
except KeyError:
g.model = init_model()
app.config['NAUCSE_MODEL'] = g.model
else:
if freezing:
# Model already initialized; don't look for changes
return
# (Re-)initialize model
g.model.load_licenses(Path(app.root_path).parent / 'licenses')
g.model.load_local_courses(Path(app.root_path).parent)
if freezing:
g.model.freeze()
def init_model():
trusted = os.environ.get('NAUCSE_TRUSTED_REPOS', None)
if trusted is None:
trusted_repo_patterns = ()
else:
trusted_repo_patterns = tuple(
line for line in trusted.split() if line
)
return models.Root(
url_factories={
'api': {
models.Root: lambda **kw: url_for('api', **kw),
models.Course: lambda **kw: url_for('course_api', **kw),
models.RunYear: lambda **kw: url_for('run_year_api', **kw),
},
'web': {
models.Lesson: lambda **kw: url_for('page',
page_slug='index', **kw),
models.Page: lambda **kw: url_for('page', **kw),
models.Solution: lambda **kw: url_for('solution', **kw),
models.Course: lambda **kw: url_for('course', **kw),
models.Session: lambda **kw: url_for('session', **kw),
models.SessionPage: lambda **kw: url_for(
'session', **kw),
models.StaticFile: lambda **kw: url_for('page_static', **kw),
models.Root: lambda **kw: url_for('index', **kw)
},
},
schema_url_factory=lambda m, is_input, **kw: url_for(
'schema', model_slug=m.model_slug,
is_input=is_input, **kw),
arca=Arca(settings={
"ARCA_BACKEND": "arca.backend.CurrentEnvironmentBackend",
"ARCA_BACKEND_CURRENT_ENVIRONMENT_REQUIREMENTS": "requirements.txt",
"ARCA_BACKEND_VERBOSITY": 2,
"ARCA_BACKEND_KEEP_CONTAINER_RUNNING": True,
"ARCA_BACKEND_USE_REGISTRY_NAME": "docker.io/naucse/naucse.python.cz",
"ARCA_SINGLE_PULL": True,
"ARCA_IGNORE_CACHE_ERRORS": True,
"ARCA_CACHE_BACKEND": "dogpile.cache.dbm",
"ARCA_CACHE_BACKEND_ARGUMENTS": {
"filename": ".arca/cache/naucse.dbm"
},
"ARCA_BASE_DIR": str(Path('.arca').resolve()),
}),
trusted_repo_patterns=trusted_repo_patterns,
)
register_url_converters(app)
setup_jinja_env(app.jinja_env)
@app.route('/')
def index():
return render_template("index.html", edit_info=g.model.edit_info)
@app.route('/courses/')
def courses():
return render_template(
"course_list.html",
featured_courses=g.model.featured_courses,
edit_info=g.model.course_edit_info,
)
@app.route('/runs/')
@app.route('/<int:year>/')
@app.route('/runs/<any(all):all>/')
def runs(year=None, all=None):
# XXX: Simplify?
today = datetime.date.today()
# List of years to show in the pagination
# If the current year is not there (no runs that start in the current year
# yet), add it manually
all_years = sorted(g.model.explicit_run_years)
if today.year not in all_years:
all_years.append(today.year)
first_year, last_year = min(all_years), max(all_years)
if year is not None:
if year > last_year:
# Instead of showing a future year, redirect to the 'Current' page
return redirect(url_for('runs'))
if year not in all_years:
# Otherwise, if there are no runs in requested year, return 404.
abort(404)
if all is not None:
run_data = {}
courses = g.model.courses
for slug, course in g.model.courses.items():
if course.start_date:
run_data.setdefault(course.start_date.year, {})[slug] = course
paginate_prev = {'year': first_year}
paginate_next = {'all': 'all'}
elif year is None:
# Show runs that are either ongoing or ended in the last 3 months
runs = {**g.model.run_years.get(today.year, {}),
**g.model.run_years.get(today.year - 1, {})}
ongoing = {slug: run for slug, run in runs.items()
if run.end_date >= today}
cutoff = today - datetime.timedelta(days=3*31)
recent = {slug: run for slug, run in runs.items()
if today > run.end_date > cutoff}
run_data = {"ongoing": ongoing, "recent": recent}
paginate_prev = {'year': None}
paginate_next = {'year': last_year}
else:
run_data = {year: g.model.run_years.get(year, {})}
past_years = [y for y in all_years if y < year]
if past_years:
paginate_next = {'year': max(past_years)}
else:
paginate_next = {'all': 'all'}
future_years = [y for y in all_years if y > year]
if future_years:
paginate_prev = {'year': min(future_years)}
else:
paginate_prev = {'year': None}
return render_template(
"run_list.html",
run_data=run_data,
today=datetime.date.today(),
year=year,
all=all,
all_years=all_years,
paginate_next=paginate_next,
paginate_prev=paginate_prev,
edit_info=g.model.runs_edit_info,
)
@app.route('/<course:course_slug>/')
def course(course_slug, year=None):
try:
course = g.model.courses[course_slug]
except KeyError:
print(g.model.courses)
abort(404)
recent_runs = course.get_recent_derived_runs()
return render_template(
"course.html",
course=course,
recent_runs=recent_runs,
edit_info=course.edit_info,
)
@app.route('/<course:course_slug>/sessions/<session_slug>/',
defaults={'page_slug': 'front'})
@app.route('/<course:course_slug>/sessions/<session_slug>/<page_slug>/')
def session(course_slug, session_slug, page_slug):
try:
course = g.model.courses[course_slug]
session = course.sessions[session_slug]
page = session.pages[page_slug]
except KeyError:
abort(404)
template = {
'front': 'coverpage.html',
'back': 'backpage.html',
}[page.slug]
materials_by_type = {}
for material in session.materials:
materials_by_type.setdefault(material.type, []).append(material)
return render_template(
template,
session=session,
course=session.course,
edit_info=session.edit_info,
materials_by_type=materials_by_type,
page=page,
)
def _get_canonicality_info(lesson):
"""Get canonical URL -- i.e., a lesson from 'lessons' with the same slug"""
# XXX: This could be made much more fancy
lessons_course = g.model.get_course('lessons')
is_canonical_lesson = (lessons_course == lesson.course)
if is_canonical_lesson:
canonical_url = None
else:
if lessons_course._has_lesson(lesson.slug):
canonical = lessons_course.lessons[lesson.slug]
canonical_url = canonical.get_url(external=True)
else:
canonical_url = None
return is_canonical_lesson, canonical_url
@app.route('/<course:course_slug>/<lesson:lesson_slug>/',
defaults={'page_slug': 'index'})
@app.route('/<course:course_slug>/<lesson:lesson_slug>/<page_slug>/')
def page(course_slug, lesson_slug, page_slug='index'):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
page = lesson.pages[page_slug]
except KeyError:
raise abort(404)
is_canonical_lesson, canonical_url = _get_canonicality_info(lesson)
return render_template(
"lesson.html",
page=page,
content=page.content,
course=course,
canonical_url=canonical_url,
is_canonical_lesson=is_canonical_lesson,
page_attribution=page.attribution,
edit_info=page.edit_info,
)
@app.route('/<course:course_slug>/<lesson:lesson_slug>/<page_slug>'
+ '/solutions/<int:solution_index>/')
def | (course_slug, lesson_slug, page_slug, solution_index):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
page = lesson.pages[page_slug]
solution = page.solutions[solution_index]
except KeyError:
raise abort(404)
is_canonical_lesson, canonical_url = _get_canonicality_info(lesson)
return render_template(
"lesson.html",
page=page,
content=solution.content,
course=course,
canonical_url=canonical_url,
is_canonical_lesson=is_canonical_lesson,
page_attribution=page.attribution,
edit_info=page.edit_info,
solution=solution,
)
@app.route('/<course:course_slug>/<lesson:lesson_slug>/static/<path:filename>')
def page_static(course_slug, lesson_slug, filename):
try:
course = g.model.courses[course_slug]
lesson = course.lessons[lesson_slug]
static = lesson.static_files[filename]
except KeyError:
raise abort(404)
print('sending', static.base_path, static.filename)
return send_from_directory(static.base_path, static.path)
def list_months(start_date, end_date):
"""Return a span of months as a list of (year, month) tuples
The months of start_date and end_date are both included.
"""
months = []
year = start_date.year
month = start_date.month
while (year, month) <= (end_date.year, end_date.month):
months.append((year, month))
month += 1
if month > 12:
month = 1
year += 1
return months
@app.route('/<course:course_slug>/calendar/')
def course_calendar(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
if not course.start_date:
abort(404)
sessions_by_date = {
s.date: s for s in course.sessions.values()
if hasattr(s, 'date')
}
return render_template(
'course_calendar.html',
course=course,
sessions_by_date=sessions_by_date,
months=list_months(course.start_date, course.end_date),
calendar=calendar.Calendar(),
edit_info=course.edit_info,
)
@app.route('/<course:course_slug>/calendar.ics')
def course_calendar_ics(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
if not course.start_date:
abort(404)
events = []
for session in course.sessions.values():
time = getattr(session, 'time', None)
if time is None:
# Sessions without times don't show up in the calendar
continue
created = os.environ.get('NAUCSE_CALENDAR_DTSTAMP', None)
cal_event = ics.Event(
name=session.title,
begin=time['start'],
end=time['end'],
uid=session.get_url(external=True),
created=created,
)
events.append(cal_event)
cal = ics.Calendar(events=events)
return Response(str(cal), mimetype="text/calendar")
@app.route('/v0/schema/<is_input:is_input>.json', defaults={'model_slug': 'root'})
@app.route('/v0/schema/<is_input:is_input>/<model_slug>.json')
def schema(model_slug, is_input):
try:
cls = models.models[model_slug]
except KeyError:
abort(404)
return jsonify(models.get_schema(cls, is_input=is_input))
@app.route('/v0/naucse.json')
def api():
return jsonify(models.dump(g.model))
@app.route('/v0/years/<int:year>.json')
def run_year_api(year):
try:
run_year = g.model.run_years[year]
except KeyError:
abort(404)
return jsonify(models.dump(run_year))
@app.route('/v0/<course:course_slug>.json')
def course_api(course_slug):
try:
course = g.model.courses[course_slug]
except KeyError:
abort(404)
return jsonify(models.dump(course))
| solution |
objects.go | package s3
import (
"context"
"io"
"sort"
"github.com/minio/minio-go/v6"
"github.com/swisscom/backman/log"
)
func (s *Client) List(folderPath string) ([]minio.ObjectInfo, error) {
log.Debugf("list S3 object [%s]", folderPath)
objects := make([]minio.ObjectInfo, 0)
done := make(chan struct{})
defer close(done)
isRecursive := true
objectCh := s.Client.ListObjectsV2(s.BucketName, folderPath, isRecursive, done)
for object := range objectCh {
if object.Err != nil {
return nil, object.Err
}
objects = append(objects, object)
}
sort.Slice(objects, func(i, j int) bool {
return objects[i].LastModified.Before(objects[j].LastModified)
})
return objects, nil
}
func (s *Client) Upload(object string, reader io.Reader, size int64) error {
return s.UploadWithContext(context.Background(), object, reader, size)
}
func (s *Client) UploadWithContext(ctx context.Context, object string, reader io.Reader, size int64) error {
log.Debugf("upload S3 object [%s]", object)
if size <= 0 {
size = -1
}
n, err := s.Client.PutObjectWithContext(ctx, s.BucketName, object, reader, size, minio.PutObjectOptions{ContentType: "application/gzip"})
if err != nil {
return err
}
log.Debugf("uploaded S3 object [%s] of size [%d] bytes", object, n)
return nil
}
func (s *Client) Stat(object string) (*minio.ObjectInfo, error) {
log.Debugf("stat S3 object [%s]", object)
stat, err := s.Client.StatObject(s.BucketName, object, minio.StatObjectOptions{})
if err != nil {
return nil, err
}
return &stat, nil
}
func (s *Client) Download(object string) (*minio.Object, error) {
return s.DownloadWithContext(context.Background(), object)
}
func (s *Client) DownloadWithContext(ctx context.Context, object string) (*minio.Object, error) {
log.Debugf("download S3 object [%s]", object)
obj, err := s.Client.GetObjectWithContext(ctx, s.BucketName, object, minio.GetObjectOptions{})
if err != nil {
return nil, err
}
return obj, nil
}
| }
return nil
} | func (s *Client) Delete(object string) error {
log.Debugf("delete S3 object [%s]", object)
if err := s.Client.RemoveObject(s.BucketName, object); err != nil {
return err |
LucidDreaming.tsx | import {Plural, Trans} from '@lingui/react'
import {DataLink} from 'components/ui/DbLink'
import {Event, Events} from 'event'
import {Analyser} from 'parser/core/Analyser'
import {filter} from 'parser/core/filter'
import {dependency} from 'parser/core/Injectable'
import {Data} from 'parser/core/modules/Data'
import Suggestions, {SEVERITY, TieredSuggestion} from 'parser/core/modules/Suggestions'
import React, {Fragment} from 'react'
//assumptions listed after each severity
const SEVERITIES = {
USE_PERCENT_THRESHOLD: {
0.8: SEVERITY.MAJOR, //less than 20% of the available time is close to not using it at all or barely
0.4: SEVERITY.MEDIUM, //60% is not using it enough -- risks not having enough mana throughout the fight, but with cards, this may not be as applicable
0.2: SEVERITY.MINOR, //80% of the time is used to keep it on the radar, but not punish
},
}
export default class | extends Analyser {
static override handle = 'lucid'
static override dependencies = [
'suggestions',
]
@dependency private data!: Data
@dependency private suggestions!: Suggestions
private lastUse = 0
private uses = 0
private totalHeld = 0
override initialise() {
this.addEventHook(filter<Event>()
.source(this.parser.actor.id)
.type('action')
.action(this.data.actions.LUCID_DREAMING.id), this.onCastLucid)
this.addEventHook('complete', this.onComplete)
}
private onCastLucid(event: Events['action']) {
this.uses++
if (this.lastUse === 0) { this.lastUse = this.parser.pull.timestamp }
let _held = 0
if (this.uses === 1) {
// The first use, take holding as from the first minute of the fight
_held = event.timestamp - this.parser.pull.timestamp
} else {
// Take holding as from the time it comes off cooldown
_held = event.timestamp - this.lastUse - this.data.actions.LUCID_DREAMING.cooldown
}
if (_held > 0) {
this.totalHeld += _held
}
//update the last use
this.lastUse = event.timestamp
}
private onComplete() {
//uses missed reported in 1 decimal
const holdDuration = this.uses === 0 ? this.parser.pull.duration : this.totalHeld
const usesMissed = Math.floor(holdDuration / this.data.actions.LUCID_DREAMING.cooldown)
const notUsesPercent = usesMissed === 0 ? 0 : holdDuration/this.parser.pull.duration
this.suggestions.add(new TieredSuggestion({
icon: this.data.actions.LUCID_DREAMING.icon,
content: <Fragment>
<Trans id="ast.lucid-dreaming.suggestion.content">
Try to keep <DataLink action="LUCID_DREAMING" /> on cooldown for better MP management.
</Trans>
</Fragment>,
tiers: SEVERITIES.USE_PERCENT_THRESHOLD,
why: <Fragment>
<Trans id="ast.lucid-dreaming.suggestion.why">
<Plural value={usesMissed} one="# use" other="# uses" /> of Lucid Dreaming <Plural value={usesMissed} one="was" other="were" /> missed by holding it for at least a total of {this.parser.formatDuration(holdDuration)}.
</Trans>
</Fragment>,
value: notUsesPercent,
}))
}
}
| LucidDreaming |
middleware.go | package reqlog
import (
"fmt"
"net/http"
"reflect"
"time"
|
type config struct {
verbose bool
}
type Option func(c *config)
func WithVerbose(on bool) Option {
return func(c *config) {
c.verbose = on
}
}
func NewMiddleware(opts ...Option) treemux.MiddlewareFunc {
c := &config{
verbose: true,
}
for _, opt := range opts {
opt(c)
}
return c.Middleware
}
func (cfg *config) Middleware(next treemux.HandlerFunc) treemux.HandlerFunc {
return func(w http.ResponseWriter, req treemux.Request) error {
rec := &statusCodeRecorder{
ResponseWriter: w,
Code: http.StatusOK,
}
now := time.Now()
err := next(rec, req)
dur := time.Since(now)
if !cfg.verbose && rec.Code >= 200 && rec.Code < 300 && err == nil {
return nil
}
args := []interface{}{
"[treemux]",
now.Format(" 15:04:05.000 "),
formatStatus(rec.Code),
fmt.Sprintf(" %10s ", dur.Round(time.Microsecond)),
formatMethod(req.Method),
req.URL.String(),
}
if err != nil {
typ := reflect.TypeOf(err).String()
args = append(args,
"\t",
color.New(color.BgRed).Sprintf(" %s ", typ+": "+err.Error()),
)
}
fmt.Println(args...)
return err
}
}
//------------------------------------------------------------------------------
type statusCodeRecorder struct {
http.ResponseWriter
Code int
}
func (rec *statusCodeRecorder) WriteHeader(statusCode int) {
rec.Code = statusCode
rec.ResponseWriter.WriteHeader(statusCode)
}
//------------------------------------------------------------------------------
func formatStatus(code int) string {
return statusColor(code).Sprintf(" %d ", code)
}
func statusColor(code int) *color.Color {
switch {
case code >= 200 && code < 300:
return color.New(color.BgGreen, color.FgHiWhite)
case code >= 300 && code < 400:
return color.New(color.BgWhite, color.FgHiBlack)
case code >= 400 && code < 500:
return color.New(color.BgYellow, color.FgHiBlack)
default:
return color.New(color.BgRed, color.FgHiWhite)
}
}
func formatMethod(method string) string {
return methodColor(method).Sprintf(" %-7s ", method)
}
func methodColor(method string) *color.Color {
switch method {
case http.MethodGet:
return color.New(color.BgBlue, color.FgHiWhite)
case http.MethodPost:
return color.New(color.BgCyan, color.FgHiBlack)
case http.MethodPut:
return color.New(color.BgYellow, color.FgHiBlack)
case http.MethodDelete:
return color.New(color.BgRed, color.FgHiWhite)
case http.MethodPatch:
return color.New(color.BgGreen, color.FgHiWhite)
case http.MethodHead:
return color.New(color.BgMagenta, color.FgHiWhite)
default:
return color.New(color.BgWhite, color.FgHiBlack)
}
} | "github.com/fatih/color"
"github.com/uptrace/treemux"
) |
lint-type-overflow2.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
#![warn(overflowing_literals)]
#![warn(const_err)]
#![feature(rustc_attrs)]
#[allow(unused_variables)]
#[rustc_error]
fn | () { //~ ERROR: compilation successful
let x2: i8 = --128; //~ warn: literal out of range for i8
let x = -3.40282357e+38_f32; //~ warn: literal out of range for f32
let x = 3.40282357e+38_f32; //~ warn: literal out of range for f32
let x = -1.7976931348623159e+308_f64; //~ warn: literal out of range for f64
let x = 1.7976931348623159e+308_f64; //~ warn: literal out of range for f64
}
| main |
show_env.py | from __future__ import absolute_import, unicode_literals
from tox import reporter as report
| env_conf = config.envconfigs # this contains all environments
default = config.envlist # this only the defaults
ignore = {config.isolated_build_env, config.provision_tox_env}.union(default)
extra = [e for e in env_conf if e not in ignore] if all_envs else []
if description:
report.line("default environments:")
max_length = max(len(env) for env in (default + extra))
def report_env(e):
if description:
text = env_conf[e].description or "[no description]"
msg = "{} -> {}".format(e.ljust(max_length), text).strip()
else:
msg = e
report.line(msg)
for e in default:
report_env(e)
if all_envs and extra:
if description:
report.line("")
report.line("additional environments:")
for e in extra:
report_env(e) |
def show_envs(config, all_envs=False, description=False): |
urls.py | """django_vali URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include | """
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import RedirectView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^vali/', include('vali.urls')),
url(r'', RedirectView.as_view(url='/admin/'))
] | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) |
without_schema.rs | use crate::{integration_tests::AuxTestParams, BackEnd, Commands};
pub(crate) async fn | <B>(c: &mut Commands<B>, aux: AuxTestParams)
where
B: BackEnd
{
crate::integration_tests::schema::migrate_works(c, aux, 6).await
}
| migrate_works |
rkt_os_arch_test.go | // Copyright 2015 The rkt 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.
// +build host coreos src kvm
package main
import (
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/coreos/rkt/pkg/aci/acitest"
"github.com/coreos/rkt/tests/testutils"
"github.com/appc/spec/schema"
"github.com/appc/spec/schema/types"
)
type osArchTest struct {
image string
rktCmd string
expectedLine string
expectError bool
}
func osArchTestRemoveImages(tests []osArchTest) {
for _, tt := range tests {
os.Remove(tt.image)
}
}
func | (t *testing.T, ctx *testutils.RktRunCtx) []osArchTest {
var tests []osArchTest
defer osArchTestRemoveImages(tests)
manifestOSArch := schema.ImageManifest{
Name: "coreos.com/rkt-missing-os-arch-test",
App: &types.App{
Exec: types.Exec{
"/inspect",
"--print-msg=HelloWorld",
},
User: "0", Group: "0",
WorkingDirectory: "/",
},
Labels: types.Labels{
{"version", "1.25.0"},
},
}
// Copy the lables of the image manifest to use the common
// part in all test cases.
labels := make(types.Labels, len(manifestOSArch.Labels))
copy(labels, manifestOSArch.Labels)
// Test a valid image as a sanity check
manifestOSArch.Labels = append(
labels,
types.Label{"os", "linux"},
types.Label{"arch", "amd64"},
)
goodManifestFile := "good-manifest.json"
goodManifestStr, err := acitest.ImageManifestString(&manifestOSArch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := ioutil.WriteFile(goodManifestFile, []byte(goodManifestStr), 0600); err != nil {
t.Fatalf("Cannot write good manifest: %v", err)
}
defer os.Remove(goodManifestFile)
goodImage := patchTestACI("rkt-good-image.aci", fmt.Sprintf("--manifest=%s", goodManifestFile))
goodTest := osArchTest{
image: goodImage,
rktCmd: fmt.Sprintf("%s --insecure-options=image run --mds-register=false %s", ctx.Cmd(), goodImage),
expectedLine: "HelloWorld",
expectError: false,
}
tests = append(tests, goodTest)
// Test an image with a missing os label
manifestOSArch.Labels = append(labels, types.Label{"arch", "amd64"})
missingOSManifestFile := "missingOS-manifest.json"
missingOSManifestStr, err := acitest.ImageManifestString(&manifestOSArch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := ioutil.WriteFile(missingOSManifestFile, []byte(missingOSManifestStr), 0600); err != nil {
t.Fatalf("Cannot write missing OS manifest: %v", err)
}
defer os.Remove(missingOSManifestFile)
missingOSImage := patchTestACI("rkt-missing-os.aci", fmt.Sprintf("--manifest=%s", missingOSManifestFile))
missingOSTest := osArchTest{
image: missingOSImage,
rktCmd: fmt.Sprintf("%s --insecure-options=image run %s", ctx.Cmd(), missingOSImage),
expectedLine: "missing os label in the image manifest",
expectError: true,
}
tests = append(tests, missingOSTest)
// Test an image with a missing arch label
manifestOSArch.Labels = append(labels, types.Label{"os", "linux"})
missingArchManifestFile := "missingArch-manifest.json"
missingArchManifestStr, err := acitest.ImageManifestString(&manifestOSArch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := ioutil.WriteFile(missingArchManifestFile, []byte(missingArchManifestStr), 0600); err != nil {
t.Fatalf("Cannot write missing Arch manifest: %v", err)
}
defer os.Remove(missingArchManifestFile)
missingArchImage := patchTestACI("rkt-missing-arch.aci", fmt.Sprintf("--manifest=%s", missingArchManifestFile))
missingArchTest := osArchTest{
image: missingArchImage,
rktCmd: fmt.Sprintf("%s --insecure-options=image run %s", ctx.Cmd(), missingArchImage),
expectedLine: "missing arch label in the image manifest",
expectError: true,
}
tests = append(tests, missingArchTest)
// Test an image with an invalid os
manifestOSArch.Labels = append(
labels,
types.Label{"os", "freebsd"},
types.Label{"arch", "amd64"},
)
invalidOSManifestFile := "invalid-os-manifest.json"
invalidOSManifestStr, err := acitest.ImageManifestString(&manifestOSArch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := ioutil.WriteFile(invalidOSManifestFile, []byte(invalidOSManifestStr), 0600); err != nil {
t.Fatalf("Cannot write invalid os manifest: %v", err)
}
defer os.Remove(invalidOSManifestFile)
invalidOSImage := patchTestACI("rkt-invalid-os.aci", fmt.Sprintf("--manifest=%s", invalidOSManifestFile))
invalidOSTest := osArchTest{
image: invalidOSImage,
rktCmd: fmt.Sprintf("%s --insecure-options=image run %s", ctx.Cmd(), invalidOSImage),
expectedLine: `bad os "freebsd"`,
expectError: true,
}
tests = append(tests, invalidOSTest)
// Test an image with an invalid arch
manifestOSArch.Labels = append(
labels,
types.Label{"os", "linux"},
types.Label{"arch", "armv5l"},
)
invalidArchManifestFile := "invalid-arch-manifest.json"
invalidArchManifestStr, err := acitest.ImageManifestString(&manifestOSArch)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := ioutil.WriteFile(invalidArchManifestFile, []byte(invalidArchManifestStr), 0600); err != nil {
t.Fatalf("Cannot write invalid arch manifest: %v", err)
}
defer os.Remove(invalidArchManifestFile)
retTests := tests
tests = nil
return retTests
}
// TestMissingOrInvalidOSArchRun tests that rkt errors out when it tries to run
// an image (not present in the store) with a missing or unsupported os/arch
func TestMissingOrInvalidOSArchRun(t *testing.T) {
ctx := testutils.NewRktRunCtx()
defer ctx.Cleanup()
tests := getMissingOrInvalidTests(t, ctx)
defer osArchTestRemoveImages(tests)
for i, tt := range tests {
t.Logf("Running test #%v: %v", i, tt.rktCmd)
runRktAndCheckOutput(t, tt.rktCmd, tt.expectedLine, tt.expectError)
}
}
// TestMissingOrInvalidOSArchFetchRun tests that rkt errors out when it tries
// to run an already fetched image with a missing or unsupported os/arch
func TestMissingOrInvalidOSArchFetchRun(t *testing.T) {
ctx := testutils.NewRktRunCtx()
defer ctx.Cleanup()
tests := getMissingOrInvalidTests(t, ctx)
defer osArchTestRemoveImages(tests)
for i, tt := range tests {
imgHash, err := importImageAndFetchHash(t, ctx, "", tt.image)
if err != nil {
t.Fatalf("%v", err)
}
rktCmd := fmt.Sprintf("%s run --mds-register=false %s", ctx.Cmd(), imgHash)
t.Logf("Running test #%v: %v", i, rktCmd)
runRktAndCheckOutput(t, rktCmd, tt.expectedLine, tt.expectError)
}
}
| getMissingOrInvalidTests |
mod.rs | #![allow(dead_code)]
extern crate hex;
pub use bitcoin::{
formatter::{Formattable, TryFormattable},
types::*,
};
pub use btc_parachain_runtime::{AccountId, BlockNumber, Call, Event, Runtime};
pub use btc_relay::{BtcAddress, BtcPublicKey};
use frame_support::traits::GenesisBuild;
pub use frame_support::{assert_err, assert_noop, assert_ok, dispatch::DispatchResultWithPostInfo};
pub use mocktopus::mocking::*;
pub use security::{ErrorCode, StatusCode};
pub use sp_arithmetic::{FixedI128, FixedPointNumber, FixedU128};
pub use sp_core::{H160, H256, U256};
pub use sp_runtime::traits::{Dispatchable, One, Zero};
pub use sp_std::convert::TryInto;
pub use vault_registry::CurrencySource;
pub use issue::IssueRequest;
pub use nomination::Nominator;
pub use redeem::RedeemRequest;
pub use refund::RefundRequest;
pub use replace::ReplaceRequest;
pub use reward::Rewards;
pub use sp_runtime::AccountId32;
pub use std::convert::TryFrom;
pub use vault_registry::{Vault, VaultStatus};
pub mod issue_testing_utils;
pub mod nomination_testing_utils;
pub mod redeem_testing_utils;
pub mod reward_testing_utils;
pub const ALICE: [u8; 32] = [0u8; 32];
pub const BOB: [u8; 32] = [1u8; 32];
pub const CAROL: [u8; 32] = [2u8; 32];
pub const DAVE: [u8; 32] = [10u8; 32];
pub const EVE: [u8; 32] = [11u8; 32];
pub const FRANK: [u8; 32] = [12u8; 32];
pub const GRACE: [u8; 32] = [13u8; 32];
pub const MAINTAINER: [u8; 32] = [5u8; 32];
pub const FAUCET: [u8; 32] = [128u8; 32];
pub const DUMMY: [u8; 32] = [255u8; 32];
pub const INITIAL_BALANCE: u128 = 1_000_000_000_000;
pub const INITIAL_LIQUIDATION_VAULT_BALANCE: u128 = 0;
pub const DEFAULT_USER_FREE_BALANCE: u128 = 1_000_000;
pub const DEFAULT_USER_LOCKED_BALANCE: u128 = 100_000;
pub const DEFAULT_USER_FREE_TOKENS: u128 = 10_000_000;
pub const DEFAULT_USER_LOCKED_TOKENS: u128 = 1000;
pub const DEFAULT_VAULT_TO_BE_ISSUED: u128 = 10_000;
pub const DEFAULT_VAULT_ISSUED: u128 = 100_000;
pub const DEFAULT_VAULT_TO_BE_REDEEMED: u128 = 20_000;
pub const DEFAULT_VAULT_BACKING_COLLATERAL: u128 = 1_000_000;
pub const DEFAULT_VAULT_GRIEFING_COLLATERAL: u128 = 30_000;
pub const DEFAULT_VAULT_FREE_BALANCE: u128 = 200_000;
pub const DEFAULT_VAULT_FREE_TOKENS: u128 = 0;
pub const DEFAULT_VAULT_REPLACE_COLLATERAL: u128 = 20_000;
pub const DEFAULT_VAULT_TO_BE_REPLACED: u128 = 40_000;
pub const DEFAULT_NOMINATION_TOTAL_NOMINATED_COLLATERAL: u128 = 0;
pub const DEFAULT_NOMINATION_COLLATERAL_TO_BE_WITHDRAWN: u128 = 0;
pub const CONFIRMATIONS: u32 = 6;
pub type BTCRelayCall = btc_relay::Call<Runtime>;
pub type BTCRelayPallet = btc_relay::Pallet<Runtime>;
pub type BTCRelayError = btc_relay::Error<Runtime>;
pub type BTCRelayEvent = btc_relay::Event<Runtime>;
pub type CollateralError = currency::Error<Runtime, currency::Collateral>;
pub type CollateralPallet = currency::Pallet<Runtime, currency::Collateral>;
pub type ExchangeRateOracleCall = exchange_rate_oracle::Call<Runtime>;
pub type ExchangeRateOraclePallet = exchange_rate_oracle::Pallet<Runtime>;
pub type FeeCall = fee::Call<Runtime>;
pub type FeeError = fee::Error<Runtime>;
pub type FeePallet = fee::Pallet<Runtime>;
pub type RewardCollateralVaultPallet = reward::Pallet<Runtime, reward::CollateralVault>;
pub type RewardWrappedVaultPallet = reward::Pallet<Runtime, reward::WrappedVault>;
pub type RewardCollateralRelayerPallet = reward::Pallet<Runtime, reward::CollateralRelayer>;
pub type RewardWrappedRelayerPallet = reward::Pallet<Runtime, reward::WrappedRelayer>;
pub type IssueCall = issue::Call<Runtime>;
pub type IssuePallet = issue::Pallet<Runtime>;
pub type IssueEvent = issue::Event<Runtime>;
pub type IssueError = issue::Error<Runtime>;
pub type RefundCall = refund::Call<Runtime>;
pub type RefundPallet = refund::Pallet<Runtime>;
pub type RefundEvent = refund::Event<Runtime>;
pub type RedeemCall = redeem::Call<Runtime>;
pub type RedeemPallet = redeem::Pallet<Runtime>;
pub type RedeemError = redeem::Error<Runtime>;
pub type RedeemEvent = redeem::Event<Runtime>;
pub type ReplaceCall = replace::Call<Runtime>;
pub type ReplaceEvent = replace::Event<Runtime>;
pub type ReplaceError = replace::Error<Runtime>;
pub type ReplacePallet = replace::Pallet<Runtime>;
pub type SecurityError = security::Error<Runtime>;
pub type SecurityPallet = security::Pallet<Runtime>;
pub type SlaPallet = sla::Pallet<Runtime>;
pub type SlaCall = sla::Call<Runtime>;
pub type StakedRelayersCall = staked_relayers::Call<Runtime>;
pub type StakedRelayersPallet = staked_relayers::Pallet<Runtime>;
pub type SystemModule = frame_system::Pallet<Runtime>;
pub type TreasuryPallet = currency::Pallet<Runtime, currency::Wrapped>;
pub type VaultRegistryCall = vault_registry::Call<Runtime>;
pub type VaultRegistryError = vault_registry::Error<Runtime>;
pub type VaultRegistryPallet = vault_registry::Pallet<Runtime>;
pub type NominationCall = nomination::Call<Runtime>;
pub type NominationError = nomination::Error<Runtime>;
pub type NominationEvent = nomination::Event<Runtime>;
pub type NominationPallet = nomination::Pallet<Runtime>;
pub fn default_user_state() -> UserData {
UserData {
free_balance: DEFAULT_USER_FREE_BALANCE,
locked_balance: DEFAULT_USER_LOCKED_BALANCE,
locked_tokens: DEFAULT_USER_LOCKED_TOKENS,
free_tokens: DEFAULT_USER_FREE_TOKENS,
}
}
pub fn default_vault_state() -> CoreVaultData {
CoreVaultData {
to_be_issued: DEFAULT_VAULT_TO_BE_ISSUED,
issued: DEFAULT_VAULT_ISSUED,
to_be_redeemed: DEFAULT_VAULT_TO_BE_REDEEMED,
backing_collateral: DEFAULT_VAULT_BACKING_COLLATERAL,
griefing_collateral: DEFAULT_VAULT_GRIEFING_COLLATERAL,
free_balance: DEFAULT_VAULT_FREE_BALANCE,
free_tokens: 0,
liquidated_collateral: 0,
replace_collateral: DEFAULT_VAULT_REPLACE_COLLATERAL,
to_be_replaced: DEFAULT_VAULT_TO_BE_REPLACED,
}
}
pub fn default_operator_state() -> CoreOperatorData {
CoreOperatorData {
collateral_to_be_withdrawn: DEFAULT_NOMINATION_COLLATERAL_TO_BE_WITHDRAWN,
}
}
pub fn root() -> <Runtime as frame_system::Config>::Origin {
<Runtime as frame_system::Config>::Origin::root()
}
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::Origin {
<Runtime as frame_system::Config>::Origin::signed(account_id)
}
pub fn account_of(address: [u8; 32]) -> AccountId {
AccountId::from(address)
}
#[derive(Debug, PartialEq, Default, Clone)]
pub struct UserData {
pub free_balance: u128,
pub locked_balance: u128,
pub locked_tokens: u128,
pub free_tokens: u128,
}
impl UserData {
#[allow(dead_code)]
pub fn get(id: [u8; 32]) -> Self {
let account_id = account_of(id);
Self {
free_balance: CollateralPallet::get_free_balance(&account_id),
locked_balance: CollateralPallet::get_reserved_balance(&account_id),
locked_tokens: TreasuryPallet::get_reserved_balance(&account_id),
free_tokens: TreasuryPallet::get_free_balance(&account_id),
}
}
#[allow(dead_code)]
pub fn force_to(id: [u8; 32], new: Self) -> Self {
let old = Self::get(id);
let account_id = account_of(id);
// set tokens to 0
TreasuryPallet::lock(&account_id, old.free_tokens).unwrap();
TreasuryPallet::burn(&account_id, old.free_tokens + old.locked_tokens).unwrap();
// set free balance:
CollateralPallet::transfer(&account_id, &account_of(FAUCET), old.free_balance).unwrap();
CollateralPallet::transfer(&account_of(FAUCET), &account_id, new.free_balance).unwrap();
// set locked balance:
CollateralPallet::slash(account_id.clone(), account_of(FAUCET), old.locked_balance).unwrap();
CollateralPallet::transfer(&account_of(FAUCET), &account_id, new.locked_balance).unwrap();
CollateralPallet::lock(&account_id, new.locked_balance).unwrap();
// set free_tokens
TreasuryPallet::mint(account_id.clone(), new.free_tokens);
// set locked_tokens
TreasuryPallet::mint(account_id.clone(), new.locked_tokens);
TreasuryPallet::lock(&account_id, new.locked_tokens).unwrap();
// sanity check:
assert_eq!(Self::get(id), new);
new
}
}
#[derive(Debug, Default, Clone)]
pub struct FeePool {
pub vault_collateral_rewards: u128,
pub vault_wrapped_rewards: u128,
pub relayer_collateral_rewards: u128,
pub relayer_wrapped_rewards: u128,
}
fn abs_difference<T: std::ops::Sub<Output = T> + Ord>(x: T, y: T) -> T {
if x < y {
y - x
} else {
x - y | fn eq(&self, rhs: &Self) -> bool {
abs_difference(self.vault_collateral_rewards, rhs.vault_collateral_rewards) <= 1
&& abs_difference(self.vault_wrapped_rewards, rhs.vault_wrapped_rewards) <= 1
&& abs_difference(self.relayer_collateral_rewards, rhs.relayer_collateral_rewards) <= 1
&& abs_difference(self.relayer_wrapped_rewards, rhs.relayer_wrapped_rewards) <= 1
}
}
impl FeePool {
pub fn get() -> Self {
Self {
vault_collateral_rewards: RewardCollateralVaultPallet::get_total_rewards().unwrap() as u128,
vault_wrapped_rewards: RewardWrappedVaultPallet::get_total_rewards().unwrap() as u128,
relayer_collateral_rewards: RewardCollateralRelayerPallet::get_total_rewards().unwrap() as u128,
relayer_wrapped_rewards: RewardWrappedRelayerPallet::get_total_rewards().unwrap() as u128,
}
}
}
#[derive(Debug, PartialEq, Default, Clone)]
pub struct CoreVaultData {
pub to_be_issued: u128,
pub issued: u128,
pub to_be_redeemed: u128,
pub backing_collateral: u128,
pub griefing_collateral: u128,
pub liquidated_collateral: u128,
pub free_balance: u128,
pub free_tokens: u128,
pub to_be_replaced: u128,
pub replace_collateral: u128,
}
impl CoreVaultData {
#[allow(dead_code)]
pub fn vault(vault: [u8; 32]) -> Self {
let account_id = account_of(vault);
let vault = VaultRegistryPallet::get_vault_from_id(&account_id).unwrap();
Self {
to_be_issued: vault.to_be_issued_tokens,
issued: vault.issued_tokens,
to_be_redeemed: vault.to_be_redeemed_tokens,
backing_collateral: CurrencySource::<Runtime>::Collateral(account_id.clone())
.current_balance()
.unwrap(),
griefing_collateral: CurrencySource::<Runtime>::Griefing(account_id.clone())
.current_balance()
.unwrap(),
liquidated_collateral: vault.liquidated_collateral,
free_balance: CollateralPallet::get_free_balance(&account_id),
free_tokens: TreasuryPallet::get_free_balance(&account_id),
to_be_replaced: vault.to_be_replaced_tokens,
replace_collateral: vault.replace_collateral,
}
}
#[allow(dead_code)]
pub fn liquidation_vault() -> Self {
let account_id = VaultRegistryPallet::liquidation_vault_account_id();
let vault = VaultRegistryPallet::get_liquidation_vault();
Self {
to_be_issued: vault.to_be_issued_tokens,
issued: vault.issued_tokens,
to_be_redeemed: vault.to_be_redeemed_tokens,
backing_collateral: CurrencySource::<Runtime>::LiquidationVault.current_balance().unwrap(),
griefing_collateral: 0,
free_balance: CollateralPallet::get_free_balance(&account_id),
free_tokens: TreasuryPallet::get_free_balance(&account_id),
liquidated_collateral: 0,
to_be_replaced: 0,
replace_collateral: 0,
}
}
#[allow(dead_code)]
pub fn force_to(vault: [u8; 32], state: CoreVaultData) {
// replace collateral is part of griefing collateral, so it needs to smaller or equal
assert!(state.griefing_collateral >= state.replace_collateral);
assert!(state.to_be_replaced + state.to_be_redeemed <= state.issued);
// register vault if not yet registered
try_register_vault(100, vault);
// temporarily give vault a lot of backing collateral so we can set issued & to-be-issued to whatever we want
VaultRegistryPallet::transfer_funds(
CurrencySource::FreeBalance(account_of(FAUCET)),
CurrencySource::Collateral(account_of(vault)),
CollateralPallet::get_free_balance(&account_of(FAUCET)),
)
.unwrap();
let current = CoreVaultData::vault(vault);
// set all token types to 0
assert_ok!(VaultRegistryPallet::decrease_to_be_issued_tokens(
&account_of(vault),
current.to_be_issued
));
assert_ok!(VaultRegistryPallet::decrease_to_be_redeemed_tokens(
&account_of(vault),
current.to_be_redeemed
));
assert_ok!(VaultRegistryPallet::try_increase_to_be_redeemed_tokens(
&account_of(vault),
current.issued
));
assert_ok!(VaultRegistryPallet::decrease_tokens(
&account_of(vault),
&account_of(DUMMY),
current.issued,
));
assert_ok!(VaultRegistryPallet::decrease_to_be_replaced_tokens(
&account_of(vault),
current.to_be_replaced,
));
assert_ok!(TreasuryPallet::lock(&account_of(vault), current.free_tokens));
assert_ok!(TreasuryPallet::burn(&account_of(vault), current.free_tokens));
// set to-be-issued
assert_ok!(VaultRegistryPallet::try_increase_to_be_issued_tokens(
&account_of(vault),
state.to_be_issued
));
// set issued (2 steps)
assert_ok!(VaultRegistryPallet::try_increase_to_be_issued_tokens(
&account_of(vault),
state.issued
));
assert_ok!(VaultRegistryPallet::issue_tokens(&account_of(vault), state.issued));
// set to-be-redeemed
assert_ok!(VaultRegistryPallet::try_increase_to_be_redeemed_tokens(
&account_of(vault),
state.to_be_redeemed
));
// set to-be-replaced:
assert_ok!(VaultRegistryPallet::try_increase_to_be_replaced_tokens(
&account_of(vault),
state.to_be_replaced,
state.replace_collateral
));
// set free tokens:
TreasuryPallet::mint(account_of(vault), state.free_tokens);
// clear all balances
VaultRegistryPallet::transfer_funds(
CurrencySource::Collateral(account_of(vault)),
CurrencySource::FreeBalance(account_of(FAUCET)),
CurrencySource::<Runtime>::Collateral(account_of(vault))
.current_balance()
.unwrap(),
)
.unwrap();
VaultRegistryPallet::transfer_funds(
CurrencySource::Griefing(account_of(vault)),
CurrencySource::FreeBalance(account_of(FAUCET)),
CurrencySource::<Runtime>::Griefing(account_of(vault))
.current_balance()
.unwrap(),
)
.unwrap();
VaultRegistryPallet::transfer_funds(
CurrencySource::FreeBalance(account_of(vault)),
CurrencySource::FreeBalance(account_of(FAUCET)),
CurrencySource::<Runtime>::FreeBalance(account_of(vault))
.current_balance()
.unwrap(),
)
.unwrap();
// now set balances to desired values
VaultRegistryPallet::transfer_funds(
CurrencySource::FreeBalance(account_of(FAUCET)),
CurrencySource::Collateral(account_of(vault)),
state.backing_collateral,
)
.unwrap();
VaultRegistryPallet::transfer_funds(
CurrencySource::FreeBalance(account_of(FAUCET)),
CurrencySource::Griefing(account_of(vault)),
state.griefing_collateral,
)
.unwrap();
VaultRegistryPallet::transfer_funds(
CurrencySource::FreeBalance(account_of(FAUCET)),
CurrencySource::FreeBalance(account_of(vault)),
state.free_balance,
)
.unwrap();
// check that we achieved the desired state
assert_eq!(CoreVaultData::vault(vault), state);
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct CoreNominatorData {
pub collateral_to_be_withdrawn: u128,
}
impl Default for CoreNominatorData {
fn default() -> Self {
CoreNominatorData {
collateral_to_be_withdrawn: 0,
}
}
}
impl CoreNominatorData {}
#[derive(Debug, PartialEq, Clone)]
pub struct CoreOperatorData {
pub collateral_to_be_withdrawn: u128,
}
impl Default for CoreOperatorData {
fn default() -> Self {
default_operator_state()
}
}
impl CoreOperatorData {
pub fn operator(operator: [u8; 32]) -> Self {
let account_id = account_of(operator);
match NominationPallet::is_operator(&account_id) {
Ok(true) => Self {
collateral_to_be_withdrawn: NominationPallet::get_collateral_to_be_withdrawn(&account_id).unwrap(),
},
Ok(false) => default_operator_state(),
Err(_) => default_operator_state(),
}
}
}
#[derive(Debug, PartialEq, Clone)]
pub struct ParachainState {
user: UserData,
vault: CoreVaultData,
liquidation_vault: CoreVaultData,
fee_pool: FeePool,
}
impl Default for ParachainState {
fn default() -> Self {
Self {
user: default_user_state(),
vault: default_vault_state(),
liquidation_vault: CoreVaultData {
free_balance: INITIAL_LIQUIDATION_VAULT_BALANCE,
..Default::default()
},
fee_pool: Default::default(),
}
}
}
impl ParachainState {
pub fn get() -> Self {
Self {
user: UserData::get(ALICE),
vault: CoreVaultData::vault(BOB),
liquidation_vault: CoreVaultData::liquidation_vault(),
fee_pool: FeePool::get(),
}
}
pub fn with_changes(
&self,
f: impl FnOnce(&mut UserData, &mut CoreVaultData, &mut CoreVaultData, &mut FeePool),
) -> Self {
let mut state = self.clone();
f(
&mut state.user,
&mut state.vault,
&mut state.liquidation_vault,
&mut state.fee_pool,
);
state
}
}
// todo: merge with ParachainState
#[derive(Debug, PartialEq, Clone)]
pub struct ParachainTwoVaultState {
vault1: CoreVaultData,
vault2: CoreVaultData,
liquidation_vault: CoreVaultData,
}
impl Default for ParachainTwoVaultState {
fn default() -> Self {
Self {
vault1: default_vault_state(),
vault2: default_vault_state(),
liquidation_vault: CoreVaultData {
free_balance: INITIAL_LIQUIDATION_VAULT_BALANCE,
..Default::default()
},
}
}
}
impl ParachainTwoVaultState {
pub fn get() -> Self {
Self {
vault1: CoreVaultData::vault(BOB),
vault2: CoreVaultData::vault(CAROL),
liquidation_vault: CoreVaultData::liquidation_vault(),
}
}
pub fn with_changes(&self, f: impl FnOnce(&mut CoreVaultData, &mut CoreVaultData, &mut CoreVaultData)) -> Self {
let mut state = self.clone();
f(&mut state.vault1, &mut state.vault2, &mut state.liquidation_vault);
state
}
}
#[allow(dead_code)]
pub fn drop_exchange_rate_and_liquidate(vault: [u8; 32]) {
assert_ok!(ExchangeRateOraclePallet::_set_exchange_rate(
FixedU128::checked_from_integer(10_000_000_000).unwrap()
));
assert_ok!(VaultRegistryPallet::liquidate_vault(&account_of(vault)));
}
#[allow(dead_code)]
pub fn set_default_thresholds() {
let secure = FixedU128::checked_from_rational(150, 100).unwrap();
let premium = FixedU128::checked_from_rational(135, 100).unwrap();
let liquidation = FixedU128::checked_from_rational(110, 100).unwrap();
VaultRegistryPallet::set_secure_collateral_threshold(secure);
VaultRegistryPallet::set_premium_redeem_threshold(premium);
VaultRegistryPallet::set_liquidation_collateral_threshold(liquidation);
}
pub fn dummy_public_key() -> BtcPublicKey {
BtcPublicKey([
2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180,
119, 54, 243, 97, 173, 150, 161, 169, 230,
])
}
#[allow(dead_code)]
pub fn try_register_vault(collateral: u128, vault: [u8; 32]) {
if VaultRegistryPallet::get_vault_from_id(&account_of(vault)).is_err() {
assert_ok!(
Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key()))
.dispatch(origin_of(account_of(vault)))
);
};
}
#[allow(dead_code)]
pub fn try_register_operator(operator: [u8; 32]) {
if NominationPallet::get_operator_from_id(&account_of(operator)).is_err() {
assert_ok!(Call::Nomination(NominationCall::opt_in_to_nomination()).dispatch(origin_of(account_of(operator))));
};
}
#[allow(dead_code)]
pub fn force_issue_tokens(user: [u8; 32], vault: [u8; 32], collateral: u128, tokens: u128) {
// register the vault
assert_ok!(
Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key()))
.dispatch(origin_of(account_of(vault)))
);
// increase to be issued tokens
assert_ok!(VaultRegistryPallet::try_increase_to_be_issued_tokens(
&account_of(vault),
tokens
));
// issue tokens
assert_ok!(VaultRegistryPallet::issue_tokens(&account_of(vault), tokens));
// mint tokens to the user
currency::Pallet::<Runtime, currency::Wrapped>::mint(user.into(), tokens);
}
#[allow(dead_code)]
pub fn required_collateral_for_issue(issued_tokens: u128) -> u128 {
let fee_amount_btc = FeePallet::get_issue_fee(issued_tokens).unwrap();
let total_amount_btc = issued_tokens + fee_amount_btc;
VaultRegistryPallet::get_required_collateral_for_wrapped(total_amount_btc).unwrap()
}
pub fn assert_store_main_chain_header_event(height: u32, hash: H256Le, relayer: AccountId) {
let store_event = Event::btc_relay(BTCRelayEvent::StoreMainChainHeader(height, hash, relayer));
let events = SystemModule::events();
// store only main chain header
assert!(events.iter().any(|a| a.event == store_event));
}
#[derive(Default, Clone, Debug)]
pub struct TransactionGenerator {
address: BtcAddress,
amount: u128,
return_data: Option<H256>,
script: Vec<u8>,
confirmations: u32,
relayer: Option<[u8; 32]>,
}
impl TransactionGenerator {
pub fn new() -> Self {
Self {
relayer: None,
confirmations: 7,
amount: 100,
script: vec![
0, 71, 48, 68, 2, 32, 91, 128, 41, 150, 96, 53, 187, 63, 230, 129, 53, 234, 210, 186, 21, 187, 98, 38,
255, 112, 30, 27, 228, 29, 132, 140, 155, 62, 123, 216, 232, 168, 2, 32, 72, 126, 179, 207, 142, 8, 99,
8, 32, 78, 244, 166, 106, 160, 207, 227, 61, 210, 172, 234, 234, 93, 59, 159, 79, 12, 194, 240, 212, 3,
120, 50, 1, 71, 81, 33, 3, 113, 209, 131, 177, 9, 29, 242, 229, 15, 217, 247, 165, 78, 111, 80, 79, 50,
200, 117, 80, 30, 233, 210, 167, 133, 175, 62, 253, 134, 127, 212, 51, 33, 2, 128, 200, 184, 235, 148,
25, 43, 34, 28, 173, 55, 54, 189, 164, 187, 243, 243, 152, 7, 84, 210, 85, 156, 238, 77, 97, 188, 240,
162, 197, 105, 62, 82, 174,
],
return_data: Some(H256::zero()),
..Default::default()
}
}
pub fn with_address(&mut self, address: BtcAddress) -> &mut Self {
self.address = address;
self
}
pub fn with_amount(&mut self, amount: u128) -> &mut Self {
self.amount = amount;
self
}
pub fn with_op_return(&mut self, op_return: Option<H256>) -> &mut Self {
self.return_data = op_return;
self
}
pub fn with_script(&mut self, script: &[u8]) -> &mut Self {
self.script = script.to_vec();
self
}
pub fn with_confirmations(&mut self, confirmations: u32) -> &mut Self {
self.confirmations = confirmations;
self
}
pub fn with_relayer(&mut self, relayer: Option<[u8; 32]>) -> &mut Self {
self.relayer = relayer;
self
}
pub fn mine(&self) -> (H256Le, u32, Vec<u8>, Vec<u8>, Transaction) {
let mut height = 1;
let extra_confirmations = self.confirmations - 1;
// initialize BTC Relay with one block
let init_block = BlockBuilder::new()
.with_version(2)
.with_coinbase(&self.address, 50, 3)
.with_timestamp(1588813835)
.mine(U256::from(2).pow(254.into()))
.unwrap();
let raw_init_block_header = RawBlockHeader::from_bytes(&init_block.header.try_format().unwrap())
.expect("could not serialize block header");
match BTCRelayPallet::initialize(account_of(ALICE), raw_init_block_header, height) {
Ok(_) => {}
Err(e) if e == BTCRelayError::AlreadyInitialized.into() => {}
_ => panic!("Failed to initialize btc relay"),
}
height = BTCRelayPallet::get_best_block_height() + 1;
let value = self.amount as i64;
let mut transaction_builder = TransactionBuilder::new();
transaction_builder.with_version(2);
transaction_builder.add_input(
TransactionInputBuilder::new()
.with_coinbase(false)
.with_script(&self.script)
.with_previous_hash(init_block.transactions[0].hash())
.build(),
);
transaction_builder.add_output(TransactionOutput::payment(value, &self.address));
if let Some(op_return_data) = self.return_data {
transaction_builder.add_output(TransactionOutput::op_return(0, op_return_data.as_bytes()));
}
let transaction = transaction_builder.build();
let prev_hash = BTCRelayPallet::get_best_block();
let block = BlockBuilder::new()
.with_previous_hash(prev_hash)
.with_version(2)
.with_coinbase(&self.address, 50, 3)
.with_timestamp(1588814835)
.add_transaction(transaction.clone())
.mine(U256::from(2).pow(254.into()))
.unwrap();
let raw_block_header =
RawBlockHeader::from_bytes(&block.header.try_format().unwrap()).expect("could not serialize block header");
let tx_id = transaction.tx_id();
let tx_block_height = height;
let proof = block.merkle_proof(&[tx_id]).unwrap();
let bytes_proof = proof.try_format().unwrap();
let raw_tx = transaction.format_with(true);
self.relay(height, &block, raw_block_header);
// Mine six new blocks to get over required confirmations
let mut prev_block_hash = block.header.hash().unwrap();
let mut timestamp = 1588814835;
for _ in 0..extra_confirmations {
height += 1;
timestamp += 1000;
let conf_block = BlockBuilder::new()
.with_previous_hash(prev_block_hash)
.with_version(2)
.with_coinbase(&self.address, 50, 3)
.with_timestamp(timestamp)
.mine(U256::from(2).pow(254.into()))
.unwrap();
let raw_conf_block_header = RawBlockHeader::from_bytes(&conf_block.header.try_format().unwrap())
.expect("could not serialize block header");
self.relay(height, &conf_block, raw_conf_block_header);
prev_block_hash = conf_block.header.hash().unwrap();
}
(tx_id, tx_block_height, bytes_proof, raw_tx, transaction)
}
fn relay(&self, height: u32, block: &Block, raw_block_header: RawBlockHeader) {
if let Some(relayer) = self.relayer {
assert_ok!(
Call::StakedRelayers(StakedRelayersCall::store_block_header(raw_block_header))
.dispatch(origin_of(account_of(relayer)))
);
assert_store_main_chain_header_event(height, block.header.hash().unwrap(), account_of(relayer));
} else {
// bypass staked relayer module
assert_ok!(BTCRelayPallet::store_block_header(&account_of(ALICE), raw_block_header));
assert_store_main_chain_header_event(height, block.header.hash().unwrap(), account_of(ALICE));
}
}
}
#[allow(dead_code)]
pub fn generate_transaction_and_mine(
address: BtcAddress,
amount: u128,
return_data: Option<H256>,
) -> (H256Le, u32, Vec<u8>, Vec<u8>) {
let (tx_id, height, proof, raw_tx, _) = TransactionGenerator::new()
.with_address(address)
.with_amount(amount)
.with_op_return(return_data)
.mine();
(tx_id, height, proof, raw_tx)
}
pub struct ExtBuilder {
test_externalities: sp_io::TestExternalities,
}
impl ExtBuilder {
pub fn build() -> Self {
let mut storage = frame_system::GenesisConfig::default()
.build_storage::<Runtime>()
.unwrap();
pallet_balances::GenesisConfig::<Runtime, pallet_balances::Instance1> {
balances: vec![
(account_of(ALICE), INITIAL_BALANCE),
(account_of(BOB), INITIAL_BALANCE),
(account_of(CAROL), INITIAL_BALANCE),
(account_of(DAVE), INITIAL_BALANCE),
(account_of(EVE), INITIAL_BALANCE),
(account_of(FRANK), INITIAL_BALANCE),
(account_of(GRACE), INITIAL_BALANCE),
(account_of(FAUCET), 1 << 60),
],
}
.assimilate_storage(&mut storage)
.unwrap();
pallet_balances::GenesisConfig::<Runtime, pallet_balances::Instance2> { balances: vec![] }
.assimilate_storage(&mut storage)
.unwrap();
exchange_rate_oracle::GenesisConfig::<Runtime> {
authorized_oracles: vec![(account_of(BOB), BOB.to_vec())],
max_delay: 3600000, // one hour
}
.assimilate_storage(&mut storage)
.unwrap();
btc_relay::GenesisConfig::<Runtime> {
bitcoin_confirmations: CONFIRMATIONS,
parachain_confirmations: CONFIRMATIONS,
disable_difficulty_check: false,
disable_inclusion_check: false,
disable_op_return_check: false,
}
.assimilate_storage(&mut storage)
.unwrap();
vault_registry::GenesisConfig::<Runtime> {
minimum_collateral_vault: 0,
punishment_delay: 8,
secure_collateral_threshold: FixedU128::checked_from_rational(150, 100).unwrap(),
premium_redeem_threshold: FixedU128::checked_from_rational(135, 100).unwrap(),
liquidation_collateral_threshold: FixedU128::checked_from_rational(110, 100).unwrap(),
}
.assimilate_storage(&mut storage)
.unwrap();
issue::GenesisConfig::<Runtime> { issue_period: 10 }
.assimilate_storage(&mut storage)
.unwrap();
redeem::GenesisConfig::<Runtime> {
redeem_transaction_size: 400,
redeem_period: 10,
redeem_btc_dust_value: 1,
}
.assimilate_storage(&mut storage)
.unwrap();
replace::GenesisConfig::<Runtime> {
replace_period: 10,
replace_btc_dust_value: 2,
}
.assimilate_storage(&mut storage)
.unwrap();
fee::GenesisConfig::<Runtime> {
issue_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5%
issue_griefing_collateral: FixedU128::checked_from_rational(5, 100000).unwrap(), // 0.005%
refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5%
redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5%
premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5%
punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10%
replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10%
maintainer_account_id: account_of(MAINTAINER),
vault_rewards: FixedU128::checked_from_rational(70, 100).unwrap(), // 70%
relayer_rewards: FixedU128::checked_from_rational(20, 100).unwrap(), // 20%
maintainer_rewards: FixedU128::checked_from_rational(10, 100).unwrap(), // 10%
nomination_rewards: FixedU128::checked_from_rational(0, 100).unwrap(), // 0%
}
.assimilate_storage(&mut storage)
.unwrap();
sla::GenesisConfig::<Runtime> {
vault_target_sla: FixedI128::from(100),
vault_redeem_failure_sla_change: FixedI128::from(-100),
vault_execute_issue_max_sla_change: FixedI128::from(4),
vault_deposit_max_sla_change: FixedI128::from(4),
vault_withdraw_max_sla_change: FixedI128::from(-4),
vault_submit_issue_proof: FixedI128::from(1),
vault_refund: FixedI128::from(1),
relayer_target_sla: FixedI128::from(100),
relayer_store_block: FixedI128::from(1),
relayer_theft_report: FixedI128::from(1),
}
.assimilate_storage(&mut storage)
.unwrap();
Self {
test_externalities: sp_io::TestExternalities::from(storage),
}
}
/// do setup common to all integration tests, then execute the callback
pub fn execute_with<R>(self, execute: impl FnOnce() -> R) -> R {
self.execute_without_relay_init(|| {
// initialize btc relay
let _ = TransactionGenerator::new().with_confirmations(7).mine();
assert_ok!(
Call::ExchangeRateOracle(ExchangeRateOracleCall::insert_authorized_oracle(
account_of(ALICE),
vec![]
))
.dispatch(root())
);
assert_ok!(
Call::ExchangeRateOracle(ExchangeRateOracleCall::set_btc_tx_fees_per_byte(3, 2, 1))
.dispatch(origin_of(account_of(ALICE)))
);
execute()
})
}
/// used for btc-relay test
pub fn execute_without_relay_init<R>(mut self, execute: impl FnOnce() -> R) -> R {
self.test_externalities.execute_with(|| {
SystemModule::set_block_number(1); // required to be able to dispatch functions
SecurityPallet::set_active_block_number(1);
assert_ok!(ExchangeRateOraclePallet::_set_exchange_rate(FixedU128::one()));
set_default_thresholds();
execute()
})
}
} | }
}
impl PartialEq for FeePool { |
index.tsx | import * as React from 'react'
import { widgetReducer, widgetState } from '@app/reducers/widgetManager.reducer'
import BreadcrumbsBase from '@components/base/BreadcrumbsBase'
import SideMenuWithContent from '@components/base/SideMenuWithContent'
import WigetManagerMenuList from '@components/templates/widget-manager/WidgetManagerMenuList'
import WidgetManagerOutputEvent from '@components/templates/widget-manager/WidgetManagerOutputEvent'
import WidgetManagerParameter from '@components/templates/widget-manager/WidgetManagerParameter'
import { IWidgetGroup } from '@config'
import {
widgetGalleryAllergyIntoleranceConfig,
widgetGalleryDiagnosticReportConfig,
widgetGalleryObservationConfig,
widgetGalleryPatientConfig,
} from '@config/embedded-widget'
import {
AppBar,
Box,
Button,
createStyles,
CssBaseline,
Fab,
Grid,
Icon,
IconButton,
makeStyles,
Paper,
Tab,
Tabs,
TextField,
Theme,
Typography,
} from '@material-ui/core'
import HomeIcon from '@material-ui/icons/Home'
import NavigateBeforeIcon from '@material-ui/icons/NavigateBefore'
import NavigateNextIcon from '@material-ui/icons/NavigateNext'
import RefreshIcon from '@material-ui/icons/Refresh'
import { IStatelessPage } from '@pages/patient-search'
import * as _ from 'lodash'
import MarkdownIt from 'markdown-it'
import { parse, stringify } from 'qs'
import '../../github-markdown.css'
import routes from '../../routes'
import clsx from 'clsx'
const md = MarkdownIt({ html: true })
const WIDGET_GROUP: IWidgetGroup[] = [
{
child: [
{
document: require('@assets/embedded-widget/get-started-iframe-sdk.md')
.default,
label: 'Get Started',
value: 'get-started',
},
],
label: 'Get Started',
value: 'get-started',
},
{
child: [
{
document: require('@assets/embedded-widget/redux.md').default,
label: 'Redux',
value: 'redux',
},
],
label: 'Redux',
value: 'redux',
},
{
child: [
{
document: require('@assets/embedded-widget/html-demo/index.md').default,
label: 'HTML Demo',
path: '../../static/public/index.html',
pathType: 'static',
value: 'html-demo',
},
],
label: 'HTML Demo',
value: 'html-demo',
},
widgetGalleryPatientConfig,
widgetGalleryObservationConfig,
// widgetGalleryDiagnosticReportConfig,
// widgetGalleryAllergyIntoleranceConfig,
]
const useStyles = makeStyles((theme: Theme) =>
createStyles({
code: {
background: 'rgb(36, 36, 36)',
borderRadius: 8,
height: '100%',
minHeight: '20vh',
padding: 16,
},
eventResponse: {
height: '30vh',
overflow: 'scroll',
padding: theme.spacing(2),
width: '100%',
},
extendedIconLeft: {
marginLeft: theme.spacing(1),
},
iframLayout: {
display: 'flex',
minHeight: '60vh',
},
iframe: {
flex: '1 1 auto',
},
mdContainer: {
'& pre': {
color: '#24292e',
},
'& th': {
color: '#24292e',
},
'& td': {
color: '#24292e',
},
color: theme.palette.text.primary,
},
nested: {
paddingLeft: theme.spacing(4),
},
parameterLayout: {
height: '100%',
padding: theme.spacing(2),
},
root: {},
tabContainer: {
backgroundColor: theme.palette.background.paper || '',
},
urlInputProps: {
height: 45,
},
widgetGallery: {
marginBottom: 16,
},
widgetGalleryHeader: {
padding: theme.spacing(2),
},
widgetGallerySide: {
backgroundColor: theme.palette.background.paper,
height: '100%',
padding: theme.spacing(2),
width: '100%',
},
}),
)
const WidgetManager: IStatelessPage<{
query: any
}> = ({ query }) => {
const classes = useStyles()
const iframeRef = React.useRef<null | HTMLIFrameElement>(null)
const [
{
iframeState,
tabState,
selectedWidget,
loading,
outputs: outputEventData,
urlText,
},
dispatch,
] = React.useReducer(widgetReducer, widgetState)
const { parameters, queryParams, url } = iframeState
React.useEffect(() => {
window.addEventListener('message', msgListener, false)
return () => {
console.info('unregister msgListener :')
window.removeEventListener('message', msgListener)
}
}, [selectedWidget?.value])
React.useEffect(() => {
if (query) {
const selectedWidget = findWidget(query.widget)
const newQueryParams = initialQueryParams(selectedWidget)
const url = createURL(selectedWidget, null, newQueryParams)
dispatch({
payload: {
iframeState: {
parameters: initialParameter(selectedWidget),
queryParams: newQueryParams,
url,
},
selectedWidget,
tabState: selectedWidget && selectedWidget.path ? 0 : 1,
urlText: url,
},
type: 'INIT',
})
}
}, [query])
function msgListener(event: any) {
if (event.data.eventType !== 'embedded-widget') {
return
}
if (event.data.action === 'REPLACE_ROUTE') {
const queryParams = parseQueryStr(event.data.path)
// console.log("queryParams", queryParams)
// if (!_.isEmpty(queryParams)) {
// }
dispatch({
payload: createURL(selectedWidget, null, queryParams),
type: 'UPDATE_URL_TEXT',
})
}
dispatch({ type: 'OUTPUT_ADD_LOG', payload: event.data })
}
const parseQueryStr = (queryStr: string) => {
const queryParams = _.split(queryStr, '?')
return queryParams[1] ? parse(queryParams[1], { depth: 0 }) : {}
}
const findWidget = (widgetValue: string) => {
const findWidget = _.chain(WIDGET_GROUP)
.map(widget => widget.child)
.flatten()
.find((widget: any) => _.toLower(widget.value) === _.toLower(widgetValue))
.value()
return findWidget ? findWidget : WIDGET_GROUP[0].child[0]
}
const createURL = (
selectedWidget: any,
parameters?: any,
queryParams?: any,
) => {
let url = _.get(selectedWidget, 'path')
if (!url) {
return ''
}
if (parameters) {
_.each(parameters, (value, key) => {
url = _.replace(url, `:${key}`, value)
})
} else {
_.each(selectedWidget.parameters, parameter => {
url = _.replace(url, `:${parameter.value}`, parameter.defaultValue)
})
}
if (queryParams) {
const stringQueryParam = parse(stringify(queryParams), { depth: 0 })
const newQueryParams = _.reduce(
stringQueryParam,
(acc, value, key) => {
if (value) {
return { ...acc, [key]: value }
}
return acc
},
{},
)
if (_.isEmpty(newQueryParams)) {
return `${url}`
}
return `${url}?${stringify(newQueryParams)}`
}
return url
}
const initialParameter = (selectedWidget: any) => {
return createMapping(
_.get(selectedWidget, 'parameters'),
'value',
'defaultValue',
)
}
const initialQueryParams = (selectedWidget: any) => {
return createMapping(
_.get(selectedWidget, 'queryParams'),
'value',
'defaultValue',
)
}
const createMapping = (object: any, key: string, value: string) => {
return _.chain(object)
.reduce((acc, item) => {
return {
...acc,
[item[key]]: item[value],
}
}, {})
.value()
}
const handleQueryParamChange = (type: string, value: any) => {
dispatch({
payload: { type, value },
type: 'IFRAME_QUERY_PARAMS_CHANGE',
})
}
const handleParameterChange = (type: string, value: any) => {
dispatch({
payload: { type, value },
type: 'IFRAME_PARAMETERS_CHANGE',
})
}
const iframeInitial = () => {
const iframeObject = _.get(iframeRef, 'current')
? (_.get(iframeRef, 'current') as HTMLIFrameElement)
: null
if (iframeObject && iframeObject.contentWindow) {
iframeObject.contentWindow.onpopstate = (event: any) => {
// setURLText(event.state.url)
}
}
}
const handleChangeWidget = (widget: any) => {
dispatch({ type: 'OUTPUT_RESET' })
routes.Router.replaceRoute(
`/embedded-widget?widget=${_.toLower(widget.value)}`,
)
}
const handleIFrameBack = (event: React.MouseEvent) => {
const iframeObject = _.get(iframeRef, 'current')
? (_.get(iframeRef, 'current') as HTMLIFrameElement)
: null
if (iframeObject && iframeObject.contentWindow) {
iframeObject.contentWindow.history.back()
}
}
const handleIFrameNext = (event: React.MouseEvent) => {
const iframeObject = _.get(iframeRef, 'current')
? (_.get(iframeRef, 'current') as HTMLIFrameElement)
: null
if (iframeObject && iframeObject.contentWindow) {
iframeObject.contentWindow.history.forward()
}
}
const handleIFrameRefresh = (event: React.MouseEvent) => {
const iframeObject = _.get(iframeRef, 'current')
? (_.get(iframeRef, 'current') as HTMLIFrameElement)
: null
if (iframeObject && iframeObject.contentWindow) {
iframeObject.contentWindow.location.reload()
}
dispatch({ type: 'IFRAME_REFRESH' })
}
const handleIFrameReset = (event: React.MouseEvent) => {
// TODO: iframe reset
dispatch({ type: 'IFRAME_RESET' })
if (selectedWidget) {
routes.Router.replaceRoute(
`/embedded-widget${
selectedWidget.value ? `?widget=${selectedWidget.value || ''}` : ''
}`,
)
} else {
routes.Router.replaceRoute(`/embedded-widget`)
}
}
const handleSubmitURL = (event?: React.FormEvent<HTMLFormElement>) => {
if (event) {
event.preventDefault()
}
// clear specific local storage
if (typeof window !== 'undefined') {
window.localStorage.removeItem('medicalPanelRecord')
}
if (selectedWidget && selectedWidget.path) {
const url = createURL(selectedWidget, parameters, queryParams)
const iframeObject = _.get(iframeRef, 'current')
? (_.get(iframeRef, 'current') as HTMLIFrameElement)
: null
if (iframeObject && iframeObject.contentWindow) {
iframeObject.contentWindow.location.replace(url)
}
}
dispatch({
payload: createURL(selectedWidget, null, queryParams),
type: 'IFRAME_SUBMIT',
})
}
const decodeURI = (uri: string) => {
if (typeof window !== 'undefined') {
return window.decodeURI(uri)
} else {
return uri
}
}
const handleTabChange = (event: React.ChangeEvent<{}>, newValue: number) => {
dispatch({ type: 'TAB_CHANGE', payload: newValue })
}
return (
<>
<CssBaseline />
{/* <BreadcrumbsBase
currentPath='Patient Info'
parentPath={[
{
icon: <HomeIcon />,
label: 'Home',
url: '/',
},
{
label: 'Embedded Widget',
},
]}
></BreadcrumbsBase> */}
<SideMenuWithContent
menuTitle='Embedded Widget'
appBarTitle={selectedWidget?.label}
renderMenuList={
<WigetManagerMenuList
widgetGroup={WIDGET_GROUP}
onItemClick={handleChangeWidget}
selectedWidget={selectedWidget}
/>
}
>
{!loading && (
<>
<AppBar position='static' color='default'>
<Tabs
value={tabState}
onChange={handleTabChange}
indicatorColor='primary'
textColor='primary'
variant='scrollable'
scrollButtons='auto'
className={classes.tabContainer}
>
{selectedWidget && selectedWidget.path ? (
<Tab label='Playground' id='0' value={0} />
) : null}
<Tab label='Document' id='1' value={1} />
</Tabs>
</AppBar>
<TabPanel value={tabState} index={0}>
<Grid container>
{selectedWidget &&
_.isEmpty(selectedWidget.parameters) &&
_.isEmpty(selectedWidget.queryParams) ? null : (
<Grid item xs={3}>
<Paper className={classes.parameterLayout}>
<form onSubmit={handleSubmitURL}>
<WidgetManagerParameter
parameters={parameters}
selectedWidget={selectedWidget}
onParameterChange={handleParameterChange}
type='parameters'
label='Parameters'
/>
<WidgetManagerParameter
parameters={queryParams}
selectedWidget={selectedWidget}
onParameterChange={handleQueryParamChange}
type='queryParams'
/>
<Grid container justify='flex-end'>
<Fab
variant='extended'
size='medium'
color='primary'
aria-label='go'
type='submit'
>
Execute
<Icon className={classes.extendedIconLeft}>
send
</Icon>
</Fab>
</Grid>
</form>
</Paper>
</Grid>
)}
<Grid
item
xs={
selectedWidget &&
_.isEmpty(selectedWidget.parameters) &&
_.isEmpty(selectedWidget.queryParams)
? 12
: 9
}
>
<Paper className={classes.parameterLayout}>
<Grid item xs={12}>
<IconButton aria-label='back' onClick={handleIFrameBack}>
<NavigateBeforeIcon />
</IconButton>
<IconButton aria-label='next' onClick={handleIFrameNext}>
<NavigateNextIcon />
</IconButton>
<IconButton
aria-label='refresh'
onClick={handleIFrameRefresh}
>
<RefreshIcon />
</IconButton> | variant='outlined'
aria-label='reset'
>
Reset
</Button>
</Grid>
<Grid
container
spacing={4}
alignItems='center'
alignContent='center'
>
<Grid item xs={12}>
<TextField
label='URL'
id='outlined-size-small'
variant='outlined'
fullWidth
value={decodeURI(urlText || '')}
disabled
InputProps={{ className: classes.urlInputProps }}
/>
</Grid>
</Grid>
<Grid container>
<Grid item xs={12} className={classes.iframLayout}>
<iframe
key={_.get(selectedWidget, 'path')}
ref={iframeRef}
className={classes.iframe}
src={`${url}`}
onLoad={iframeInitial}
/>
</Grid>
</Grid>
</Paper>
</Grid>
</Grid>
{selectedWidget?.path && (
<WidgetManagerOutputEvent outputEventData={outputEventData} />
)}
</TabPanel>
<TabPanel value={tabState} index={1}>
<div
className={clsx('markdown-body', classes.mdContainer)}
dangerouslySetInnerHTML={{
__html: md.render(
_.get(selectedWidget, 'document') || `# Comming soon`,
),
}}
></div>
</TabPanel>
</>
)}
</SideMenuWithContent>
</>
)
}
const TabPanel: React.FunctionComponent<{
value: any
index: number
}> = ({ value, index, children }) => {
return (
<Typography
component='div'
role='tabpanel'
hidden={value !== index}
id={`simple-tabpanel-${index}`}
aria-labelledby={`simple-tab-${index}`}
>
{value === index && <Box p={3}>{children}</Box>}
</Typography>
)
}
WidgetManager.getInitialProps = async ({ req, res, query }) => {
return {
query,
}
}
export default WidgetManager | <Button
onClick={handleIFrameReset} |
listRegistryCredentials.go | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package v20171001
import (
"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
)
// The response from the ListCredentials operation.
func | (ctx *pulumi.Context, args *ListRegistryCredentialsArgs, opts ...pulumi.InvokeOption) (*ListRegistryCredentialsResult, error) {
var rv ListRegistryCredentialsResult
err := ctx.Invoke("azure-nextgen:containerregistry/v20171001:listRegistryCredentials", args, &rv, opts...)
if err != nil {
return nil, err
}
return &rv, nil
}
type ListRegistryCredentialsArgs struct {
// The name of the container registry.
RegistryName string `pulumi:"registryName"`
// The name of the resource group to which the container registry belongs.
ResourceGroupName string `pulumi:"resourceGroupName"`
}
// The response from the ListCredentials operation.
type ListRegistryCredentialsResult struct {
// The list of passwords for a container registry.
Passwords []RegistryPasswordResponse `pulumi:"passwords"`
// The username for a container registry.
Username *string `pulumi:"username"`
}
| ListRegistryCredentials |
bind.rs | use crate::arg::SqlArg;
use std::collections::HashMap;
pub trait Bind {
/// Replace first ? with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price BETWEEN ? AND ?".bind(&100).bind(&200))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price BETWEEN 100 AND 200;", &sql);
/// # Ok(())
/// # }
/// ```
fn bind(&self, arg: &dyn SqlArg) -> String;
/// Cyclic bindings of values.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > ? AND title LIKE ?".binds(&[&100, &"Harry Potter%"]))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND title LIKE 'Harry Potter%';", &sql);
/// # Ok(())
/// # }
/// ```
fn binds(&self, args: &[&dyn SqlArg]) -> String;
/// Replace all $N with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1 AND price < $1 + $2"
/// .bind_num(1, &100)
/// .bind_num(2, &200))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND price < 100 + 200;", &sql);
/// # Ok(())
/// # }
/// ```
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1")
/// .and_where("price < $1 + $2")
/// .sql()?
/// .bind_num(1, &100)
/// .bind_num(2, &200);
///
/// assert_eq!("SELECT title, price FROM books WHERE (price > 100) AND (price < 100 + 200);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_num(&self, num: u16, arg: &dyn SqlArg) -> String;
/// Replace $1, $2, ... with elements of array.
/// Escape the $ symbol with another $ symbol.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1 AND price < $1 + $2".bind_nums(&[&100, &200]))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND price < 100 + 200;", &sql);
/// # Ok(())
/// # }
/// ```
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1")
/// .and_where("price < $1 + $2")
/// .sql()?
/// .bind_nums(&[&100, &200]);
///
/// assert_eq!("SELECT title, price FROM books WHERE (price > 100) AND (price < 100 + 200);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_nums(&self, args: &[&dyn SqlArg]) -> String;
/// Replace all :name: with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::insert_into("books")
/// .fields(&["title", "price"])
/// .values(&[":name:, :costs:"])
/// .sql()?
/// .bind_name(&"name", &"Harry Potter and the Philosopher's Stone")
/// .bind_name(&"costs", &150);
///
/// assert_eq!("INSERT INTO books (title, price) VALUES ('Harry Potter and the Philosopher''s Stone', 150);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_name(&self, name: &dyn ToString, arg: &dyn SqlArg) -> String;
/// Replace each :name: from map.
/// Escape the : symbol with another : symbol.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
/// use std::collections::HashMap;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let mut names: HashMap<&str, &dyn SqlArg> = HashMap::new();
/// names.insert("name", &"Harry Potter and the Philosopher's Stone");
/// names.insert("costs", &150);
///
/// let sql = SqlBuilder::insert_into("books")
/// .fields(&["title", "price"])
/// .values(&[":name:, :costs:"])
/// .sql()?
/// .bind_names(&names);
///
/// assert_eq!("INSERT INTO books (title, price) VALUES ('Harry Potter and the Philosopher''s Stone', 150);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_names(&self, names: &dyn BindNames) -> String;
}
impl Bind for &str {
/// Replace first ? with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price BETWEEN ? AND ?".bind(&100).bind(&200))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price BETWEEN 100 AND 200;", &sql);
/// # Ok(())
/// # }
/// ```
fn bind(&self, arg: &dyn SqlArg) -> String {
(*self).to_string().bind(arg)
}
/// Cyclic bindings of values.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > ? AND title LIKE ?".binds(&[&100, &"Harry Potter%"]))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND title LIKE 'Harry Potter%';", &sql);
/// # Ok(())
/// # }
/// ```
fn binds(&self, args: &[&dyn SqlArg]) -> String {
(*self).to_string().binds(args)
}
/// Replace all $N with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1 AND price < $1 + $2"
/// .bind_num(1, &100)
/// .bind_num(2, &200))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND price < 100 + 200;", &sql);
/// # Ok(())
/// # }
/// ```
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1")
/// .and_where("price < $1 + $2")
/// .sql()?
/// .bind_num(1, &100)
/// .bind_num(2, &200);
///
/// assert_eq!("SELECT title, price FROM books WHERE (price > 100) AND (price < 100 + 200);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_num(&self, num: u16, arg: &dyn SqlArg) -> String {
(*self).to_string().bind_num(num, arg)
}
/// Replace $1, $2, ... with elements of array.
/// Escape the $ symbol with another $ symbol.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1 AND price < $1 + $2".bind_nums(&[&100, &200]))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND price < 100 + 200;", &sql);
/// # Ok(())
/// # }
/// ```
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1")
/// .and_where("price < $1 + $2")
/// .sql()?
/// .bind_nums(&[&100, &200]);
///
/// assert_eq!("SELECT title, price FROM books WHERE (price > 100) AND (price < 100 + 200);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_nums(&self, args: &[&dyn SqlArg]) -> String {
(*self).to_string().bind_nums(args)
}
/// Replace all :name: with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::insert_into("books")
/// .fields(&["title", "price"])
/// .values(&[":name:, :costs:"])
/// .sql()?
/// .bind_name(&"name", &"Harry Potter and the Philosopher's Stone")
/// .bind_name(&"costs", &150);
///
/// assert_eq!("INSERT INTO books (title, price) VALUES ('Harry Potter and the Philosopher''s Stone', 150);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_name(&self, name: &dyn ToString, arg: &dyn SqlArg) -> String {
(*self).to_string().bind_name(name, arg)
}
/// Replace each :name: from map.
/// Escape the : symbol with another : symbol.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
/// use std::collections::HashMap;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let mut names: HashMap<&str, &dyn SqlArg> = HashMap::new();
/// names.insert("name", &"Harry Potter and the Philosopher's Stone");
/// names.insert("costs", &150);
///
/// let sql = SqlBuilder::insert_into("books")
/// .fields(&["title", "price"])
/// .values(&[":name:, :costs:"])
/// .sql()?
/// .bind_names(&names);
///
/// assert_eq!("INSERT INTO books (title, price) VALUES ('Harry Potter and the Philosopher''s Stone', 150);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_names<'a>(&self, names: &dyn BindNames) -> String {
(*self).to_string().bind_names(names)
}
}
impl Bind for String {
/// Replace first ? with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price BETWEEN ? AND ?".bind(&100).bind(&200))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price BETWEEN 100 AND 200;", &sql);
/// # Ok(())
/// # }
/// ```
fn bind(&self, arg: &dyn SqlArg) -> String {
self.replacen('?', &arg.sql_arg(), 1)
}
/// Cyclic bindings of values.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > ? AND title LIKE ?".binds(&[&100, &"Harry Potter%"]))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND title LIKE 'Harry Potter%';", &sql);
/// # Ok(())
/// # }
/// ```
fn binds(&self, args: &[&dyn SqlArg]) -> String {
let mut offset = 0;
let mut res = String::new();
let len = args.len();
for ch in self.chars() {
if ch == '?' {
res.push_str(&args[offset].sql_arg());
offset = (offset + 1) % len;
} else {
res.push(ch);
}
}
res
}
/// Replace all $N with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1 AND price < $1 + $2"
/// .bind_num(1, &100)
/// .bind_num(2, &200))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND price < 100 + 200;", &sql);
/// # Ok(())
/// # }
/// ```
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1")
/// .and_where("price < $1 + $2")
/// .sql()?
/// .bind_num(1, &100)
/// .bind_num(2, &200);
///
/// assert_eq!("SELECT title, price FROM books WHERE (price > 100) AND (price < 100 + 200);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_num(&self, num: u16, arg: &dyn SqlArg) -> String {
let rep = format!("${}", &num);
self.replace(&rep, &arg.sql_arg())
}
/// Replace $1, $2, ... with elements of array.
/// Escape the $ symbol with another $ symbol.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1 AND price < $1 + $2".bind_nums(&[&100, &200]))
/// .sql()?;
///
/// assert_eq!("SELECT title, price FROM books WHERE price > 100 AND price < 100 + 200;", &sql);
/// # Ok(())
/// # }
/// ```
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::select_from("books")
/// .fields(&["title", "price"])
/// .and_where("price > $1")
/// .and_where("price < $1 + $2")
/// .sql()?
/// .bind_nums(&[&100, &200]);
///
/// assert_eq!("SELECT title, price FROM books WHERE (price > 100) AND (price < 100 + 200);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_nums(&self, args: &[&dyn SqlArg]) -> String {
let mut res = String::new();
let mut num = 0usize;
let mut wait_digit = false;
let len = args.len();
for ch in self.chars() {
if ch == '$' {
if wait_digit {
if num > 0 {
let idx = num - 1;
if len > idx {
res.push_str(&args[idx].sql_arg());
}
num = 0;
} else {
wait_digit = false;
res.push(ch);
}
} else {
wait_digit = true;
}
} else if wait_digit {
if let Some(digit) = ch.to_digit(10) {
num = num * 10 + digit as usize;
} else {
let idx = num - 1;
if len > idx {
res.push_str(&args[idx].sql_arg());
}
res.push(ch);
wait_digit = false;
num = 0;
}
} else {
res.push(ch);
}
}
if wait_digit && num > 0 {
let idx = num - 1;
if len > idx {
res.push_str(&args[idx].sql_arg());
}
}
res
}
/// Replace all :name: with a value.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let sql = SqlBuilder::insert_into("books")
/// .fields(&["title", "price"])
/// .values(&[":name:, :costs:"])
/// .sql()?
/// .bind_name(&"name", &"Harry Potter and the Philosopher's Stone")
/// .bind_name(&"costs", &150);
///
/// assert_eq!("INSERT INTO books (title, price) VALUES ('Harry Potter and the Philosopher''s Stone', 150);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_name(&self, name: &dyn ToString, arg: &dyn SqlArg) -> String {
let rep = format!(":{}:", &name.to_string());
self.replace(&rep, &arg.sql_arg())
}
/// Replace each :name: from map.
/// Escape the : symbol with another : symbol.
///
/// ```
/// # use std::error::Error;
/// use sql_builder::prelude::*;
/// use std::collections::HashMap;
///
/// # fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
/// let mut names: HashMap<&str, &dyn SqlArg> = HashMap::new();
/// names.insert("name", &"Harry Potter and the Philosopher's Stone");
/// names.insert("costs", &150);
///
/// let sql = SqlBuilder::insert_into("books")
/// .fields(&["title", "price"])
/// .values(&[":name:, :costs:"])
/// .sql()?
/// .bind_names(&names);
///
/// assert_eq!("INSERT INTO books (title, price) VALUES ('Harry Potter and the Philosopher''s Stone', 150);", &sql);
/// # Ok(())
/// # }
/// ```
fn bind_names<'a>(&self, names: &dyn BindNames) -> String {
let mut res = String::new();
let mut key = String::new();
let mut wait_colon = false;
let names = names.names_map();
for ch in self.chars() {
if ch == ':' {
if wait_colon {
if key.is_empty() {
res.push(ch);
} else {
let skey = key.to_string();
if let Some(value) = names.get(&*skey) {
res.push_str(&value.sql_arg());
} else {
res.push_str("NULL");
}
key = String::new();
}
wait_colon = false;
} else {
wait_colon = true;
}
} else if wait_colon {
key.push(ch);
} else {
res.push(ch);
}
}
if wait_colon {
res.push(';');
res.push_str(&key);
}
res
}
}
pub trait BindNames<'a> {
fn names_map(&self) -> HashMap<&'a str, &dyn SqlArg>;
}
impl<'a> BindNames<'a> for HashMap<&'a str, &dyn SqlArg> {
fn | (&self) -> HashMap<&'a str, &dyn SqlArg> {
self.to_owned()
}
}
impl<'a> BindNames<'a> for &HashMap<&'a str, &dyn SqlArg> {
fn names_map(&self) -> HashMap<&'a str, &dyn SqlArg> {
self.to_owned().to_owned()
}
}
impl<'a> BindNames<'a> for Vec<(&'a str, &dyn SqlArg)> {
fn names_map(&self) -> HashMap<&'a str, &dyn SqlArg> {
let mut map = HashMap::new();
for (k, v) in self.iter() {
map.insert(*k, *v);
}
map
}
}
impl<'a> BindNames<'a> for &[(&'a str, &dyn SqlArg)] {
fn names_map(&self) -> HashMap<&'a str, &dyn SqlArg> {
let mut map = HashMap::new();
for (k, v) in self.iter() {
map.insert(*k, *v);
}
map
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::prelude::*;
use std::error::Error;
#[test]
fn test_bind() -> Result<(), Box<dyn Error + Send + Sync>> {
let foo = "f?o?o";
assert_eq!("'lol'foo?", &"?foo?".bind(&"lol"));
assert_eq!("'lol'foo10", &"?foo?".bind(&"lol").bind(&10));
assert_eq!("'lol'foo?", &"?foo?".bind(&String::from("lol")));
assert_eq!("'lol'foo?", &String::from("?foo?").bind(&"lol"));
assert_eq!("f'lol'o?o", &foo.bind(&"lol"));
assert_eq!("fo'f?o?o'o", &"fo?o".bind(&foo));
assert_eq!("fo10o", &"fo?o".bind(&10_usize));
assert_eq!("fo10o", &"fo?o".bind(&10));
assert_eq!("fo10o", &"fo?o".bind(&10_isize));
assert_eq!("foTRUEo", &"fo?o".bind(&true));
assert_eq!("foFALSEo", &"fo?o".bind(&false));
assert_eq!(
"10f'lol'o10o$3",
&"$1f$2o$1o$3".bind_num(1, &10_u8).bind_num(2, &"lol")
);
assert_eq!("f'lol'oo:def:", &"f:abc:oo:def:".bind_name(&"abc", &"lol"));
Ok(())
}
#[test]
fn test_binds() -> Result<(), Box<dyn Error + Send + Sync>> {
assert_eq!("10f20o30o10", &"?f?o?o?".binds(&[&10, &20, &30]));
assert_eq!(
"'abc'f'def'o'ghi'o'abc'",
&"?f?o?o?".binds(&[&"abc", &"def", &"ghi"])
);
assert_eq!(
"10f20o30o10",
&String::from("?f?o?o?").binds(&[&10, &20, &30])
);
assert_eq!(
"10f'AAA'oTRUEo10",
&String::from("?f?o?o?").binds(&[&10, &"AAA", &true])
);
assert_eq!(
"10f'AAA'o$oTRUE",
&String::from("$1f$02o$$o$3$4").bind_nums(&[&10, &"AAA", &true])
);
assert_eq!(
"1f1.5o0.0000001o1",
&"?f?o?o?".binds(&[&1.0, &1.5, &0.0000001])
);
Ok(())
}
#[test]
fn test_bind_doc() -> Result<(), Box<dyn Error + Send + Sync>> {
let sql = SqlBuilder::select_from("books")
.fields(&["title", "price"])
.and_where("price > ? AND title LIKE ?".binds(&[&100, &"Harry Potter%"]))
.sql()?;
assert_eq!(
"SELECT title, price FROM books WHERE price > 100 AND title LIKE 'Harry Potter%';",
&sql
);
Ok(())
}
#[test]
fn test_bind_names() -> Result<(), Box<dyn Error + Send + Sync>> {
let mut names: HashMap<&str, &dyn SqlArg> = HashMap::new();
names.insert("aaa", &10);
names.insert("bbb", &20);
names.insert("ccc", &"tt");
names.insert("ddd", &40);
let sql = SqlBuilder::insert_into("books")
.fields(&["title", "price"])
.values(&["'a_book', :aaa:"])
.values(&["'c_book', :ccc:"])
.values(&["'e_book', :eee:"])
.sql()?
.bind_names(&names);
assert_eq!(
"INSERT INTO books (title, price) VALUES ('a_book', 10), ('c_book', 'tt'), ('e_book', NULL);",
&sql
);
let names: Vec<(&str, &dyn SqlArg)> =
vec![("aaa", &10), ("bbb", &20), ("ccc", &"tt"), ("ddd", &40)];
let sql = SqlBuilder::insert_into("books")
.fields(&["title", "price"])
.values(&["'a_book', :aaa:"])
.values(&["'c_book', :ccc:"])
.values(&["'e_book', :eee:"])
.sql()?
.bind_names(&names);
assert_eq!(
"INSERT INTO books (title, price) VALUES ('a_book', 10), ('c_book', 'tt'), ('e_book', NULL);",
&sql
);
Ok(())
}
#[test]
fn test_null() -> Result<(), Box<dyn Error + Send + Sync>> {
let foo: Option<&str> = None;
assert_eq!("foNULLo", &"fo?o".bind(&foo));
let foo = Some("foo");
assert_eq!("fo'foo'o", &"fo?o".bind(&foo));
Ok(())
}
}
| names_map |
pbxFile.js | var path = require('path'),
M_EXTENSION = /[.]m$/, SOURCE_FILE = 'sourcecode.c.objc',
H_EXTENSION = /[.]h$/, HEADER_FILE = 'sourcecode.c.h',
BUNDLE_EXTENSION = /[.]bundle$/, BUNDLE = '"wrapper.plug-in"',
XIB_EXTENSION = /[.]xib$/, XIB_FILE = 'file.xib',
DYLIB_EXTENSION = /[.]dylib$/, DYLIB = '"compiled.mach-o.dylib"',
FRAMEWORK_EXTENSION = /[.]framework/, FRAMEWORK = 'wrapper.framework',
ARCHIVE_EXTENSION = /[.]a$/, ARCHIVE = 'archive.ar',
DEFAULT_SOURCE_TREE = '"<group>"',
DEFAULT_FILE_ENCODING = 4;
function | (path) {
if (M_EXTENSION.test(path))
return SOURCE_FILE;
if (H_EXTENSION.test(path))
return HEADER_FILE;
if (BUNDLE_EXTENSION.test(path))
return BUNDLE;
if (XIB_EXTENSION.test(path))
return XIB_FILE;
if (FRAMEWORK_EXTENSION.test(path))
return FRAMEWORK;
if (DYLIB_EXTENSION.test(path))
return DYLIB;
if (ARCHIVE_EXTENSION.test(path))
return ARCHIVE;
// dunno
return 'unknown';
}
function fileEncoding(file) {
if (file.lastType != BUNDLE) {
return DEFAULT_FILE_ENCODING;
}
}
function defaultSourceTree(file) {
if (file.lastType == DYLIB || file.lastType == FRAMEWORK) {
return 'SDKROOT';
} else {
return DEFAULT_SOURCE_TREE;
}
}
function correctPath(file, filepath) {
if (file.lastType == FRAMEWORK) {
return 'System/Library/Frameworks/' + filepath;
} else if (file.lastType == DYLIB) {
return 'usr/lib/' + filepath;
} else {
return filepath;
}
}
function correctGroup(file) {
if (file.lastType == SOURCE_FILE) {
return 'Sources';
} else if (file.lastType == DYLIB || file.lastType == ARCHIVE) {
return 'Frameworks';
} else {
return 'Resources';
}
}
function pbxFile(filepath, opt) {
var opt = opt || {};
this.lastType = opt.lastType || detectLastType(filepath);
this.path = correctPath(this, filepath);
this.basename = path.basename(filepath);
this.group = correctGroup(this);
this.sourceTree = opt.sourceTree || defaultSourceTree(this);
this.fileEncoding = opt.fileEncoding || fileEncoding(this);
if (opt.weak && opt.weak === true)
this.settings = { ATTRIBUTES: ['Weak'] };
if (opt.compilerFlags) {
if (!this.settings)
this.settings = {};
this.settings.COMPILER_FLAGS = opt.compilerFlags;
}
}
module.exports = pbxFile;
| detectLastType |
calc_bulk_properties.py | import os, shutil, subprocess
import ase.build
import pypospack.io.vasp as vasp
import pypospack.crystal as crystal
import pypospack.io.slurm as slurm
class VaspCalculateBulkProperties(object):
|
class VaspMinimizeStructure(object):
def __init__(self,sim_dir,obj_structure, xc = 'GGA'):
assert isinstance(obj_structure,pypospack.crystal.SimulationCell)
self.xc = xc
self.sim_dir = sim_dir
self.is_job_submitted = False
self.is_job_completed = False
if os.path.exists(self.sim_dir):
self.is_job_submitted = os.path.exists(self.sim_dir,'job.submitted')
self.is_job_completed = os.path.exists(self.sim_dir,'job.completed')
if self.is_job_completed:
self.postprocesses()
else:
os.mkdir(self.sim_dir)
self.create_simulation()
self.submit_job()
def create_simulation(self):
# initialize input files
self.vs = vasp.VaspSimulation()
self.vs.poscar = vasp.Poscar(obj_structure)
self.vs.incar = vasp.Incar()
self.vs.potcar = vasp.Potcar()
self.vs.kpoints = vasp.Kpoints()
self.vs.xc = self.xc
self.vs.simulation_directory = self.sim_dir
self.vs.symbols = self.vs.poscar.symbols
# configure potcar file
self.vs.potcar.symbols = self.vs.symbols
self.vs.potcar.xc = self.vs.xc
fn_potcar = os.path.join(self.vs.simulation_directory,'POTCAR')
self.vs.potcar.write(fn_potcar)
self.vs.potcar.read(fn_potcar)
self.vs.encut = max(self.vs.potcar.encut_max)
self.vs.natoms = self.vs.poscar.n_atoms
# configure incar file
magmom_0 = 1.0
self.vs.incar.ismear = 1
self.vs.incar.sigma = 0.20
self.vs.incar.ispin = 2
self.vs.incar.magmom = "{}*{}".format(self.vs.natoms,magmom_0)
self.vs.incar.ibrion = 2
self.vs.incar.isif = 3
self.vs.incar.potim = 0.5
self.vs.incar.ediffg = -0.001
self.vs.poscar.write(os.path.join(\
self.vs.simulation_directory,"POSCAR"))
self.vs.incar.write(os.path.join(\
self.vs.simulation_directory,"INCAR"))
self.vs.kpoints.write(os.path.join(\
self.vs.simulation_directory,"KPOINTS"))
def submit_job(self):
pass
def postprocess(self):
pass
class VaspConvergeEncut(object):
pass
class VaspConvergeKpoints(object):
pass
class VaspMinimizeStructure(object):
pass
class VaspCalculateElastic(object):
pass
def calculate_bulk_properties(sim_dir):
os.mkdir(sim_dir)
if __name__ == '__main__':
structures = {}
structures['Ni_fcc_cubic'] = {'symbols':['Ni'],
'sg':'fcc',
'a0':3.508,
'shape':'cubic'}
structures['Ni_bcc_cubic'] = {'symbols':['Ni'],
'sg':'bcc',
'a0':3.508,
'shape':'cubic'}
structures['Ni_hcp_cubic'] = {'symbols':['Ni'],
'sg':'hcp',
'a0':3.508,
'shape':'cubic'}
structures['Ni_dia_cubic'] = {'symbols':['Ni'],
'sg':'diamond',
'a0':3.508,
'shape':'cubic'}
structures['Ni_sc_cubic'] = {'symbols':['Ni'],
'sg':'sc',
'a0':3.508,
'shape':'cubic'}
root_dir = os.getcwd()
for k,v in structures.items():
sim_dir = os.path.join(root_dir,k)
# add in aliases for space groups here
if v['sg'] in ['dia']:
v['sg'] = 'diamond'
if v['sg'] in ['fcc','bcc','diamond','sc','hcp']:
if isinstance(v['symbols'],list):
if len(v['symbols']) == 1:
v['symbols'] = v['symbols'][0]
else:
raise KeyError('cannot have more than one symbol in {}'.format(sg))
else:
raise KeyError('sg is an unsupported space group, passed in {}'.format(sg))
obj_poscar = None
if v['shape'] == 'cubic':
obj_poscar = vasp.Poscar(\
ase.build.bulk(\
v['symbols'],
v['sg'],
a=v['a0'],
cubic=True))
elif v['shape'] == 'ortho':
obj_poscar= vasp.Poscar(\
ase.build.bulk(\
v['symbols'],
v['sg'],
a=v['a0'],
ortho=True))
elif v['shape'] == 'prim':
obj_poscar = vasp.Poscar(\
ase.build.bulk(\
v['symbols'].
v['sg'],
a0=v['a0']))
else:
raise KeyError('sg is an unsupported space group, pass in {}'.format(sg))
VaspCalculateBulkProperties(sim_dir,obj_poscar)
| def __init__(self,sim_dir,obj_structure):
self.sim_dir = sim_dir
self.sim_task_list = ['min0','conv_encut','conv_kpoints','minf','elas']
self.dir_dict = {}
for task in self.sim_task_list:
self.dir_dict[task] = os.path.join(self.sim_dir,task)
# define the tasks
self.sim_task_class_name = {}
self.sim_task_class_name['min0'] = ['pypospack.task.vasp','VaspMinimizeStructure']
self.sim_task_class_name['conv_encut'] = ['pypospack.task.vasp','VaspConvergeEncut']
self.sim_task_class_name['conv_kpoints'] = ['pypospack.task.vasp','VaspConvergeKponts']
self.sim_task_class_name['minf'] = ['pypospack.task.vasp','VaspMinimizeStructure']
self.sim_task_class_name['elas'] = ['pypospack.task.vasp', 'VaspCalculateElastic']
# define dependency
self.sim_task_dependency = {}
self.sim_task_dependency['min'
self.min_0_dir = os.path.join(self.sim_dir,'min_0')
self.conv_encut_dir = os.path.join(self.sim_dir,'conv_encut')
self.conv_kpoints_dir = os.path.join(self.sim_dir,'conv_kpoints')
self.min_f_dir = os.path.join(self.sim_dir,'min_0')
self.elas_dir = os.path.join(self.sim_dir,'elas')
def run(self):
self.sims = {}
if os.path.exists(self.sim_dir):
for task in self.sim_task_list:
self.sim_task[task] = getattrself.sim_task_class_name
else:
os.mkdir(self.sim_dir)
self.sims['min_0'] = VaspMinimizeStructure(\
sim_dir = self.min_0_dir,
obj_structure = obj_structure)
if self.sims['min_0'].is_job_completed:
pass
else:
pass
self.sims['conv_encut'] = VaspConvergeEncut()
self.sims['conv_kpoints'] = VaspMinimizeStructure()
is_encut_complete = self.sims['conv_encut'].is_job_complete
is_kpoints_complete = self.sim['conv_kpoints'].is_job_complete
if is_encut_complete and is_kpoints_complete:
self.sims['min_f'] = VaspMinimizeStructure(\
sim_dir = self.min_f_dir,
obj_structure = obj_structure)
VaspConvergeKpoints()
VaspMinimizeStructure()
VaspCalculateElastic() |
resource_alicloud_oss_bucket_object_test.go | package alicloud
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"testing"
"github.com/alibaba/terraform-provider/alicloud/connectivity"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/hashicorp/terraform/terraform"
)
func TestAccAlicloudOssBucketObject_source(t *testing.T) {
tmpFile, err := ioutil.TempFile("", "tf-oss-object-test-acc-source")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
// first write some data to the tempfile just so it's not 0 bytes.
err = ioutil.WriteFile(tmpFile.Name(), []byte("{anything will do }"), 0644)
if err != nil {
t.Fatal(err)
}
var obj http.Header
bucket := fmt.Sprintf("tf-testacc-object-source-%d", acctest.RandInt())
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAlicloudOssBucketObjectDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: fmt.Sprintf(`
resource "alicloud_oss_bucket" "bucket" {
bucket = "%s"
}
resource "alicloud_oss_bucket_object" "source" {
bucket = "${alicloud_oss_bucket.bucket.bucket}"
key = "test-object-source-key"
source = "%s"
content_type = "binary/octet-stream"
}`, bucket, tmpFile.Name()),
Check: testAccCheckAlicloudOssBucketObjectExists(
"alicloud_oss_bucket_object.source", bucket, obj),
},
},
})
}
func TestAccAlicloudOssBucketObject_content(t *testing.T) {
var obj http.Header
bucket := fmt.Sprintf("tf-testacc-object-content-%d", acctest.RandInt())
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAlicloudOssBucketObjectDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: fmt.Sprintf(`
resource "alicloud_oss_bucket" "bucket" {
bucket = "%s"
}
resource "alicloud_oss_bucket_object" "content" {
bucket = "${alicloud_oss_bucket.bucket.bucket}"
key = "test-object-content-key"
content = "some words for test oss object content"
}`, bucket),
Check: testAccCheckAlicloudOssBucketObjectExists(
"alicloud_oss_bucket_object.content", bucket, obj),
},
},
})
}
func TestAccAlicloudOssBucketObject_acl(t *testing.T) {
tmpFile, err := ioutil.TempFile("", "tf-oss-object-test-acc-source")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpFile.Name())
// first write some data to the tempfile just so it's not 0 bytes.
err = ioutil.WriteFile(tmpFile.Name(), []byte("{anything will do }"), 0644)
if err != nil {
t.Fatal(err)
}
var obj http.Header
bucket := fmt.Sprintf("tf-testacc-bucket-%d", acctest.RandInt())
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckAlicloudOssBucketObjectDestroy,
Steps: []resource.TestStep{
resource.TestStep{
Config: fmt.Sprintf(`
resource "alicloud_oss_bucket" "bucket" {
bucket = "%s"
}
resource "alicloud_oss_bucket_object" "acl" {
bucket = "${alicloud_oss_bucket.bucket.bucket}"
key = "test-object-acl-key"
source = "%s"
acl = "%s"
}
`, bucket, tmpFile.Name(), "public-read"),
Check: resource.ComposeTestCheckFunc(
testAccCheckAlicloudOssBucketObjectExists(
"alicloud_oss_bucket_object.acl", bucket, obj),
resource.TestCheckResourceAttr(
"alicloud_oss_bucket_object.acl",
"acl",
"public-read"),
),
},
},
})
}
func testAccCheckAlicloudOssBucketObjectExists(n string, bucket string, obj http.Header) resource.TestCheckFunc {
providers := []*schema.Provider{testAccProvider}
return testAccCheckOssBucketObjectExistsWithProviders(n, bucket, obj, &providers)
}
func testAccCheckOssBucketObjectExistsWithProviders(n string, bucket string, obj http.Header, providers *[]*schema.Provider) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Not found: %s", n)
}
if rs.Primary.ID == "" {
return fmt.Errorf("No ID is set")
}
for _, provider := range *providers {
// Ignore if Meta is empty, this can happen for validation providers
if provider.Meta() == nil {
continue
}
client := provider.Meta().(*connectivity.AliyunClient)
raw, err := client.WithOssClient(func(ossClient *oss.Client) (interface{}, error) {
return ossClient.Bucket(bucket)
})
buck, _ := raw.(*oss.Bucket)
if err != nil {
return fmt.Errorf("Error getting bucket: %#v", err)
}
object, err := buck.GetObjectMeta(rs.Primary.ID)
log.Printf("[WARN]get oss bucket object %#v", bucket)
if err == nil {
if object != nil {
obj = object
return nil
}
continue
} else if err != nil {
return err
} | return fmt.Errorf("Bucket not found")
}
}
func testAccCheckAlicloudOssBucketObjectDestroy(s *terraform.State) error {
return testAccCheckOssBucketObjectDestroyWithProvider(s, testAccProvider)
}
func testAccCheckOssBucketObjectDestroyWithProvider(s *terraform.State, provider *schema.Provider) error {
client := provider.Meta().(*connectivity.AliyunClient)
ossService := OssService{client}
for _, rs := range s.RootModule().Resources {
if rs.Type != "alicloud_oss_bucket" {
continue
}
// Try to find the resource
bucket, err := ossService.QueryOssBucketById(rs.Primary.ID)
if err == nil {
if bucket.Name != "" {
return fmt.Errorf("Found instance: %s", bucket.Name)
}
}
// Verify the error is what we want
if IsExceptedErrors(err, []string{OssBucketNotFound}) {
continue
}
return err
}
return nil
} | }
|
Opengauss_Function_DDL_Create_Directory_Case0005.py | """
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type : 功能测试
Case Name : 创建目录对象,路径不合法,合理报错
Description :
1.路径含特殊字符
2.路径是相对路径
3.路径是符号链接
Expect :
1.目录创建失败
2.目录创建失败
3.目录创建失败
History :
"""
import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro
logger = Logger()
class Function(unittest.TestCase):
def setUp(self):
logger.info(f"-----{os.path.basename(__file__)}开始执行-----")
self.commonsh = CommonSH("dbuser")
self.userNode = Node("dbuser")
self.link_path = os.path.join("/home", f"{self.userNode.ssh_user}",
"my_link0005")
def test_directory(self):
text = "-----前置准备 创建符号链接-----"
logger.info(text)
self.soft_link = [f"rm -rf {self.link_path}",
f"ln -s /tmp {self.link_path}"]
for i in range(2):
msg = self.userNode.sh(self.soft_link[i]).result()
logger.info(msg)
self.assertTrue(len(msg.strip()) == 0, "执行失败" + text)
text = "-----step1+2+3:路径含特殊字符/路径是相对路径/路径是符号连接;expect:-----"
logger.info(text)
error_path = ["/&~?!tmp/", "../tmp/", f"{self.link_path}"]
error_msg = ['illegal string: "&"',
"ERROR: directory path cannot be relative",
"is not a directory, please check"]
for j in range(3):
sql_cmd = f"create or replace directory dir as '{error_path[j]}';"
msg1 = self.commonsh.execut_db_sql(sql_cmd)
logger.info(msg1)
self.assertTrue(error_msg[j] in msg1, "执行失败" + text)
def tearDown(self):
text = "清理环境"
logger.info(text)
result = self.userNode.sh(self.soft_link[0]).result()
logger.info(result) | self.assertTrue(len(result.strip()) == 0, "执行失败" + text)
logger.info(f"-----{os.path.basename(__file__)}执行结束-----") |
|
listwatch.go | // Copyright 2016 The prometheus-operator 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.
package listwatch
import (
"context"
"fmt"
"strings"
"sync"
"github.com/go-kit/kit/log"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/cache"
)
// NewUnprivilegedNamespaceListWatchFromClient mimics
// cache.NewListWatchFromClient.
// It allows for the creation of a cache.ListWatch for namespaces from a client
// that does not have `List` privileges. If the slice of namespaces contains
// only v1.NamespaceAll, then this func assumes that the client has List and
// Watch privileges and returns a regular cache.ListWatch, since there is no
// other way to get all namespaces.
//
// The allowed namespaces and denied namespaces are mutually exclusive.
// See NewFilteredUnprivilegedNamespaceListWatchFromClient for a description on how they are applied.
func NewUnprivilegedNamespaceListWatchFromClient(l log.Logger, c cache.Getter, allowedNamespaces, deniedNamespaces map[string]struct{}, fieldSelector fields.Selector) cache.ListerWatcher {
optionsModifier := func(options *metav1.ListOptions) {
options.FieldSelector = fieldSelector.String()
}
return NewFilteredUnprivilegedNamespaceListWatchFromClient(l, c, allowedNamespaces, deniedNamespaces, optionsModifier)
}
// NewFilteredUnprivilegedNamespaceListWatchFromClient mimics
// cache.NewUnprivilegedNamespaceListWatchFromClient.
// It allows for the creation of a cache.ListWatch for allowed or denied namespaces
// from a client that does not have `List` privileges.
//
// If the given allowed namespaces contain only v1.NamespaceAll,
// then this function assumes that the client has List and
// Watch privileges and returns a regular cache.ListWatch, since there is no
// other way to get all namespaces.
//
// The given allowed and denied namespaces are mutually exclusive.
// If allowed namespaces contain multiple items, the given denied namespaces have no effect.
// If the allowed namespaces includes exactly one entry with the value v1.NamespaceAll (empty string),
// the given denied namespaces are applied.
func NewFilteredUnprivilegedNamespaceListWatchFromClient(l log.Logger, c cache.Getter, allowedNamespaces, deniedNamespaces map[string]struct{}, optionsModifier func(options *metav1.ListOptions)) cache.ListerWatcher {
// If the only namespace given is `v1.NamespaceAll`, then this
// cache.ListWatch must be privileged. In this case, return a regular
// cache.ListWatch decorated with a denylist watcher
// filtering the given denied namespaces.
if IsAllNamespaces(allowedNamespaces) {
return newDenylistListerWatcher(
l,
deniedNamespaces,
cache.NewFilteredListWatchFromClient(c, "namespaces", metav1.NamespaceAll, optionsModifier),
)
}
listFunc := func(options metav1.ListOptions) (runtime.Object, error) {
optionsModifier(&options)
list := &v1.NamespaceList{}
for name := range allowedNamespaces {
result := &v1.Namespace{}
err := c.Get().
Resource("namespaces").
Name(name).
VersionedParams(&options, scheme.ParameterCodec).
Do(context.TODO()).
Into(result)
if err != nil {
return nil, err
}
list.Items = append(list.Items, *result)
}
return list, nil
}
watchFunc := func(_ metav1.ListOptions) (watch.Interface, error) {
// Since the client does not have Watch privileges, do not
// actually watch anything. Use a watch.FakeWatcher here to
// implement watch.Interface but not send any events.
return watch.NewFake(), nil
}
return &cache.ListWatch{ListFunc: listFunc, WatchFunc: watchFunc}
}
// MultiNamespaceListerWatcher takes allowed and denied namespaces and a
// cache.ListerWatcher generator func and returns a single cache.ListerWatcher
// capable of operating on multiple namespaces.
//
// Allowed namespaces and denied namespaces are mutually exclusive.
// If allowed namespaces contain multiple items, the given denied namespaces have no effect.
// If the allowed namespaces includes exactly one entry with the value v1.NamespaceAll (empty string),
// the given denied namespaces are applied.
func MultiNamespaceListerWatcher(l log.Logger, allowedNamespaces, deniedNamespaces map[string]struct{}, f func(string) cache.ListerWatcher) cache.ListerWatcher {
// If there is only one namespace then there is no need to create a
// multi lister watcher proxy.
if IsAllNamespaces(allowedNamespaces) {
return newDenylistListerWatcher(l, deniedNamespaces, f(v1.NamespaceAll))
}
if len(allowedNamespaces) == 1 {
for n := range allowedNamespaces {
return f(n)
}
}
var lws []cache.ListerWatcher
for n := range allowedNamespaces {
lws = append(lws, f(n))
}
return multiListerWatcher(lws)
}
// multiListerWatcher abstracts several cache.ListerWatchers, allowing them
// to be treated as a single cache.ListerWatcher.
type multiListerWatcher []cache.ListerWatcher
// List implements the ListerWatcher interface.
// It combines the output of the List method of every ListerWatcher into
// a single result.
func (mlw multiListerWatcher) List(options metav1.ListOptions) (runtime.Object, error) {
l := metav1.List{}
resourceVersions := sets.NewString()
for _, lw := range mlw {
list, err := lw.List(options)
if err != nil {
return nil, err
}
items, err := meta.ExtractList(list)
if err != nil {
return nil, err
}
metaObj, err := meta.ListAccessor(list)
if err != nil {
return nil, err
}
for _, item := range items {
l.Items = append(l.Items, runtime.RawExtension{Object: item.DeepCopyObject()})
}
if !resourceVersions.Has(metaObj.GetResourceVersion()) {
resourceVersions.Insert(metaObj.GetResourceVersion())
}
}
// Combine the resource versions so that the composite Watch method can
// distribute appropriate versions to each underlying Watch func.
l.ListMeta.ResourceVersion = strings.Join(resourceVersions.List(), "/")
return &l, nil
}
// Watch implements the ListerWatcher interface.
// It returns a watch.Interface that combines the output from the
// watch.Interface of every cache.ListerWatcher into a single result chan.
func (mlw multiListerWatcher) Watch(options metav1.ListOptions) (watch.Interface, error) {
var resourceVersions string
// Allow resource versions to be "".
if options.ResourceVersion != "" {
rvs := strings.Split(options.ResourceVersion, "/")
if len(rvs) > 1 {
return nil, fmt.Errorf("expected resource version to have 1 part, got %d", len(rvs))
}
resourceVersions = options.ResourceVersion
}
return newMultiWatch(mlw, resourceVersions, options)
}
// multiWatch abstracts multiple watch.Interface's, allowing them
// to be treated as a single watch.Interface.
type multiWatch struct {
result chan watch.Event
stopped chan struct{}
stoppers []func()
}
// newMultiWatch returns a new multiWatch or an error if one of the underlying
// Watch funcs errored.
func newMultiWatch(lws []cache.ListerWatcher, resourceVersions string, options metav1.ListOptions) (*multiWatch, error) {
var (
result = make(chan watch.Event)
stopped = make(chan struct{})
stoppers []func()
wg sync.WaitGroup
)
wg.Add(len(lws))
for _, lw := range lws {
o := options.DeepCopy()
o.ResourceVersion = resourceVersions
w, err := lw.Watch(*o)
if err != nil |
go func() {
defer wg.Done()
for {
event, ok := <-w.ResultChan()
if !ok {
return
}
select {
case result <- event:
case <-stopped:
return
}
}
}()
stoppers = append(stoppers, w.Stop)
}
// result chan must be closed,
// once all event sender goroutines exited.
go func() {
wg.Wait()
close(result)
}()
return &multiWatch{
result: result,
stoppers: stoppers,
stopped: stopped,
}, nil
}
// ResultChan implements the watch.Interface interface.
func (mw *multiWatch) ResultChan() <-chan watch.Event {
return mw.result
}
// Stop implements the watch.Interface interface.
// It stops all of the underlying watch.Interfaces and closes the backing chan.
// Can safely be called more than once.
func (mw *multiWatch) Stop() {
select {
case <-mw.stopped:
// nothing to do, we are already stopped
default:
for _, stop := range mw.stoppers {
stop()
}
close(mw.stopped)
}
return
}
// IsAllNamespaces checks if the given map of namespaces
// contains only v1.NamespaceAll.
func IsAllNamespaces(namespaces map[string]struct{}) bool {
_, ok := namespaces[v1.NamespaceAll]
return ok && len(namespaces) == 1
}
// IdenticalNamespaces returns true if a and b are identical.
func IdenticalNamespaces(a, b map[string]struct{}) bool {
if len(a) != len(b) {
return false
}
for k := range a {
if _, ok := b[k]; !ok {
return false
}
}
return true
}
| {
return nil, err
} |
test_describe_availability_zone.py | # Copyright 2017-2018 Amazon.com, Inc. and its affiliates. All Rights Reserved.
#
# Licensed under the MIT License. See the LICENSE accompanying this file
# for the specific language governing permissions and limitations under
# the License.
import mount_efs
import pytest
from botocore.exceptions import ClientError, EndpointConnectionError, NoCredentialsError
from .. import utils
MOCK_EC2_AGENT = "fake-client"
AZ_NAME = "us-east-2b"
AZ_ID = "use2-az2"
OPERATION_NAME = "DescribeAvailabilityZones"
def _test_describe_availability_zones_response(
mocker,
dryrun_effect,
response,
expected_describe_time,
desired_az_id=None,
desired_exception=None,
desired_message=None,
):
describe_mock = mocker.patch(
"mount_efs.ec2_describe_availability_zones_helper",
side_effect=[dryrun_effect, response],
)
if desired_exception:
assert desired_message != None
with pytest.raises(mount_efs.FallbackException) as excinfo:
mount_efs.get_az_id_by_az_name(MOCK_EC2_AGENT, AZ_NAME)
assert desired_message in str(excinfo)
else:
az_id = mount_efs.get_az_id_by_az_name(MOCK_EC2_AGENT, AZ_NAME)
assert az_id == desired_az_id
utils.assert_called_n_times(describe_mock, expected_describe_time)
def test_describe_availability_zones_dryrun_succeed_return_correct(mocker):
dryrun_exception_response = {
"Error": {"Code": "DryRunOperation", "Message": "DryRunOperation"}
}
response = {
"AvailabilityZones": [
{
"Messages": [],
"ZoneId": AZ_ID,
"State": "available",
"ZoneName": AZ_NAME,
"RegionName": "us-east-2",
}
]
}
_test_describe_availability_zones_response(
mocker,
ClientError(dryrun_exception_response, OPERATION_NAME),
response,
2,
AZ_ID,
)
def test_describe_availability_zones_dryrun_failed_unauthorized_operation(mocker):
dryrun_exception_response = {
"Error": {"Code": "UnauthorizedOperation", "Message": "UnauthorizedOperation"}
}
_test_describe_availability_zones_response(
mocker,
ClientError(dryrun_exception_response, OPERATION_NAME),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message="Unauthorized to perform operation",
)
def | (mocker):
dryrun_exception_response = {
"Error": {"Code": "InvalidParameterValue", "Message": "InvalidParameterValue"}
}
_test_describe_availability_zones_response(
mocker,
ClientError(dryrun_exception_response, OPERATION_NAME),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message="Invalid availability zone",
)
def test_describe_availability_zones_dryrun_failed_service_unavailable(mocker):
dryrun_exception_response = {
"Error": {
"Code": "ServiceUnavailableException",
"Message": "ServiceUnavailableException",
}
}
_test_describe_availability_zones_response(
mocker,
ClientError(dryrun_exception_response, OPERATION_NAME),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message="The ec2 service cannot",
)
def test_describe_availability_zones_dryrun_failed_access_denied(mocker):
exception_message = "is not authorized to perform"
dryrun_exception_response = {
"Error": {"Code": "AccessDeniedException", "Message": exception_message}
}
_test_describe_availability_zones_response(
mocker,
ClientError(dryrun_exception_response, OPERATION_NAME),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message=exception_message,
)
def test_describe_availability_zones_dryrun_failed_unknown_exception(mocker):
dryrun_exception_response = {
"Error": {"Code": "UnknownException", "Message": "UnknownException"}
}
_test_describe_availability_zones_response(
mocker,
ClientError(dryrun_exception_response, OPERATION_NAME),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message="Unexpected error",
)
def test_describe_availability_zones_dryrun_failed_no_credential_error(mocker):
_test_describe_availability_zones_response(
mocker,
NoCredentialsError(),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message="confirm your aws credentials are properly configured",
)
def test_describe_availability_zones_failed_unknown_error(mocker):
_test_describe_availability_zones_response(
mocker,
Exception("Unknown"),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message="Unknown error",
)
def test_describe_availability_zones_failed_endpoing_error(mocker):
_test_describe_availability_zones_response(
mocker,
EndpointConnectionError(endpoint_url="https://efs.us-east-1.com"),
None,
1,
desired_exception=mount_efs.FallbackException,
desired_message="Could not connect to the endpoint",
)
def test_describe_availability_zones_return_empty_az_info(mocker):
dryrun_exception_response = {
"Error": {"Code": "DryRunOperation", "Message": "DryRunOperation"}
}
response = {"AvailabilityZones": []}
_test_describe_availability_zones_response(
mocker,
ClientError(dryrun_exception_response, OPERATION_NAME),
response,
2,
None,
)
def test_describe_availability_zones_return_none_az_info(mocker):
dryrun_exception_response = {
"Error": {"Code": "DryRunOperation", "Message": "DryRunOperation"}
}
_test_describe_availability_zones_response(
mocker, ClientError(dryrun_exception_response, OPERATION_NAME), None, 2, None
)
| test_describe_availability_zones_dryrun_failed_invalid_az_name |
index.ts | // Copyright 2015-2021 Swim 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.
export {HtmlConverterSpec} from "./HtmlConverterSpec";
export {CssConverterSpec} from "./CssConverterSpec"; | export {ConverterSuite} from "./ConverterSuite"; |
|
bytereader.go | // Copyright 2019+ Klaus Post. All rights reserved.
// License information can be found in the LICENSE file.
// Based on work by Yann Collet, released under BSD License.
package zstd
import "encoding/binary"
// byteReader provides a byte reader that reads
// little endian values from a byte stream.
// The input stream is manually advanced.
// The reader performs no bounds checks.
type byteReader struct {
b []byte
off int
}
// init will initialize the reader and set the input.
func (b *byteReader) init(in []byte) {
b.b = in
b.off = 0
}
// advance the stream b n bytes.
func (b *byteReader) advance(n uint) {
b.off += int(n)
}
// overread returns whether we have advanced too far.
func (b *byteReader) overread() bool {
return b.off > len(b.b)
}
// Int32 returns a little endian int32 starting at current offset.
func (b byteReader) Int32() int32 {
b2 := b.b[b.off : b.off+4 : b.off+4]
v3 := int32(b2[3])
v2 := int32(b2[2])
v1 := int32(b2[1])
v0 := int32(b2[0])
return v0 | (v1 << 8) | (v2 << 16) | (v3 << 24)
}
// Uint8 returns the next byte | return v
}
// Uint32 returns a little endian uint32 starting at current offset.
func (b byteReader) Uint32() uint32 {
if r := b.remain(); r < 4 {
// Very rare
v := uint32(0)
for i := 1; i <= r; i++ {
v = (v << 8) | uint32(b.b[len(b.b)-i])
}
return v
}
return binary.LittleEndian.Uint32(b.b[b.off : b.off+4])
}
// unread returns the unread portion of the input.
func (b byteReader) unread() []byte {
return b.b[b.off:]
}
// remain will return the number of bytes remaining.
func (b byteReader) remain() int {
return len(b.b) - b.off
} | func (b *byteReader) Uint8() uint8 {
v := b.b[b.off] |
410.6f88487e.async.js | (window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[410],{tvlV:function(c,e,t){"use strict";t.r(e);var a=t("q1tI"),n={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32zm-600 72h560v208H232V136zm560 480H232V408h560v208zm0 272H232V680h560v208zM496 208H312c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8zM312 544h184c4.4 0 8-3.6 8-8v-48c0-4.4-3.6-8-8-8H312c-4.4 0-8 3.6-8 8v48c0 4.4 3.6 8 8 8zm328 244a40 40 0 1080 0 40 40 0 10-80 0z"}}]},name:"hdd",theme:"outlined"},d=n,i=t("6VBw"),s=function(c,e){return a["createElement"](i["a"],Object.assign({},c,{ref:e,icon:d}))};s.displayName="HddOutlined";e["default"]=a["forwardRef"](s)}}]); | ||
mpsc_list_v1.rs | use std::cell::UnsafeCell;
use std::ptr;
use std::sync::atomic::{AtomicPtr, Ordering};
use std::thread;
use crossbeam::utils::CachePadded;
struct Node<T> {
prev: *mut Node<T>,
next: AtomicPtr<Node<T>>,
value: Option<T>,
refs: usize,
}
// linked bit is MSB, ref count is 2 for handle and list
const REF_INIT: usize = 0x1000_0002;
const REF_COUNT_MASK: usize = 0x0FFF_FFFF;
impl<T> Node<T> {
unsafe fn new(v: Option<T>) -> *mut Node<T> {
Box::into_raw(Box::new(Node {
prev: ptr::null_mut(),
next: AtomicPtr::new(ptr::null_mut()),
value: v,
refs: REF_INIT,
}))
}
}
pub struct Entry<T>(ptr::NonNull<Node<T>>);
unsafe impl<T: Sync> Sync for Entry<T> {}
impl<T> Entry<T> {
// get the internal data mut ref
// must make sure it's not popped by the consumer
#[inline]
pub unsafe fn with_mut_data<F>(&self, f: F)
where
F: FnOnce(&mut T),
{
let node = &mut *self.0.as_ptr();
let data = node.value.as_mut().expect("Node value is None");
f(data);
}
/// judge if the node is still linked in the list
#[inline]
pub fn is_link(&self) -> bool {
let node = unsafe { &mut *self.0.as_ptr() };
node.refs & !REF_COUNT_MASK != 0
}
#[inline]
pub fn into_ptr(self) -> *mut Self {
let ret = self.0.as_ptr() as *mut Self;
::std::mem::forget(self);
ret
}
#[inline]
pub unsafe fn from_ptr(ptr: *mut Self) -> Self {
Entry(ptr::NonNull::new_unchecked(ptr as *mut Node<T>))
}
// remove the entry from it's list and return the contained value
// it's only safe for the consumer that call pop()
pub fn remove(mut self) -> Option<T> {
unsafe {
let node = self.0.as_mut();
| }
// this is a new tail just return
if node.prev.is_null() {
return None;
}
let next = node.next.load(Ordering::Acquire);
let prev = &mut *node.prev;
// here we must make sure the next is not equal to null
// other thread may modify the next value if it's null
// it's safe to remove the node that between tail and head
// but not safe to remove the last node since it's volatile
// when next is null, the remove takes no action
// and expect pop() would eventually consume the data
// this is mainly used in the timer list, so it's rarely
// the next is not contention for that we have wait some time already
// leave the last node not removed also persist the queue for a while
// that prevent frequent queue create and destroy
if !next.is_null() {
// clear the link bit
node.refs &= REF_COUNT_MASK;
// this is not the last node, just unlink it
(*next).prev = prev;
prev.next.store(next, Ordering::Release);
let ret = node.value.take();
// since self is not dropped, below is always false
node.refs -= 1;
if node.refs == 0 {
// release the node only when the ref count becomes 0
let _: Box<Node<T>> = Box::from_raw(node);
}
return ret;
}
}
None
}
}
impl<T> Drop for Entry<T> {
// only call this drop in the same thread, or you must make sure it happens with no contension
// running in a coroutine is a kind of sequential operation, so it can safely drop there after
// returning from "kernel"
fn drop(&mut self) {
let node = unsafe { self.0.as_mut() };
// dec the ref count of node
node.refs -= 1;
if node.refs == 0 {
// release the node
let _: Box<Node<T>> = unsafe { Box::from_raw(node) };
}
}
}
unsafe impl<T: Send> Send for Entry<T> {}
/// The multi-producer single-consumer structure. This is not cloneable, but it
/// may be safely shared so long as it is guaranteed that there is only one
/// popper at a time (many pushers are allowed).
pub struct Queue<T> {
head: CachePadded<AtomicPtr<Node<T>>>,
tail: UnsafeCell<*mut Node<T>>,
}
unsafe impl<T> Send for Queue<T> {}
unsafe impl<T> Sync for Queue<T> {}
impl<T> Queue<T> {
/// Creates a new queue that is safe to share among multiple producers and
/// one consumer.
pub fn new() -> Queue<T> {
let stub = unsafe { Node::new(None) };
// there is no handle for the node, so it's ref should be 1 now
unsafe { &mut *stub }.refs = 1;
Queue {
head: AtomicPtr::new(stub).into(),
tail: UnsafeCell::new(stub),
}
}
/// Pushes a new value onto this queue.
/// if the new node is head, indicate a true
/// this is used to update the BH if it's a new head
pub fn push(&self, t: T) -> (Entry<T>, bool) {
unsafe {
let node = Node::new(Some(t));
let prev = self.head.swap(node, Ordering::AcqRel);
(*node).prev = prev;
(*prev).next.store(node, Ordering::Release);
let tail = *self.tail.get();
let is_head = tail == prev;
(Entry(ptr::NonNull::new_unchecked(node)), is_head)
}
}
/// if the queue is empty
#[inline]
pub fn is_empty(&self) -> bool {
let tail = unsafe { *self.tail.get() };
// the list is empty
self.head.load(Ordering::Acquire) == tail
}
/// get the head ref
#[inline]
pub fn peek(&self) -> Option<&T> {
unsafe {
let tail = *self.tail.get();
// the list is empty
if self.head.load(Ordering::Acquire) == tail {
return None;
}
// spin until tail next become non-null
let mut next;
let mut i = 0;
loop {
next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
break;
}
i += 1;
if i > 500 {
thread::yield_now();
i = 0;
}
}
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
(*next).value.as_ref()
}
}
pub fn pop_if<F>(&self, f: &F) -> Option<T>
where
F: Fn(&T) -> bool,
{
unsafe {
let tail = *self.tail.get();
// the list is empty
if self.head.load(Ordering::Acquire) == tail {
return None;
}
// spin until tail next become non-null
let mut next;
let mut i = 0;
loop {
next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
break;
}
i += 1;
if i > 100 {
thread::yield_now();
i = 0;
}
}
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
let v = (*next).value.as_ref().unwrap();
if !f(v) {
// no pop
return None;
}
// clear the link bit
assert!((*tail).refs & REF_COUNT_MASK != 0);
(*tail).refs &= REF_COUNT_MASK;
// clear the prev pointer indicate a new end point
(*next).prev = ptr::null_mut();
// move the tail to next
*self.tail.get() = next;
// we take the next value, this is why use option to host the value
let ret = (*next).value.take().unwrap();
(*tail).refs -= 1;
if (*tail).refs == 0 {
// release the node only when the ref count becomes 0
let _: Box<Node<T>> = Box::from_raw(tail);
}
Some(ret)
}
}
/// Pops some data from this queue.
pub fn pop(&self) -> Option<T> {
unsafe {
let tail = *self.tail.get();
// the list is empty
if self.head.load(Ordering::Acquire) == tail {
return None;
}
// clear the link bit
assert!((*tail).refs & REF_COUNT_MASK != 0);
(*tail).refs &= REF_COUNT_MASK;
// spin until tail next become non-null
let mut next;
let mut i = 0;
loop {
next = (*tail).next.load(Ordering::Acquire);
if !next.is_null() {
break;
}
i += 1;
if i > 100 {
thread::yield_now();
i = 0;
}
}
(*next).prev = ptr::null_mut();
// move the tail to next
*self.tail.get() = next;
assert!((*tail).value.is_none());
assert!((*next).value.is_some());
// we tack the next value, this is why use option to host the value
let ret = (*next).value.take().unwrap();
(*tail).refs -= 1;
if (*tail).refs == 0 {
// release the node only when the ref count becomes 0
let _: Box<Node<T>> = Box::from_raw(tail);
}
Some(ret)
}
}
}
impl<T> Default for Queue<T> {
fn default() -> Self {
Queue::new()
}
}
impl<T> Drop for Queue<T> {
fn drop(&mut self) {
while let Some(_) = self.pop() {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::mpsc::channel;
use std::sync::Arc;
use std::thread;
#[test]
fn test_queue() {
let q: Queue<usize> = Queue::new();
assert_eq!(q.pop(), None);
q.push(1);
q.push(2);
assert_eq!(q.pop(), Some(1));
assert_eq!(q.pop(), Some(2));
assert_eq!(q.is_empty(), true);
let a = q.push(3);
let b = q.push(4);
assert_eq!(a.1, true);
assert_eq!(a.0.remove(), Some(3));
assert_eq!(b.1, false);
assert_eq!(b.0.remove(), None);
assert_eq!(q.pop(), Some(4));
assert_eq!(q.is_empty(), true);
q.push(5);
q.push(6);
q.push(7);
let co = |v: &usize| *v < 7;
assert_eq!(q.peek(), Some(&5));
assert_eq!(q.pop_if(&co), Some(5));
assert_eq!(q.pop_if(&co), Some(6));
assert_eq!(q.pop_if(&co), None);
assert_eq!(q.pop(), Some(7));
}
#[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000;
let q = Queue::new();
match q.pop() {
None => {}
Some(..) => panic!(),
}
let (tx, rx) = channel();
let q = Arc::new(q);
for _ in 0..nthreads {
let tx = tx.clone();
let q = q.clone();
thread::spawn(move || {
for i in 0..nmsgs {
q.push(i);
}
tx.send(()).unwrap();
});
}
let mut i = 0;
while i < nthreads * nmsgs {
match q.pop() {
None => {}
Some(_) => i += 1,
}
}
drop(tx);
for _ in 0..nthreads {
rx.recv().unwrap();
}
}
} | // when the link bit is cleared, next and prev is no longer valid
if node.refs & !REF_COUNT_MASK == 0 {
// already removed
return None; |
coverage.py | # -*- coding: utf-8 -*-
"""
This module contains methods for processing and aggregating coverage files generated by ``bedtools``.
"""
import pandas as pd
import numpy as np
import re
import os
from .reader import read_sample_info
cov_cols = ['Target', 'min_coverage', 'sum_coverage', 'basepairs', 'cov_per_bp', 'fraction_zero_coverage', 'fraction_10x_coverage', 'fraction_30x_coverage']
cov_cols_dtypes = dict(zip(cov_cols, [str, int, int, int, float, float]))
def fraction_zero_coverage(coverage):
"""Calculate fraction of bases with coverage 0."""
return 1.0 * (coverage == 0).sum() / len(coverage)
def fraction_10x_coverage(coverage):
"""Calculate fraction of bases with coverage 10 or more."""
return 1.0 * (coverage >= 10).sum() / len(coverage)
def fraction_30x_coverage(coverage):
"""Calculate fraction of bases with coverage 30 or more."""
return 1.0 * (coverage >= 30).sum() / len(coverage)
def process_file(input: str, output: str):
"""Read raw bedtools coverage file, calculate summary statistics and output them as CSV file.
Args:
input: path to a bedtools coverage file
output: path to the summary CSV file
"""
# read bedtools output
depth = pd.read_csv(input, sep='\t', names = ['chr', 'start_0', 'end', 'id', 'score', 'strand', 'position', 'coverage'], low_memory=False) |
# make id index into normal column, then reset column names
summary.reset_index(level=0, inplace=True)
summary.columns = cov_cols
# write file
summary.to_csv(output, index = False)
def aggregate(input, output):
"""Read coverage summary files and create aggregate files.
Args:
input: dict containing 'csvs', the list of csvs fils to aggregate, and optionally 'sample_info', a table with additional sample annotation
output: dict containing paths for output files: merged, min_coverage, cov_per_bp, fraction_zero_coverage
"""
# load sample information table
sample_info = None
if 'sample_info' in input and len(input['sample_info']) > 0:
sample_info = read_sample_info(input['sample_info'][0])
merged = None
for file in input['csvs']:
sname = os.path.basename(file)
sname = re.sub(r'\.coverage\.csv$', '', sname)
print('Reading', file, 'for', sname, '...')
df = pd.read_csv(file,
index_col = False,
dtype = cov_cols_dtypes)
df['Sample'] = sname
print(sname, 'coverage data shape:', str(df.shape))
if merged is None:
merged = df
else:
merged = merged.append(df, ignore_index = True)
assert merged is not None, \
'\n\nABORTED: Did not find any coverage data!\n\n'
print('Merged data shape:', str(merged.shape))
print(merged.head())
print('Duplicated:')
print(merged[merged.duplicated(['Target', 'Sample'], keep=False)])
if sample_info is not None:
merged = merged.join(sample_info, on = ['Sample', 'Target'], how = 'left')
# make matrices
for column in ['min_coverage', 'cov_per_bp', 'fraction_zero_coverage']:
pivoted = merged.pivot(index='Target', columns='Sample', values=column)
print('Made pivot table for', column, ' with shape', str(pivoted.shape))
pivoted.to_csv(output[column])
print(output[column])
# output full merged data set
merged.to_csv(output['merged'], index = False) |
# summarize
summary = depth.groupby('id').aggregate({'coverage': [np.min, np.sum, len, np.mean, fraction_zero_coverage, fraction_10x_coverage, fraction_30x_coverage]}) |
elements-text.js | // Up-to-date as of 2013-04-19.
var textElements = {
a: {
// Conforming
target: "string",
download: "string",
ping: "string",
rel: "string",
relList: {type: "tokenlist", domAttrName: "rel"},
hreflang: "string",
type: "string",
referrerPolicy: {type: "enum", keywords: ["", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url"]},
// HTMLHyperlinkElementUtils
href: "url",
// Obsolete
coords: "string",
charset: "string",
name: "string",
rev: "string",
shape: "string",
},
em: {},
strong: {}, | cite: {},
q: {
cite: "url",
},
dfn: {},
abbr: {},
ruby: {},
rt: {},
rp: {},
data: {
value: "string",
},
time: {
dateTime: "string",
},
code: {},
var: {},
samp: {},
kbd: {},
sub: {},
sup: {},
i: {},
b: {},
u: {},
mark: {},
bdi: {},
bdo: {},
span: {},
br: {
// Obsolete
clear: "string",
},
wbr: {},
};
mergeElements(textElements); | small: {},
s: {}, |
syserrintset.rs | #[doc = "Writer for register SYSERRINTSET"]
pub type W = crate::W<u32, super::SYSERRINTSET>;
#[doc = "Register SYSERRINTSET `reset()`'s with value 0"]
impl crate::ResetValue for super::SYSERRINTSET {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Write proxy for field `EPERRINTSET0`"]
pub struct EPERRINTSET0_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET1`"]
pub struct EPERRINTSET1_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET2`"]
pub struct EPERRINTSET2_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET3`"]
pub struct EPERRINTSET3_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET4`"]
pub struct EPERRINTSET4_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET5`"]
pub struct EPERRINTSET5_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET5_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET6`"]
pub struct EPERRINTSET6_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET6_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET7`"]
pub struct EPERRINTSET7_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET7_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W |
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET8`"]
pub struct EPERRINTSET8_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET8_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET9`"]
pub struct EPERRINTSET9_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET9_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET10`"]
pub struct EPERRINTSET10_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET10_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET11`"]
pub struct EPERRINTSET11_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET11_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET12`"]
pub struct EPERRINTSET12_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET12_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET13`"]
pub struct EPERRINTSET13_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET13_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET14`"]
pub struct EPERRINTSET14_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET14_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET15`"]
pub struct EPERRINTSET15_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET15_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET16`"]
pub struct EPERRINTSET16_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET16_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET17`"]
pub struct EPERRINTSET17_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET17_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET18`"]
pub struct EPERRINTSET18_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET18_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET19`"]
pub struct EPERRINTSET19_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET19_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET20`"]
pub struct EPERRINTSET20_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET20_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET21`"]
pub struct EPERRINTSET21_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET21_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET22`"]
pub struct EPERRINTSET22_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET22_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET23`"]
pub struct EPERRINTSET23_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET23_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET24`"]
pub struct EPERRINTSET24_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET24_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET25`"]
pub struct EPERRINTSET25_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET25_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET26`"]
pub struct EPERRINTSET26_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET26_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET27`"]
pub struct EPERRINTSET27_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET27_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET28`"]
pub struct EPERRINTSET28_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET28_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET29`"]
pub struct EPERRINTSET29_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET29_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET30`"]
pub struct EPERRINTSET30_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET30_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 30)) | (((value as u32) & 0x01) << 30);
self.w
}
}
#[doc = "Write proxy for field `EPERRINTSET31`"]
pub struct EPERRINTSET31_W<'a> {
w: &'a mut W,
}
impl<'a> EPERRINTSET31_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl W {
#[doc = "Bit 0 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset0(&mut self) -> EPERRINTSET0_W {
EPERRINTSET0_W { w: self }
}
#[doc = "Bit 1 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset1(&mut self) -> EPERRINTSET1_W {
EPERRINTSET1_W { w: self }
}
#[doc = "Bit 2 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset2(&mut self) -> EPERRINTSET2_W {
EPERRINTSET2_W { w: self }
}
#[doc = "Bit 3 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset3(&mut self) -> EPERRINTSET3_W {
EPERRINTSET3_W { w: self }
}
#[doc = "Bit 4 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset4(&mut self) -> EPERRINTSET4_W {
EPERRINTSET4_W { w: self }
}
#[doc = "Bit 5 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset5(&mut self) -> EPERRINTSET5_W {
EPERRINTSET5_W { w: self }
}
#[doc = "Bit 6 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset6(&mut self) -> EPERRINTSET6_W {
EPERRINTSET6_W { w: self }
}
#[doc = "Bit 7 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset7(&mut self) -> EPERRINTSET7_W {
EPERRINTSET7_W { w: self }
}
#[doc = "Bit 8 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset8(&mut self) -> EPERRINTSET8_W {
EPERRINTSET8_W { w: self }
}
#[doc = "Bit 9 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset9(&mut self) -> EPERRINTSET9_W {
EPERRINTSET9_W { w: self }
}
#[doc = "Bit 10 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset10(&mut self) -> EPERRINTSET10_W {
EPERRINTSET10_W { w: self }
}
#[doc = "Bit 11 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset11(&mut self) -> EPERRINTSET11_W {
EPERRINTSET11_W { w: self }
}
#[doc = "Bit 12 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset12(&mut self) -> EPERRINTSET12_W {
EPERRINTSET12_W { w: self }
}
#[doc = "Bit 13 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset13(&mut self) -> EPERRINTSET13_W {
EPERRINTSET13_W { w: self }
}
#[doc = "Bit 14 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset14(&mut self) -> EPERRINTSET14_W {
EPERRINTSET14_W { w: self }
}
#[doc = "Bit 15 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset15(&mut self) -> EPERRINTSET15_W {
EPERRINTSET15_W { w: self }
}
#[doc = "Bit 16 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset16(&mut self) -> EPERRINTSET16_W {
EPERRINTSET16_W { w: self }
}
#[doc = "Bit 17 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset17(&mut self) -> EPERRINTSET17_W {
EPERRINTSET17_W { w: self }
}
#[doc = "Bit 18 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset18(&mut self) -> EPERRINTSET18_W {
EPERRINTSET18_W { w: self }
}
#[doc = "Bit 19 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset19(&mut self) -> EPERRINTSET19_W {
EPERRINTSET19_W { w: self }
}
#[doc = "Bit 20 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset20(&mut self) -> EPERRINTSET20_W {
EPERRINTSET20_W { w: self }
}
#[doc = "Bit 21 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset21(&mut self) -> EPERRINTSET21_W {
EPERRINTSET21_W { w: self }
}
#[doc = "Bit 22 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset22(&mut self) -> EPERRINTSET22_W {
EPERRINTSET22_W { w: self }
}
#[doc = "Bit 23 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset23(&mut self) -> EPERRINTSET23_W {
EPERRINTSET23_W { w: self }
}
#[doc = "Bit 24 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset24(&mut self) -> EPERRINTSET24_W {
EPERRINTSET24_W { w: self }
}
#[doc = "Bit 25 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset25(&mut self) -> EPERRINTSET25_W {
EPERRINTSET25_W { w: self }
}
#[doc = "Bit 26 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset26(&mut self) -> EPERRINTSET26_W {
EPERRINTSET26_W { w: self }
}
#[doc = "Bit 27 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset27(&mut self) -> EPERRINTSET27_W {
EPERRINTSET27_W { w: self }
}
#[doc = "Bit 28 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset28(&mut self) -> EPERRINTSET28_W {
EPERRINTSET28_W { w: self }
}
#[doc = "Bit 29 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset29(&mut self) -> EPERRINTSET29_W {
EPERRINTSET29_W { w: self }
}
#[doc = "Bit 30 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset30(&mut self) -> EPERRINTSET30_W {
EPERRINTSET30_W { w: self }
}
#[doc = "Bit 31 - Set endpoint xx (2 <= xx <= 31) System Error Interrupt request. 0 = No effect. 1 = Set the EPxx System Error Interrupt request in the USBSysErrIntSt register."]
#[inline(always)]
pub fn eperrintset31(&mut self) -> EPERRINTSET31_W {
EPERRINTSET31_W { w: self }
}
}
| {
self.bit(false)
} |
models.py | from datetime import datetime as dt
from django.contrib.auth import get_user_model
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
User = get_user_model()
"""
MAX_YEARS_TITLES: this value indicates which year can be the maximum for the
publication date of the work (+ 10 years for current year).
Relevant for upcoming movies, books, etc.
"""
MAX_YEARS_TITLES = dt.now().year + 10
class Categorie(models.Model):
"""Model for categories titles: films, books, etc."""
name = models.CharField(
_("category name"),
max_length=128,
unique=True,
help_text=_("Please enter category name (it's required)."),
)
slug = models.SlugField(
_("category slug"),
blank=True,
max_length=128,
unique=True,
)
def __str__(self):
return self.name
class Meta:
ordering = ("name",)
verbose_name = "Categorie"
verbose_name_plural = "Categories"
class | (models.Model):
"""Model for genre titles: comedy, fantasy, etc."""
name = models.CharField(
_("genre name"),
max_length=100,
unique=True,
help_text=_("Please enter genre name (it's required)."),
)
slug = models.SlugField(
_("genre slug"),
blank=True,
max_length=100,
unique=True,
)
def __str__(self):
return self.name
class Meta:
ordering = ("name",)
verbose_name = "Genre"
verbose_name_plural = "Genres"
class Title(models.Model):
"""Model for titles."""
name = models.CharField(
_("title name"),
max_length=128,
db_index=True,
help_text=_("Please enter title name (it's required)."),
)
year = models.PositiveSmallIntegerField(
_("title year"),
null=True,
blank=True,
db_index=True,
validators=(
MaxValueValidator(
MAX_YEARS_TITLES,
(
"Expected title year must not be later than "
"10 years from the current year."
),
),
),
)
description = models.TextField(
_("title description"),
null=True,
blank=True,
)
genre = models.ManyToManyField(
Genre,
blank=True,
db_index=True,
related_name="titles",
verbose_name=_("title genre"),
)
category = models.ForeignKey(
Categorie,
on_delete=models.SET_NULL,
blank=True,
null=True,
db_index=True,
related_name="titles",
verbose_name=_("title category"),
)
def __str__(self):
return self.name
class Meta:
ordering = ("name",)
verbose_name = "Title"
verbose_name_plural = "Titles"
class Review(models.Model):
"""Model for reviews, where users
can score the title and write their opinion."""
title = models.ForeignKey(
Title,
on_delete=models.CASCADE,
related_name="reviews",
verbose_name=_("review title"),
)
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="reviews",
verbose_name=_("review author"),
)
text = models.TextField(
_("text"),
help_text=_("Please enter review text (it's required)."),
)
score = models.PositiveSmallIntegerField(
_("review score"),
null=True,
validators=(
MinValueValidator(1, "Please, rate the title from 1 to 10."),
MaxValueValidator(10, "Please, rate the title from 1 to 10."),
),
)
pub_date = models.DateTimeField(
_("publication date"),
auto_now_add=True,
db_index=True,
)
def __str__(self):
return self.text
class Meta:
ordering = ("-pub_date",)
verbose_name = "Review"
verbose_name_plural = "Reviews"
class Comment(models.Model):
"""Model for comments for review
where users can discuss the review."""
author = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name="comments",
verbose_name=_("comment author"),
)
review = models.ForeignKey(
Review,
on_delete=models.CASCADE,
related_name="comments",
verbose_name=_("comment review"),
)
text = models.TextField(
_("text"),
help_text=_("Please enter comment text (it's required)."),
)
pub_date = models.DateTimeField(
_("publication date"),
auto_now_add=True,
db_index=True,
)
def __str__(self):
return self.text
class Meta:
ordering = ("-pub_date",)
verbose_name = "Comment"
verbose_name_plural = "Comments"
| Genre |
label_traincatset.py | # -*- coding: utf-8 -*-
"""label_TrainCatSet.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1vDyBZ7Ql-8qQ3l7EWJB9TfnwGy66qGGn
"""
import pandas as pd
import os
import numpy as np
# Enlisto los nombres de las imagenes
imagenes = os.listdir('/content/drive/MyDrive/Colab Data/Proyecto buscomiperro/gatos')
imagenes[:5]
def | (id): # Para que el resultado sea como el de razas le quito la extensión
return os.path.splitext(id)[0]
labels = list(map(extract_ext, imagenes))
df = pd.DataFrame()
df['id'] = labels
df['breed'] = 'gato'
df.to_csv('cat_labels.csv')
| extract_ext |
main.go | package main
import (
"net"
"sync/atomic"
"os"
"os/signal"
"github.com/sirupsen/logrus"
"gopkg.in/workanator/vuego.v1/browser"
"gopkg.in/workanator/vuego.v1/server"
"gopkg.in/workanator/vuego.v1/test_todo"
)
func main() {
// Configure the logger
logrus.SetLevel(logrus.DebugLevel)
// Track lifetime of the parts of the application.
var (
partsRunning int32
serverErrorChan = make(chan error)
browserErrorChan = make(chan error)
)
defer close(browserErrorChan)
defer close(serverErrorChan)
// Start the server
var serv atomic.Value
atomic.AddInt32(&partsRunning, 1)
go func() {
defer atomic.AddInt32(&partsRunning, -1)
srv := &server.Server{
ListenIP: net.ParseIP("127.0.0.1"),
ListenPort: 8008,
}
serv.Store(srv)
err := srv.Start(test_todo.Bundle())
// Send the error.
serverErrorChan <- err
}()
// Start the browser
atomic.AddInt32(&partsRunning, 1)
go func() {
defer atomic.AddInt32(&partsRunning, -1)
err := browser.Lauch(
"http://127.0.0.1:8008/app",
&browser.Options{
NewInstance: false,
Window: browser.WindowOptions{
Width: 800,
},
},
browser.Firefox(),
)
// Send the error.
browserErrorChan <- err
}()
// React on OS signals.
sigint := make(chan os.Signal, 1)
signal.Notify(sigint, os.Interrupt)
// Wait until one part is finished.
interrupt := false
for !interrupt {
select {
case err := <-browserErrorChan: | } else {
logrus.Info("Browser finished")
}
case err := <-serverErrorChan:
if err != nil {
logrus.WithError(err).Error("Server error")
} else {
logrus.Info("Server finished")
}
case signal := <-sigint:
logrus.WithField("signal", signal).Info("Caught signal")
interrupt = true
if srv, ok := serv.Load().(*server.Server); ok && srv != nil {
srv.Stop()
}
}
// Check if all parts finished
if atomic.LoadInt32(&partsRunning) == 0 {
interrupt = true
}
}
} | if err != nil {
logrus.WithError(err).Error("Browser error") |
opacity.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
| var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdOpacity = function MdOpacity(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm10 23.4h20c0-3.4-1.1-5.4-3-7.3l-7-7.3-7 7.2c-1.9 1.9-3 4-3 7.4z m19.5-10c2.5 2.5 3.9 6 3.9 9.3s-1.4 6.9-3.9 9.5-6.1 3.9-9.5 3.9-6.9-1.3-9.5-3.9-3.9-6.1-3.9-9.5 1.4-6.8 3.9-9.3l9.5-9.5z' })
)
);
};
exports.default = MdOpacity;
module.exports = exports['default']; | |
test_solvers.py | from sympy.core.function import expand_mul
from sympy.core.numbers import (I, Rational)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.simplify.simplify import simplify
from sympy.matrices.matrices import (ShapeError, NonSquareMatrixError)
from sympy.matrices import (
ImmutableMatrix, Matrix, eye, ones, ImmutableDenseMatrix, dotprodsimp)
from sympy.testing.pytest import raises
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.solvers.solveset import linsolve
from sympy.abc import x, y
def test_issue_17247_expression_blowup_29():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.gauss_jordan_solve(ones(4, 1)) == (Matrix(S('''[
[ -32549314808672/3306971225785 - 17397006745216*I/3306971225785],
[ 67439348256/3306971225785 - 9167503335872*I/3306971225785],
[-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905],
[ -11328/952745 + 87616*I/952745]]''')), Matrix(0, 1, []))
def test_issue_17247_expression_blowup_30():
|
# @XFAIL # This calculation hangs with dotprodsimp.
# def test_issue_17247_expression_blowup_31():
# M = Matrix([
# [x + 1, 1 - x, 0, 0],
# [1 - x, x + 1, 0, x + 1],
# [ 0, 1 - x, x + 1, 0],
# [ 0, 0, 0, x + 1]])
# with dotprodsimp(True):
# assert M.LDLsolve(ones(4, 1)) == Matrix([
# [(x + 1)/(4*x)],
# [(x - 1)/(4*x)],
# [(x + 1)/(4*x)],
# [ 1/(x + 1)]])
def test_issue_17247_expression_blowup_32():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
with dotprodsimp(True):
assert M.LUsolve(ones(4, 1)) == Matrix([
[(x + 1)/(4*x)],
[(x - 1)/(4*x)],
[(x + 1)/(4*x)],
[ 1/(x + 1)]])
def test_LUsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[2, 1], [1, 0], [1, 0]]) # issue 14548
b = Matrix([3, 1, 1])
assert A.LUsolve(b) == Matrix([1, 1])
b = Matrix([3, 1, 2]) # inconsistent
raises(ValueError, lambda: A.LUsolve(b))
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4],
[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix([2, 1, -4])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[0, -1, 2], [5, 10, 7]]) # underdetermined
x = Matrix([-1, 2, 0])
b = A*x
raises(NotImplementedError, lambda: A.LUsolve(b))
A = Matrix(4, 4, lambda i, j: 1/(i+j+1) if i != 3 else 0)
b = Matrix.zeros(4, 1)
raises(NonInvertibleMatrixError, lambda: A.LUsolve(b))
def test_QRsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.QRsolve(b)
assert soln == x
x = Matrix([[1, 2], [3, 4], [5, 6]])
b = A*x
soln = A.QRsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.QRsolve(b)
assert soln == x
x = Matrix([[7, 8], [9, 10], [11, 12]])
b = A*x
soln = A.QRsolve(b)
assert soln == x
def test_errors():
raises(ShapeError, lambda: Matrix([1]).LUsolve(Matrix([[1, 2], [3, 4]])))
def test_cholesky_solve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix(((1, 5), (5, 1)))
x = Matrix((4, -3))
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix(((9, 3*I), (-3*I, 5)))
x = Matrix((-2, 1))
b = A*x
soln = A.cholesky_solve(b)
assert expand_mul(soln) == x
A = Matrix(((9*I, 3), (-3 + I, 5)))
x = Matrix((2 + 3*I, -1))
b = A*x
soln = A.cholesky_solve(b)
assert expand_mul(soln) == x
a00, a01, a11, b0, b1 = symbols('a00, a01, a11, b0, b1')
A = Matrix(((a00, a01), (a01, a11)))
b = Matrix((b0, b1))
x = A.cholesky_solve(b)
assert simplify(A*x) == b
def test_LDLsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.LDLsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.LDLsolve(b)
assert soln == x
A = Matrix(((9, 3*I), (-3*I, 5)))
x = Matrix((-2, 1))
b = A*x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix(((9*I, 3), (-3 + I, 5)))
x = Matrix((2 + 3*I, -1))
b = A*x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix(((9, 3), (3, 9)))
x = Matrix((1, 1))
b = A * x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix([[-5, -3, -4], [-3, -7, 7]])
x = Matrix([[8], [7], [-2]])
b = A * x
raises(NotImplementedError, lambda: A.LDLsolve(b))
def test_lower_triangular_solve():
raises(NonSquareMatrixError,
lambda: Matrix([1, 0]).lower_triangular_solve(Matrix([0, 1])))
raises(ShapeError,
lambda: Matrix([[1, 0], [0, 1]]).lower_triangular_solve(Matrix([1])))
raises(ValueError,
lambda: Matrix([[2, 1], [1, 2]]).lower_triangular_solve(
Matrix([[1, 0], [0, 1]])))
A = Matrix([[1, 0], [0, 1]])
B = Matrix([[x, y], [y, x]])
C = Matrix([[4, 8], [2, 9]])
assert A.lower_triangular_solve(B) == B
assert A.lower_triangular_solve(C) == C
def test_upper_triangular_solve():
raises(NonSquareMatrixError,
lambda: Matrix([1, 0]).upper_triangular_solve(Matrix([0, 1])))
raises(ShapeError,
lambda: Matrix([[1, 0], [0, 1]]).upper_triangular_solve(Matrix([1])))
raises(TypeError,
lambda: Matrix([[2, 1], [1, 2]]).upper_triangular_solve(
Matrix([[1, 0], [0, 1]])))
A = Matrix([[1, 0], [0, 1]])
B = Matrix([[x, y], [y, x]])
C = Matrix([[2, 4], [3, 8]])
assert A.upper_triangular_solve(B) == B
assert A.upper_triangular_solve(C) == C
def test_diagonal_solve():
raises(TypeError, lambda: Matrix([1, 1]).diagonal_solve(Matrix([1])))
A = Matrix([[1, 0], [0, 1]])*2
B = Matrix([[x, y], [y, x]])
assert A.diagonal_solve(B) == B/2
A = Matrix([[1, 0], [1, 2]])
raises(TypeError, lambda: A.diagonal_solve(B))
def test_pinv_solve():
# Fully determined system (unique result, identical to other solvers).
A = Matrix([[1, 5], [7, 9]])
B = Matrix([12, 13])
assert A.pinv_solve(B) == A.cholesky_solve(B)
assert A.pinv_solve(B) == A.LDLsolve(B)
assert A.pinv_solve(B) == Matrix([sympify('-43/26'), sympify('71/26')])
assert A * A.pinv() * B == B
# Fully determined, with two-dimensional B matrix.
B = Matrix([[12, 13, 14], [15, 16, 17]])
assert A.pinv_solve(B) == A.cholesky_solve(B)
assert A.pinv_solve(B) == A.LDLsolve(B)
assert A.pinv_solve(B) == Matrix([[-33, -37, -41], [69, 75, 81]]) / 26
assert A * A.pinv() * B == B
# Underdetermined system (infinite results).
A = Matrix([[1, 0, 1], [0, 1, 1]])
B = Matrix([5, 7])
solution = A.pinv_solve(B)
w = {}
for s in solution.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert solution == Matrix([[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 1],
[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 3],
[-w['w0_0']/3 - w['w1_0']/3 + w['w2_0']/3 + 4]])
assert A * A.pinv() * B == B
# Overdetermined system (least squares results).
A = Matrix([[1, 0], [0, 0], [0, 1]])
B = Matrix([3, 2, 1])
assert A.pinv_solve(B) == Matrix([3, 1])
# Proof the solution is not exact.
assert A * A.pinv() * B != B
def test_pinv_rank_deficient():
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[1, 1, 1], [2, 2, 2]]),
Matrix([[1, 0], [0, 0]]),
Matrix([[1, 2], [2, 4], [3, 6]])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# Test solving with rank-deficient matrices.
A = Matrix([[1, 0], [0, 0]])
# Exact, non-unique solution.
B = Matrix([3, 0])
solution = A.pinv_solve(B)
w1 = solution.atoms(Symbol).pop()
assert w1.name == 'w1_0'
assert solution == Matrix([3, w1])
assert A * A.pinv() * B == B
# Least squares, non-unique solution.
B = Matrix([3, 1])
solution = A.pinv_solve(B)
w1 = solution.atoms(Symbol).pop()
assert w1.name == 'w1_0'
assert solution == Matrix([3, w1])
assert A * A.pinv() * B != B
def test_gauss_jordan_solve():
# Square, full rank, unique solution
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
b = Matrix([3, 6, 9])
sol, params = A.gauss_jordan_solve(b)
assert sol == Matrix([[-1], [2], [0]])
assert params == Matrix(0, 1, [])
# Square, full rank, unique solution, B has more columns than rows
A = eye(3)
B = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
sol, params = A.gauss_jordan_solve(B)
assert sol == B
assert params == Matrix(0, 4, [])
# Square, reduced rank, parametrized solution
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = Matrix([3, 6, 9])
sol, params, freevar = A.gauss_jordan_solve(b, freevar=True)
w = {}
for s in sol.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert sol == Matrix([[w['tau0'] - 1], [-2*w['tau0'] + 2], [w['tau0']]])
assert params == Matrix([[w['tau0']]])
assert freevar == [2]
# Square, reduced rank, parametrized solution, B has two columns
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = Matrix([[3, 4], [6, 8], [9, 12]])
sol, params, freevar = A.gauss_jordan_solve(B, freevar=True)
w = {}
for s in sol.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert sol == Matrix([[w['tau0'] - 1, w['tau1'] - Rational(4, 3)],
[-2*w['tau0'] + 2, -2*w['tau1'] + Rational(8, 3)],
[w['tau0'], w['tau1']],])
assert params == Matrix([[w['tau0'], w['tau1']]])
assert freevar == [2]
# Square, reduced rank, parametrized solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[-2*w['tau0'] - 3*w['tau1']],
[w['tau0']], [w['tau1']]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
# Square, reduced rank, parametrized solution
A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
b = Matrix([0, 0, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]])
assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]])
# Square, reduced rank, no solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, tall, full rank, unique solution
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
b = Matrix([0, 0, 1, 0])
sol, params = A.gauss_jordan_solve(b)
assert sol == Matrix([[Rational(-1, 2)], [0], [Rational(1, 6)]])
assert params == Matrix(0, 1, [])
# Rectangular, tall, full rank, unique solution, B has less columns than rows
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [1, 2], [0, 0]])
sol, params = A.gauss_jordan_solve(B)
assert sol == Matrix([[Rational(-1, 2), Rational(-2, 2)], [0, 0], [Rational(1, 6), Rational(2, 6)]])
assert params == Matrix(0, 2, [])
# Rectangular, tall, full rank, no solution
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
b = Matrix([0, 0, 0, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, tall, full rank, no solution, B has two columns (2nd has no solution)
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [1, 0], [0, 1]])
raises(ValueError, lambda: A.gauss_jordan_solve(B))
# Rectangular, tall, full rank, no solution, B has two columns (1st has no solution)
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [0, 1], [1, 0]])
raises(ValueError, lambda: A.gauss_jordan_solve(B))
# Rectangular, tall, reduced rank, parametrized solution
A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]])
b = Matrix([0, 0, 0, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[-3*w['tau0'] + 5], [-1], [w['tau0']]])
assert params == Matrix([[w['tau0']]])
# Rectangular, tall, reduced rank, no solution
A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]])
b = Matrix([0, 0, 1, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, wide, full rank, parametrized solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 1, 12]])
b = Matrix([1, 1, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[2*w['tau0'] - 1], [-3*w['tau0'] + 1], [0],
[w['tau0']]])
assert params == Matrix([[w['tau0']]])
# Rectangular, wide, reduced rank, parametrized solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]])
b = Matrix([0, 1, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[w['tau0'] + 2*w['tau1'] + S.Half],
[-2*w['tau0'] - 3*w['tau1'] - Rational(1, 4)],
[w['tau0']], [w['tau1']]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
# watch out for clashing symbols
x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau1')
M = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]])
A = M[:, :-1]
b = M[:, -1:]
sol, params = A.gauss_jordan_solve(b)
assert params == Matrix(3, 1, [x0, x1, x2])
assert sol == Matrix(5, 1, [x0, 0, x1, _x0, x2])
# Rectangular, wide, reduced rank, no solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]])
b = Matrix([1, 1, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Test for immutable matrix
A = ImmutableMatrix([[1, 0], [0, 1]])
B = ImmutableMatrix([1, 2])
sol, params = A.gauss_jordan_solve(B)
assert sol == ImmutableMatrix([1, 2])
assert params == ImmutableMatrix(0, 1, [])
assert sol.__class__ == ImmutableDenseMatrix
assert params.__class__ == ImmutableDenseMatrix
# Test placement of free variables
A = Matrix([[1, 0, 0, 0], [0, 0, 0, 1]])
b = Matrix([1, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[1], [w['tau0']], [w['tau1']], [1]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
def test_linsolve_underdetermined_AND_gauss_jordan_solve():
#Test placement of free variables as per issue 19815
A = Matrix([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])
B = Matrix([1, 2, 1, 1, 1, 1, 1, 2])
sol, params = A.gauss_jordan_solve(B)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']],
[w['tau3']], [w['tau4']], [w['tau5']]])
assert sol == Matrix([[1 - 1*w['tau2']],
[w['tau2']],
[1 - 1*w['tau0'] + w['tau1']],
[w['tau0']],
[w['tau3'] + w['tau4']],
[-1*w['tau3'] - 1*w['tau4'] - 1*w['tau1']],
[1 - 1*w['tau2']],
[w['tau1']],
[w['tau2']],
[w['tau3']],
[w['tau4']],
[1 - 1*w['tau5']],
[w['tau5']],
[1]])
from sympy.abc import j,f
# https://github.com/sympy/sympy/issues/20046
A = Matrix([
[1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, -1, 0, -1, 0, -1, 0, -1, -j],
[0, 0, 0, 0, 1, 1, 1, 1, f]
])
sol_1=Matrix(list(linsolve(A))[0])
tau0, tau1, tau2, tau3, tau4 = symbols('tau:5')
assert sol_1 == Matrix([[-f - j - tau0 + tau2 + tau4 + 1],
[j - tau1 - tau2 - tau4],
[tau0],
[tau1],
[f - tau2 - tau3 - tau4],
[tau2],
[tau3],
[tau4]])
# https://github.com/sympy/sympy/issues/19815
sol_2 = A[:, : -1 ] * sol_1 - A[:, -1 ]
assert sol_2 == Matrix([[0], [0], [0]])
def test_solve():
A = Matrix([[1,2], [2,4]])
b = Matrix([[3], [4]])
raises(ValueError, lambda: A.solve(b)) #no solution
b = Matrix([[ 4], [8]])
raises(ValueError, lambda: A.solve(b)) #infinite solution
| M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.cholesky_solve(ones(4, 1)) == Matrix(S('''[
[ -32549314808672/3306971225785 - 17397006745216*I/3306971225785],
[ 67439348256/3306971225785 - 9167503335872*I/3306971225785],
[-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905],
[ -11328/952745 + 87616*I/952745]]''')) |
tisserand.py | """ Generates Tisserand plots """
from enum import Enum
import numpy as np
from astropy import units as u
from matplotlib import pyplot as plt
from poliastro.plotting._base import BODY_COLORS
from poliastro.twobody.mean_elements import get_mean_elements
from poliastro.util import norm
class TisserandKind(Enum):
"""All possible Tisserand kinds"""
APSIS = "apsis"
ENERGY = "energy"
PERIOD = "period"
class TisserandPlotter:
"""Generates Tisserand figures"""
def __init__(self, kind=TisserandKind.APSIS, axes=None):
"""Object initializer
Parameters
----------
kind: TisserandKind
Nature for the Tisserand
axes: ~matplotlib.pyplot.axes
Axes for the figure
"""
# Asign Tisserand kind
self.kind = kind
# Check if axis available
if not axes:
_, self.ax = plt.subplots(1, 1)
else:
self.ax = axes
# Force axes scale regarding Tisserand kind
self.ax.set_xscale("log")
if self.kind == TisserandKind.APSIS:
self.ax.set_yscale("log")
def _solve_tisserand(
self, body, vinf_span, num_contours, alpha_lim=(0, np.pi), N=100
):
"""Solves all possible Tisserand lines with a meshgrid workflow
Parameters
----------
body: ~poliastro.bodies.Body
Body to be plotted Tisserand
vinf_array: ~astropy.units.Quantity
Desired Vinf for the flyby
num_contours: int
Number of contour lines for flyby speed
N: int
Number of points for flyby angle
Note
----
The algorithm for generating Tisserand plots is the one depicted in
"Preliminary Trajectory Design of a Mission to Enceladus" by David
Falcato Fialho Palma, section 3.6
"""
# Generate mean orbital elements Earth
body_rv = get_mean_elements(body).to_vectors()
R_body, V_body = norm(body_rv.r), norm(body_rv.v)
# Generate non-dimensional velocity and alpha span
vinf_array = np.linspace(vinf_span[0], vinf_span[-1], num_contours)
alpha_array = np.linspace(alpha_lim[0], alpha_lim[-1], N)
vinf_array /= V_body
# Construct the mesh for any configuration
V_INF, ALPHA = np.meshgrid(vinf_array, alpha_array)
# Solving for non-dimensional a_sc and ecc_sc
A_SC = 1 / np.abs(1 - V_INF ** 2 - 2 * V_INF * np.cos(ALPHA))
ECC_SC = np.sqrt(1 - 1 / A_SC * ((3 - 1 / A_SC - V_INF ** 2) / (2)) ** 2)
# Compute main Tisserand variables
RR_P = A_SC * R_body * (1 - ECC_SC)
RR_A = A_SC * R_body * (1 + ECC_SC)
TT = 2 * np.pi * np.sqrt((A_SC * R_body) ** 3 / body.parent.k)
EE = -body.parent.k / (2 * A_SC * R_body)
# Build color lines to internal canvas
return RR_P, RR_A, EE, TT
def | (self, RR_P, RR_A, EE, TT, color):
"""Collect lines and append them to internal data
Parameters
----------
data: list
Array containing [RR_P, RR_A, EE, TT, color]
Returns
-------
lines: list
Plotting lines for the Tisserand
"""
# Plot desired kind lines
if self.kind == TisserandKind.APSIS:
# Generate apsis lines
lines = self.ax.plot(RR_A.to(u.AU), RR_P.to(u.AU), color=color)
elif self.kind == TisserandKind.ENERGY:
# Generate energy lines
lines = self.ax.plot(
RR_P.to(u.AU), EE.to(u.au ** 2 / u.s ** 2), color=color
)
elif self.kind == TisserandKind.PERIOD:
# Generate period lines
lines = self.ax.plot(RR_P.to(u.AU), TT.to(u.year), color=color)
return lines
def plot_line(self, body, vinf, alpha_lim=(0, np.pi), color=None):
"""Plots body Tisserand line within flyby angle
Parameters
----------
body: ~poliastro.bodies.Body
Body to be plotted Tisserand
vinf: ~astropy.units.Quantity
Vinf velocity line
alpha_lim: tuple
Minimum and maximum flyby angles
color: str
String representing for the color lines
Returns
-------
self.ax: ~matplotlib.axes.Axes
Apsis tisserand is the default plotting option
"""
# HACK: to reuse Tisserand solver, we transform input Vinf into a tuple
vinf_span = (vinf, vinf)
# Solve Tisserand parameters
RR_P, RR_A, EE, TT = self._solve_tisserand(
body, vinf_span, num_contours=2, alpha_lim=alpha_lim
)
# Check if color defined
if not color:
color = BODY_COLORS[body.name]
# Build canvas lines from Tisserand parameters
self._build_lines(RR_P, RR_A, EE, TT, color)
return self.ax
def plot(self, body, vinf_span, num_contours=10, color=None):
"""Plots body Tisserand for given amount of solutions within Vinf span
Parameters
----------
body: ~poliastro.bodies.Body
Body to be plotted Tisserand
vinf_span: tuple
Minimum and maximum Vinf velocities
num_contours: int
Number of points to iterate over previously defined velocities
color: str
String representing for the color lines
Returns
-------
self.ax: ~matplotlib.axes.Axes
Apsis tisserand is the default plotting option
"""
# Solve Tisserand parameters
RR_P, RR_A, EE, TT = self._solve_tisserand(body, vinf_span, num_contours)
# Check if color defined
if not color:
color = BODY_COLORS[body.name]
# Build canvas lines from Tisserand parameters
self._build_lines(RR_P, RR_A, EE, TT, color)
return self.ax
| _build_lines |
creds_utils.go | /*
* Copyright 2019-2020 The NATS 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.
*/
package jwt
import (
"bytes"
"errors"
"fmt"
"regexp"
"strings"
"github.com/nats-io/nkeys"
)
// DecorateJWT returns a decorated JWT that describes the kind of JWT
func DecorateJWT(jwtString string) ([]byte, error) {
gc, err := DecodeGeneric(jwtString)
if err != nil {
return nil, err
}
return formatJwt(string(gc.Type), jwtString)
}
func | (kind string, jwtString string) ([]byte, error) {
templ := `-----BEGIN NATS %s JWT-----
%s
------END NATS %s JWT------
`
w := bytes.NewBuffer(nil)
kind = strings.ToUpper(kind)
_, err := fmt.Fprintf(w, templ, kind, jwtString, kind)
if err != nil {
return nil, err
}
return w.Bytes(), nil
}
// DecorateSeed takes a seed and returns a string that wraps
// the seed in the form:
// ************************* IMPORTANT *************************
// NKEY Seed printed below can be used sign and prove identity.
// NKEYs are sensitive and should be treated as secrets.
//
// -----BEGIN USER NKEY SEED-----
// SUAIO3FHUX5PNV2LQIIP7TZ3N4L7TX3W53MQGEIVYFIGA635OZCKEYHFLM
// ------END USER NKEY SEED------
func DecorateSeed(seed []byte) ([]byte, error) {
w := bytes.NewBuffer(nil)
ts := bytes.TrimSpace(seed)
pre := string(ts[0:2])
kind := ""
switch pre {
case "SU":
kind = "USER"
case "SA":
kind = "ACCOUNT"
case "SO":
kind = "OPERATOR"
default:
return nil, errors.New("seed is not an operator, account or user seed")
}
header := `************************* IMPORTANT *************************
NKEY Seed printed below can be used to sign and prove identity.
NKEYs are sensitive and should be treated as secrets.
-----BEGIN %s NKEY SEED-----
`
_, err := fmt.Fprintf(w, header, kind)
if err != nil {
return nil, err
}
w.Write(ts)
footer := `
------END %s NKEY SEED------
*************************************************************
`
_, err = fmt.Fprintf(w, footer, kind)
if err != nil {
return nil, err
}
return w.Bytes(), nil
}
var userConfigRE = regexp.MustCompile(`\s*(?:(?:[-]{3,}[^\n]*[-]{3,}\n)(.+)(?:\n\s*[-]{3,}[^\n]*[-]{3,}\n))`)
// An user config file looks like this:
// -----BEGIN NATS USER JWT-----
// eyJ0eXAiOiJqd3QiLCJhbGciOiJlZDI1NTE5...
// ------END NATS USER JWT------
//
// ************************* IMPORTANT *************************
// NKEY Seed printed below can be used sign and prove identity.
// NKEYs are sensitive and should be treated as secrets.
//
// -----BEGIN USER NKEY SEED-----
// SUAIO3FHUX5PNV2LQIIP7TZ3N4L7TX3W53MQGEIVYFIGA635OZCKEYHFLM
// ------END USER NKEY SEED------
// FormatUserConfig returns a decorated file with a decorated JWT and decorated seed
func FormatUserConfig(jwtString string, seed []byte) ([]byte, error) {
gc, err := DecodeGeneric(jwtString)
if err != nil {
return nil, err
}
if gc.Type != UserClaim {
return nil, fmt.Errorf("%q cannot be serialized as a user config", string(gc.Type))
}
w := bytes.NewBuffer(nil)
jd, err := formatJwt(string(gc.Type), jwtString)
if err != nil {
return nil, err
}
_, err = w.Write(jd)
if err != nil {
return nil, err
}
if !bytes.HasPrefix(bytes.TrimSpace(seed), []byte("SU")) {
return nil, fmt.Errorf("nkey seed is not an user seed")
}
d, err := DecorateSeed(seed)
if err != nil {
return nil, err
}
_, err = w.Write(d)
if err != nil {
return nil, err
}
return w.Bytes(), nil
}
// ParseDecoratedJWT takes a creds file and returns the JWT portion.
func ParseDecoratedJWT(contents []byte) (string, error) {
items := userConfigRE.FindAllSubmatch(contents, -1)
if len(items) == 0 {
return string(contents), nil
}
// First result should be the user JWT.
// We copy here so that if the file contained a seed file too we wipe appropriately.
raw := items[0][1]
tmp := make([]byte, len(raw))
copy(tmp, raw)
return string(tmp), nil
}
// ParseDecoratedNKey takes a creds file, finds the NKey portion and creates a
// key pair from it.
func ParseDecoratedNKey(contents []byte) (nkeys.KeyPair, error) {
var seed []byte
items := userConfigRE.FindAllSubmatch(contents, -1)
if len(items) > 1 {
seed = items[1][1]
} else {
lines := bytes.Split(contents, []byte("\n"))
for _, line := range lines {
if bytes.HasPrefix(bytes.TrimSpace(line), []byte("SO")) ||
bytes.HasPrefix(bytes.TrimSpace(line), []byte("SA")) ||
bytes.HasPrefix(bytes.TrimSpace(line), []byte("SU")) {
seed = line
break
}
}
}
if seed == nil {
return nil, errors.New("no nkey seed found")
}
if !bytes.HasPrefix(seed, []byte("SO")) &&
!bytes.HasPrefix(seed, []byte("SA")) &&
!bytes.HasPrefix(seed, []byte("SU")) {
return nil, errors.New("doesn't contain a seed nkey")
}
kp, err := nkeys.FromSeed(seed)
if err != nil {
return nil, err
}
return kp, nil
}
// ParseDecoratedUserNKey takes a creds file, finds the NKey portion and creates a
// key pair from it. Similar to ParseDecoratedNKey but fails for non-user keys.
func ParseDecoratedUserNKey(contents []byte) (nkeys.KeyPair, error) {
nk, err := ParseDecoratedNKey(contents)
if err != nil {
return nil, err
}
seed, err := nk.Seed()
if err != nil {
return nil, err
}
if !bytes.HasPrefix(seed, []byte("SU")) {
return nil, errors.New("doesn't contain an user seed nkey")
}
kp, err := nkeys.FromSeed(seed)
if err != nil {
return nil, err
}
return kp, nil
}
| formatJwt |
benchtools.js | const my = module.exports
my.benchSet = (runs, warmUps, verify, ...benchmarks) => {
const times = {}
let runsLeft = runs + warmUps
console.log(`
Runs: ${runs} runs (+ ${warmUps} warm-up runs)
Variations: ${benchmarks.length}
`)
while (runsLeft--) {
benchmarks.forEach(bench => {
const { label, time } = bench(verify) | return
}
if (!times[label]) {
times[label] = []
}
times[label].push(time)
})
}
const results = Object.entries(times).reduce(
(results, [entry, entryTimes]) => {
const avg = entryTimes.reduce((a, b) => a + b) / entryTimes.length
results.push({ label: entry, time: avg })
return results
},
[]
)
results.sort((a, b) => {
return a.time - b.time
})
const baseTime = results[0]
console.log(`${baseTime.label}: ${baseTime.time.toFixed(2)}ms (fastest)`)
results.slice(1).forEach(({ label, time }) => {
const timeDiff = time - baseTime.time
const timesSlower = time / baseTime.time
console.log(`${label}: ${time.toFixed(2)}ms (+${timeDiff.toFixed(2)}ms / ${timesSlower.toFixed(1)}x slower)`)
})
}
my.bench = (label, fn) => {
return verify => {
const start = Date.now()
const ret = Array.from(fn())
const end = Date.now()
verify(ret)
return { label, time: end - start }
}
} |
if (--warmUps > 0) { |
bcservice.js | /*
Copyright ONECHAIN 2017 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.
*/
var helper=require('../app/helper.js')
var path=require('path')
var hfc = require('fabric-client');
hfc.addConfigFile(path.join(__dirname, '/app/network-config.json'));
var ORGS = hfc.getConfigSetting('network-config');
var config = require('../config.json');
var query=require('../app/query.js')
var logger = helper.getLogger('bcservice');
// var bcserver = require('./bcservice');
/**
* 获取所有的组织
*/
function getAllOrgs(){
var OrgArray=[]
for (let key in ORGS) {
if (key.indexOf('org') === 0) {
let orgName = ORGS[key].name;
OrgArray.push(orgName)
}
}
return OrgArray
}
/**
* 获取所有的peers的请求地址
*
* @returns {Array}
*/
function getAllPeerRequest() {
var peerArray = []
for (let key in ORGS) {
if (key.indexOf('org') === 0) {
let orgproperty = ORGS[key]
for ( let orgkey in orgproperty){
if( orgkey.indexOf('peer') === 0 ){
var peerbean = {'name':orgkey,'org':key}
peerArray.push(peerbean)
}
}
}
}
return peerArray;
}
/**
* 获取所有的账本
*/
function getAllChannels(){
}
/**
* 获取所有的节点
*/
function getallPeers () {
var peerArray=[]
for (let key in ORGS) {
if (key.indexOf('org') === 0) {
let peerName = ORGS[key].peer1.requests;
peerArray.push(peerName)
}
}
return peerArray
}
/**
* 获取所有的账本
*/
function getAllChannels(){
return config.channelsList
}
/**
* 根据账本名称获取账本中的区块
* @param channelname
*/
function getChainInfo( channelname ){
return query.getChainInfo('peer1',channelname,'admin','org1')
}
/**
* 根据区块编号获取区块详细信息
* @param chainid
*/
function getBlock4Channel( channelName,blockNum ){
return query.getBlockByNumber('peer1',blockNum ,'admin','org1')
}
/**
* 获取channel中的交易
* @param chainid
*/
function getTans4Chain( channelName,trxnID ) {
return query.getTransactionByID('peer1',channelName, trxnID, 'admin', 'org1')
}
/**
* 获取账本中的chaincode
*/
function getChainCode4Channel(channelName) {
return query.getInstalledChaincodes('peer1',channelName, '', 'admin', 'org1')
}
function getBlockRange(from,to){
var parms = [];
for(var ind = from ; ind < to ; ind++){
parms.push(query.getBlockByNumber('peer1','mychannel',ind,' | ));
}
return Promise.all(parms).then(datas=>{
var block_array=[]
datas.forEach((k,v) =>{
var block_obj={}
var num = k.header.number.toString();
block_obj.num=num
var previous_hash=k.header.previous_hash
block_obj.previous_hash=previous_hash
var data_hash=k.header.data_hash
block_obj.data_hash=data_hash
block_obj.tx=[]
k.data.data.forEach(t=>{
block_obj.tx.push(t.payload.header.channel_header.tx_id)
})
block_array.push(block_obj)
})
return Promise.resolve(block_array)
}).catch(err=>{
logger.error(err)
})
}
function getTx(channelName,tx_array){
let params=[]
tx_array.forEach(tx=>{
params.push(getTans4Chain(channelName,tx))
})
return Promise.all(params).then(datas=>{
return Promise.resolve(datas)
}).catch(err=>{
logger.error(err)
})
}
module.exports.getAllOrgs=getAllOrgs
module.exports.getAllPeerRequest = getAllPeerRequest
module.exports.getAllChannels=getAllChannels
module.exports.getallPeers=getallPeers
module.exports.getTans4Chain=getTans4Chain
module.exports.getChainCode4Channel=getChainCode4Channel
module.exports.getChainInfo=getChainInfo
module.exports.getBlock4Channel=getBlock4Channel
module.exports.getBlockRange=getBlockRange
module.exports.getTx=getTx
| admin','org1' |
video_detect.py | import argparse
import math
import os
import shutil
import time
import numpy as np
from pathlib import Path
from ensemble_boxes import *
import copy
import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
import matplotlib.pyplot as plt
from itertools import combinations
import random
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general import (
check_img_size, non_max_suppression, apply_classifier, scale_coords,
xyxy2xywh, xywh2xyxy, plot_one_box, strip_optimizer, set_logging)
from utils.torch_utils import select_device, load_classifier, time_synchronized
from mmdet.apis import init_detector, inference_detector
fcap = cv2.VideoCapture('/root/Swin-Transformer-Object-Detection/demo/VID_20210909_164000.mp4')
data_root = '/root/Swin-Transformer-Object-Detection/'
config_file = data_root + 'configs/swin.py'
checkpoint_file = data_root + '2021_7_28/epoch_50.pth'
# build the model from a config file and a checkpoint file
swin_model = init_detector(config_file, checkpoint_file, device='cuda:0')
framerate = 10
def get_image(fcap, framerate):
|
def filterbox_iou(rec1, rec2):
"""
computing IoU
:param rec1: (y0, x0, y1, x1), which reflects
(top, left, bottom, right)
:param rec2: (y0, x0, y1, x1)
:return: scala value of IoU
"""
# computing area of each rectangles
S_rec1 = (rec1[2] - rec1[0]) * (rec1[3] - rec1[1])
S_rec2 = (rec2[2] - rec2[0]) * (rec2[3] - rec2[1])
# computing the sum_area
sum_area = S_rec1 + S_rec2
# find the each edge of intersect rectangle
left_line = max(rec1[1], rec2[1])
right_line = min(rec1[3], rec2[3])
top_line = max(rec1[0], rec2[0])
bottom_line = min(rec1[2], rec2[2])
# judge if there is an intersect
if left_line >= right_line or top_line >= bottom_line:
return 0
else:
intersect = (right_line - left_line) * (bottom_line - top_line)
return (intersect / (sum_area - intersect)) * 1.0
def detect(save_img=False):
out, source, weights, view_img, save_txt, imgsz = \
opt.save_dir, opt.source, opt.weights, opt.view_img, opt.save_txt, opt.img_size
webcam = source.isnumeric() or source.startswith(('rtsp://', 'rtmp://', 'http://')) or source.endswith('.txt')
# Initialize
set_logging()
device = select_device(opt.device)
if os.path.exists(out): # output dir
shutil.rmtree(out) # delete dir
os.makedirs(out) # make new dir
half = device.type != 'cpu' # half precision only supported on CUDA
# Load model
model = attempt_load(weights, map_location=device) # load FP32 model
imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size
if half:
model.half() # to FP16
# Second-stage classifier
classify = False
if classify:
modelc = load_classifier(name='resnet101', n=2) # initialize
modelc.load_state_dict(torch.load('weights/resnet101.pt', map_location=device)['model']) # load weights
modelc.to(device).eval()
# Set Dataloader
vid_path, vid_writer = None, None
if webcam:
view_img = True
cudnn.benchmark = True # set True to speed up constant image size inference
dataset = LoadStreams(source, img_size=imgsz)
else:
save_img = True
dataset = LoadImages(source, img_size=imgsz)
# Get names and colors
names = model.module.names if hasattr(model, 'module') else model.names
colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(len(names))]
# Run inference
t0 = time.time()
img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img
_ = model(img.half() if half else img) if device.type != 'cpu' else None # run once
f_detect = 0
counting_img = 0
full_detect = 0
full_truth = 0
img_dict = {}
frame_key = 0
dict2 = {}
for path, img, im0s, vid_cap in dataset:
img_before = img
img = torch.from_numpy(img).to(device)
# img_before = img
img = img.half() if half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
# Inference
t1 = time_synchronized()
pred = model(img, augment=opt.augment)[0]
# Apply NMS
nms_pred = non_max_suppression(pred, opt.conf_thres, opt.iou_thres, classes=1,
agnostic=opt.agnostic_nms)
# nms_pred = cross_class_nms(nms_pred, opt.conf_thres, 0.9, agnostic=opt.agnostic_nms)
t2 = time_synchronized()
# Process detections
for i, det in enumerate(nms_pred): # detections per image
print(det)
dict1 = {'total': 0}
if webcam: # batch_size >= 1
p, s, im0 = path[i], '%g: ' % i, im0s[i].copy()
else:
p, s, im0 = path, '', im0s
save_path = str(Path(out) / Path(p).name)
txt_path = str(Path(out) / Path(p).stem) + ('_%g' % dataset.frame if dataset.mode == 'video' else '')
s += '%gx%g ' % img.shape[2:] # print string
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
swin_img = cv2.imread(p)
result = inference_detector(swin_model, swin_img)
swin_bbox_list, swin_score_list, swin_label_list = swin_model.show_result(swin_img, result,
out_file=save_path)
yolo_bbox_list = det[:, 0:4].cpu().detach().numpy().tolist()
yolo_score_list = det[:, 4].cpu().detach().numpy().tolist()
yolo_label_list = det[:, 5].cpu().detach().numpy().tolist()
swin_list = ['txd', 'jgc', 'xbs', 'wbs', 'c-pg', 'lwz', 'tc', 'a-pg', 'b-pg', 'g-pg', 'z-pg', 'bbt', 'lxb',
'xgg', 'lsd', 'wt']
yolo_list = ['wt', 'jgc', 'lsd', 'lxb', 'bbt', 'xgg', 'txd', 'lwz', 'tc', 'xbs', 'wbs', 'a-pg', 'b-pg',
'c-pg', 'g-pg', 'z-pg']
swin_trueLabel_list = []
for i in swin_label_list:
swin_trueLabel_list.append(yolo_list.index(swin_list[i]))
# NMS for different class, high thresh
# nms_bbox, nms_score, nms_label = yolo_bbox_list, yolo_score_list, yolo_label_list
# nms_bbox, nms_score, nms_label = torch.from_numpy(np.array(nms_bbox)).reshape(-1, 4), torch.from_numpy(
# np.array(nms_score)).reshape(-1, 1), torch.from_numpy(np.array(nms_label)).reshape(-1, 1)
# two_det = torch.cat((torch.cat((nms_bbox, nms_score), 1), nms_label), 1)
# normalize
# 需要将框进行归一化操作
# for i, single in enumerate(swin_bbox_list):
# swin_bbox_list[i] = [single[0] / 640, single[1] / 480, single[2] / 640, single[3] / 480]
#
# for i, single in enumerate(yolo_bbox_list):
# yolo_bbox_list[i] = [single[0] / 640, single[1] / 480, single[2] / 640, single[3] / 480]
swin_object = [0, 1, 2, 3, 6, 7, 8, 9, 10] # from yolo_list:wt lsd lwz tc xbs wbs
# yolo_list = ['0wt', 'jgc', '2lsd', 'lxb', '4bbt', 'xgg', '6txd', 'lwz', '8tc', 'xbs', '10wbs', 'a-pg', '12b-pg',
# 'c-pg', '14g-pg', 'z-pg']
yolo_label_list_copy = yolo_label_list.copy()
swin_trueLabel_list_copy = swin_trueLabel_list.copy()
for i in yolo_label_list_copy:
if i in swin_object:
index1 = yolo_label_list.index(i)
del yolo_bbox_list[index1]
del yolo_score_list[index1]
del yolo_label_list[index1]
# label_filter = [4, 5, 11, 12, 13, 14, 15]
# filer_box = {}
# filter_list = []
# filter_label_list = []
# for i in range(len(yolo_label_list)):
# if yolo_label_list_copy[i] in label_filter:
# filter_list.append(i)
# filter_label_list.append(yolo_label_list_copy[i])
# yolo_bbox_list_copy = yolo_bbox_list
# yolo_score_list_copy = yolo_score_list
#
#
# for pair in combinations(filter_list, 2):
# box1 = yolo_bbox_list_copy[pair[0]]
# box2 = yolo_bbox_list_copy[pair[1]]
# b_iou = filterbox_iou(box1, box2)
# if b_iou >= 0.9:
# if box1 in yolo_bbox_list and box2 in yolo_bbox_list:
# index_0 = yolo_bbox_list.index(box1)
# index_1 = yolo_bbox_list.index(box2)
# index = index_0 if yolo_score_list[pair[0]] <= yolo_score_list[pair[1]] else index_1
# del yolo_bbox_list[index]
# del yolo_score_list[index]
# del yolo_label_list[index]
for i in swin_trueLabel_list_copy:
if i not in swin_object:
index2 = swin_trueLabel_list.index(i)
del swin_bbox_list[index2]
del swin_score_list[index2]
del swin_trueLabel_list[index2]
two_bbox, two_score, two_label = copy.deepcopy(swin_bbox_list), copy.deepcopy(swin_score_list), copy.deepcopy(swin_trueLabel_list)
for i in range(len(yolo_bbox_list)):
two_bbox.append(yolo_bbox_list[i])
two_score.append(yolo_score_list[i])
two_label.append(yolo_label_list[i])
two_bbox, two_score, two_label = torch.from_numpy(np.array(two_bbox)).reshape(-1, 4), torch.from_numpy(
np.array(two_score)).reshape(-1, 1), torch.from_numpy(np.array(two_label)).reshape(-1, 1)
yolo_bbox_list, yolo_score_list, yolo_label_list = torch.from_numpy(np.array(yolo_bbox_list)).reshape(-1,
4), torch.from_numpy(
np.array(yolo_score_list)).reshape(-1, 1), torch.from_numpy(np.array(yolo_label_list)).reshape(-1, 1)
swin_bbox_list, swin_score_list, swin_trueLabel_list = torch.from_numpy(np.array(swin_bbox_list)).reshape(
-1,
4), torch.from_numpy(
np.array(swin_score_list)).reshape(-1, 1), torch.from_numpy(np.array(swin_trueLabel_list)).reshape(-1,
1)
# det = torch.cat((torch.cat((swin_bbox_list, swin_score_list), 1), swin_trueLabel_list), 1) # only show swin_model inference result
# det = torch.cat((torch.cat((yolo_bbox_list, yolo_score_list), 1), yolo_label_list),1) # only show yolo_model inference result
det = torch.cat((torch.cat((two_bbox, two_score), 1), two_label), 1) # show two_model inference result
# bbox_list = [swin_bbox_list, yolo_bbox_list]
# score_list = [swin_score_list, yolo_score_list]
# label_list = [swin_trueLabel_list, yolo_label_list]
#
# wbf_weight = [1, 1]
# iou_thr = 0.55
# skip_box_thr = 0.0001
#
# boxes, scores, labels = weighted_boxes_fusion(bbox_list, score_list, label_list, weights=wbf_weight,
# iou_thr=iou_thr, skip_box_thr=skip_box_thr)
# for in_file in boxes:
# in_file[0], in_file[1], in_file[2], in_file[3] = int(in_file[0] * 640), int(in_file[1] * 480), int(
# in_file[2] * 640), int(in_file[3] * 480)
# boxes, scores, labels = boxes.reshape(-1, 4), scores.reshape(-1, 1), labels.reshape(-1, 1)
# boxes, scores, labels = torch.from_numpy(boxes), torch.from_numpy(scores), torch.from_numpy(labels)
# det2model = torch.cat((torch.cat((boxes, scores), 1), labels), 1)
# det = det2model
if det is not None and len(det):
numers = len(det)
# Rescale boxes from img_size to im0 size
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
# Print results
for c in det[:, -1].unique():
n = (det[:, -1] == c).sum() # detections per class
s += '%g %ss, ' % (n, names[int(c)]) # add to string
# Write results 包围框、置信度、种类
for *xyxy, conf, cls in reversed(det):
if dict1.__contains__(cls):
dict1[cls] = dict1[cls] + 1
dict1['total'] = dict1['total'] + 1
else:
dict1[cls] = 0
dict1['total'] = dict1['total'] + 1
if save_txt: # Write to file
xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh
line = (cls, conf, *xywh) if opt.save_conf else (cls, *xywh) # label format
with open(txt_path + '.txt', 'a') as f:
f.write(('%g ' * len(line) + '\n') % line)
if save_img or view_img: # Add bbox to image
label = '%s %.2f' % (names[int(cls)], conf)
img1 = im0.copy()
# if cv2.waitKey(1)==32:
# count = 0
# for filename in os.listdir('new_image/'):
# if filename.endswith('.jpg'):
# count += 1
# # print(count)
# print(f"保存第{count + 1}张图片")
# # 保存图像,保存到上一层的imgs文件夹内,以1、2、3、4...为文件名保存图像
# cv2.imwrite('new_image/{}.jpg'.format(count + 1), img1)
# plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=0.5) # 线的粗细
plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=2) # 线的粗细
# print(f"\n{names[int(cls)]}的包围框坐标是{int(xyxy[0]),int(xyxy[1]),int(xyxy[2]),int(xyxy[3])}")
# print(f"\n{names[int(cls)]}的中心坐标是{(int(xyxy[0])+int(xyxy[2]))/2, (int(xyxy[1])+int(xyxy[3]))/2}")
# Print time (inference + NMS)
# print('%sDone. (%.3fs)' % (s, t2 - t1))
print(f"{s}")
print(f"s")
# 打印坐标、种类
# print('%s' % (names[int(cls)]))
# Stream results
# view_img = True
if view_img:
cv2.imshow(p, im0)
if cv2.waitKey(1) == ord('q'): # q to quit
raise StopIteration
# Save results (image with detections)
if save_img:
if dataset.mode == 'images':
txt = f".numers={len(det)}"
cv2.putText(im0, txt,
(50, 100),
cv2.FONT_HERSHEY_SIMPLEX, 1.2, (34, 157, 255), 2)
cv2.imwrite(save_path, im0)
else:
if vid_path != save_path: # new video
vid_path = save_path
if isinstance(vid_writer, cv2.VideoWriter):
vid_writer.release() # release previous video writer
fourcc = 'mp4v' # output video codec
fps = vid_cap.get(cv2.CAP_PROP_FPS)
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*fourcc), fps, (w, h))
vid_writer.write(im0)
im_after = im0
img_dict[frame_key] = dict1
frame_key += 1
detected = len(det)
img_category = save_path.split('/')[-1].split('_')[0]
if img_category == 'body':
true = 17
elif img_category =='op':
true = 12
else:
true = 29
root_path = '/root/results/'
if detected == true:
plt.figure()
plt.subplot(1, 3, 1)
plt.title('original image', size=10)
plt.axis([0, 640, 0, 480])
plt.xticks([])
plt.yticks([])
plt.imshow(img_before.transpose(1, 2, 0))
plt.subplot(1, 3, 2)
plt.title('detected image', size=10)
plt.axis([0, 640, 0, 480])
plt.xticks([])
plt.yticks([])
plt.imshow(im_after)
plt.text(700, 300, f"Original:{true}", size=10)
plt.text(700, 100, f"Detected:{detected}", size=10)
# plt.text(700, 100, f"Average confidence:{conf}%")
plt.savefig(root_path + f'{img_category}_{counting_img}.jpg', bbox_inches='tight', pad_inches=0.1,
dpi=800)
counting_img += 1
full_detect += detected
full_truth += true
elif detected != true and f_detect <= 7 and random.uniform(0, 1) > 0.65:
plt.figure()
plt.subplot(1, 3, 1)
plt.title(f'original image', size=10)
plt.axis([0, 640, 0, 480])
plt.xticks([])
plt.yticks([])
plt.imshow(img_before.transpose(1, 2, 0))
plt.subplot(1, 3, 2)
plt.title(f'detected image', size=10)
plt.axis([0, 640, 0, 480])
plt.xticks([])
plt.yticks([])
plt.imshow(im_after)
plt.text(700, 300, f"Original:{true}", size=10)
plt.text(700, 100, f"Detected:{detected}", size=10)
plt.savefig(root_path + f'{img_category}_{counting_img}.jpg', bbox_inches='tight', pad_inches=0.1,
dpi=800)
counting_img += 1
f_detect+=1
full_detect += detected
full_truth += true
else:
# print('wrong-------', save_path)
pass
# plt.show()
# plt.figure()
# plt.axis([0, 640, 0, 480])
# plt.text(700, 300, f"Origina:{count_acc}%")
# plt.text(700, 200, f"Detected:{classify_acc}%")
# plt.text(700, 100, f"Average confidence:{conf}%")
# break
if save_txt or save_img:
print('Results saved to %s' % Path(out))
full_time = time.time() - t0
print('Done. (%.3fs)' % full_time)
merege = math.ceil(full_detect/frame_key)
for i in img_dict:
if img_dict[i]['total'] == merege:
dict2 = img_dict[i]
plt.figure()
plt.xticks([])
plt.yticks([])
plt.axis([0, 640, 0, 680])
plt.text(50, 620, f"Calming detection report:{dict2}", color='blue', size=5)
plt.text(50, 520, f"Calming detection report", color='blue', size=10)
plt.text(50, 420, f"the detect: {merege}", color='blue', size=10)
plt.text(50, 320, f"All equipment Detected: {full_detect}", size=10)
plt.text(50, 220, f"All equipment manually counted: {full_truth}", size=10)
plt.text(50, 120, f"Counting Accuracy: %.2f" % (full_detect*100/full_truth) + '%', size=10)
plt.text(50, 40, f"Average time: %.2f" % (full_time/counting_img) + " s", size=10)
print('dfddddddddddddddddddddddddddddddddddddddddd')
plt.savefig('/root/Downloads/report.jpg')
if __name__ == '__main__':
get_image(fcap,framerate)
parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default='super_yolo.pt', help='model.pt path(s)')
parser.add_argument('--source', type=str, default='/root/Swin-Transformer-Object-Detection/demo/video_frame', help='source') # file/folder, 0 for webcam
parser.add_argument('--img-size', type=int, default=640, help='inference size (pixels)')
parser.add_argument('--conf-thres', type=float, default=0.85, help='object confidence threshold')
parser.add_argument('--iou-thres', type=float, default=0.45, help='IOU threshold for NMS')
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
parser.add_argument('--view-img', action='store_true', help='display results')
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
parser.add_argument('--save-dir', type=str, default='/root/Calming_final_test/results', help='directory to save results')
parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --class 0, or --class 0 2 3')
parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
parser.add_argument('--augment', action='store_true', help='augmented inference')
parser.add_argument('--update', action='store_true', help='update all models')
opt = parser.parse_args()
print(opt)
with torch.no_grad():
if opt.update: # update all models (to fix SourceChangeWarning)
for opt.weights in ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt']:
detect()
strip_optimizer(opt.weights)
else:
detect()
| c = 1
while True:
ret, frame = fcap.read()
if ret:
if (c % framerate == 0):
cv2.imwrite(data_root + 'demo/video_frame/' + str(c) + '.jpg', frame)
c += 1
cv2.waitKey(0)
else:
print('the task is end')
break
fcap.release() |
PitftGraphicLib.py | #Based on gerthvh's menu_8button.py
#BlockComPhone PitftGraphicLib v0.1 For Portrait Pitft Only
import sys, pygame
from pygame.locals import *
import time
import subprocess
import os
from subprocess import *
#os.system('adafruit-pitft-touch-cal -f') #Confirm orentation #But TOO Laggy
os.environ["SDL_FBDEV"] = "/dev/fb1"
os.environ["SDL_MOUSEDEV"] = "/dev/input/touchscreen"
os.environ["SDL_MOUSEDRV"] = "TSLIB"
#set size of the screen
size = width, height = 240, 320
#screen = pygame.display.set_mode(size)
os.system('sudo sh -c "echo 508 > /sys/class/gpio/export"')
#os.system('ls -l /sys/class/gpio')
os.system("sudo sh -c 'echo 'out' > /sys/class/gpio/gpio508/direction'")
os.system("sudo sh -c 'echo '1' > /sys/class/gpio/gpio508/value'")
def initdis():
global screen
screen = pygame.display.set_mode(size)
# Initialize pygame and hide mouse
pygame.init()
pygame.mouse.set_visible(0)
screen = pygame.display.set_mode(size)
# Background Color
screen.fill(black)
# Outer Border
pygame.draw.rect(screen, red, (0,0,240,320),10)
def disinitdis():
pygame.quit()
global touchlist
touchlist = []
def clear(xpos,ypos,length,height):
pygame.draw.rect(screen, black, (xpos,ypos,length,height),0)
def clearall():
pygame.draw.rect(screen, black, (0,0,240,320),0)
pygame.draw.rect(screen, red, (0,0,240,320),10)
global touchlist
touchlist = []
def backlight(onoff):
#print('Backlight')
|
#colors R G B
white = (255, 255, 255)
red = (255, 0, 0)
green = ( 0, 255, 0)
blue = ( 0, 0, 255)
black = ( 0, 0, 0)
cyan = ( 50, 255, 255)
magenta = (255, 0, 255)
yellow = (255, 255, 0)
orange = (255, 127, 0)
touchlist = []
# define function for printing text in a specific place with a specific width and height with a specific colour and border
def make_button(text, xpo, ypo, height, width, recspace, colour, fontsize, function):
font=pygame.font.Font(None,fontsize)
label=font.render(str(text), 1, (colour))
screen.blit(label,(xpo,ypo))
#Space between rec and label
pygame.draw.rect(screen, colour, (xpo-recspace,ypo-recspace,width,height),3)
#Touchscreen
global touchlist
touchlist.append((xpo,width+xpo,ypo,height+ypo,function))
# define function for printing text in a specific place with a specific colour
def make_label(text, xpo, ypo, fontsize, colour):
font=pygame.font.Font(None,fontsize)
label=font.render(str(text), 1, (colour))
screen.blit(label,(xpo,ypo))
# define function that checks for touch location
def on_touch():
counterst = 0
# get the position that was touched
touch_pos = (pygame.mouse.get_pos() [0], pygame.mouse.get_pos() [1])
while counterst < len(touchlist):
if touchlist[counterst][0] <= touch_pos[0] <= touchlist[counterst][1] and touchlist[counterst][2] <= touch_pos[1] <= touchlist[counterst][3]:
touchlist[counterst][4]()
counterst = counterst + 1
def touchdisch():
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
print "screen pressed" #for debugging purposes
pos = (pygame.mouse.get_pos() [0], pygame.mouse.get_pos() [1])
print pos #for checking
pygame.draw.circle(screen, white, pos, 2, 0) #for debugging purposes - adds a small dot where the screen is pressed
on_touch()
#ensure there is always a safe way to end the program if the touch screen fails
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
sys.exit()
if event.type == pygame.QUIT: sys.exit()
pygame.display.update()
| if onoff: os.system("sudo sh -c 'echo '1' > /sys/class/gpio/gpio508/value'")
else: os.system("sudo sh -c 'echo '0' > /sys/class/gpio/gpio508/value'") |
client.py | """
.. module:: python-etcd
:synopsis: A python etcd client.
.. moduleauthor:: Jose Plana <[email protected]>
"""
import urllib3
import json
import ssl
import etcd
class Client(object):
"""
Client for etcd, the distributed log service using raft.
"""
_MGET = 'GET'
_MPUT = 'PUT'
_MPOST = 'POST'
_MDELETE = 'DELETE'
_comparison_conditions = set(('prevValue', 'prevIndex', 'prevExist'))
_read_options = set(('recursive', 'wait', 'waitIndex', 'sorted', 'consistent'))
_del_conditions = set(('prevValue', 'prevIndex'))
def __init__(
self,
host='127.0.0.1',
port=4001,
read_timeout=60,
allow_redirect=True,
protocol='http',
cert=None,
ca_cert=None,
allow_reconnect=False,
):
"""
Initialize the client.
Args:
host (mixed):
If a string, IP to connect to.
If a tuple ((host, port), (host, port), ...)
port (int): Port used to connect to etcd.
read_timeout (int): max seconds to wait for a read.
allow_redirect (bool): allow the client to connect to other nodes.
+
protocol (str): Protocol used to connect to etcd.
cert (mixed): If a string, the whole ssl client certificate;
if a tuple, the cert and key file names.
ca_cert (str): The ca certificate. If pressent it will enable
validation.
allow_reconnect (bool): allow the client to reconnect to another
etcd server in the cluster in the case the
default one does not respond.
"""
self._machines_cache = []
self._protocol = protocol
def uri(protocol, host, port):
return '%s://%s:%d' % (protocol, host, port)
if not isinstance(host, tuple):
self._host = host
self._port = port
else:
self._host, self._port = host[0]
self._machines_cache.extend(
[uri(self._protocol, *conn) for conn in host])
self._base_uri = uri(self._protocol, self._host, self._port)
self.version_prefix = '/v2'
self._read_timeout = read_timeout
self._allow_redirect = allow_redirect
self._allow_reconnect = allow_reconnect
# SSL Client certificate support
kw = {}
if self._read_timeout > 0:
kw['timeout'] = self._read_timeout
if protocol == 'https':
# If we don't allow TLSv1, clients using older version of OpenSSL
# (<1.0) won't be able to connect.
kw['ssl_version'] = ssl.PROTOCOL_TLSv1
if cert:
if isinstance(cert, tuple):
# Key and cert are separate
kw['cert_file'] = cert[0]
kw['key_file'] = cert[1]
else:
# combined certificate
kw['cert_file'] = cert
if ca_cert:
kw['ca_certs'] = ca_cert
kw['cert_reqs'] = ssl.CERT_REQUIRED
self.http = urllib3.PoolManager(num_pools=10, **kw)
if self._allow_reconnect:
# we need the set of servers in the cluster in order to try
# reconnecting upon error.
self._machines_cache = self.machines
self._machines_cache.remove(self._base_uri)
else:
self._machines_cache = []
@property
def base_uri(self):
"""URI used by the client to connect to etcd."""
return self._base_uri
@property
def host(self):
"""Node to connect etcd."""
return self._host
@property
def port(self):
"""Port to connect etcd."""
return self._port
@property
def protocol(self):
"""Protocol used to connect etcd."""
return self._protocol
@property
def read_timeout(self):
"""Max seconds to wait for a read."""
return self._read_timeout
@property
def allow_redirect(self):
"""Allow the client to connect to other nodes."""
return self._allow_redirect
@property
def machines(self):
"""
Members of the cluster.
Returns:
list. str with all the nodes in the cluster.
>>> print client.machines
['http://127.0.0.1:4001', 'http://127.0.0.1:4002']
"""
return [
node.strip() for node in self.api_execute(
self.version_prefix + '/machines',
self._MGET).data.decode('utf-8').split(',')
]
@property
def leader(self):
"""
Returns:
str. the leader of the cluster.
>>> print client.leader
'http://127.0.0.1:4001'
"""
return self.api_execute(
self.version_prefix + '/leader',
self._MGET).data.decode('ascii')
@property
def key_endpoint(self):
"""
REST key endpoint.
"""
return self.version_prefix + '/keys'
def __contains__(self, key):
"""
Check if a key is available in the cluster.
>>> print 'key' in client
True
"""
try:
self.get(key)
return True
except KeyError:
return False
def _sanitize_key(self, key):
if not key.startswith('/'):
key = "/{}".format(key)
return key
def write(self, key, value, ttl=None, dir=False, append=False, **kwdargs):
"""
Writes the value for a key, possibly doing atomit Compare-and-Swap
Args:
key (str): Key.
value (object): value to set
ttl (int): Time in seconds of expiration (optional).
dir (bool): Set to true if we are writing a directory; default is false.
append (bool): If true, it will post to append the new value to the dir, creating a sequential key. Defaults to false.
Other parameters modifying the write method are accepted:
prevValue (str): compare key to this value, and swap only if corresponding (optional).
prevIndex (int): modify key only if actual modifiedIndex matches the provided one (optional).
prevExist (bool): If false, only create key; if true, only update key.
Returns:
client.EtcdResult
>>> print client.write('/key', 'newValue', ttl=60, prevExist=False).value
'newValue'
"""
key = self._sanitize_key(key)
params = {}
if value is not None:
params['value'] = value
if ttl:
params['ttl'] = ttl
if dir:
if value:
raise etcd.EtcdException(
'Cannot create a directory with a value')
params['dir'] = "true"
for (k, v) in kwdargs.items():
if k in self._comparison_conditions:
if type(v) == bool:
params[k] = v and "true" or "false"
else:
params[k] = v
method = append and self._MPOST or self._MPUT
if '_endpoint' in kwdargs:
path = kwdargs['_endpoint'] + key
else:
path = self.key_endpoint + key
response = self.api_execute(path, method, params=params)
return self._result_from_response(response)
def update(self, obj):
"""
Updates the value for a key atomically. Typical usage would be:
c = etcd.Client()
o = c.read("/somekey")
o.value += 1
c.update(o)
Args:
obj (etcd.EtcdResult): The object that needs updating.
"""
kwdargs = {
'dir': obj.dir,
'ttl': obj.ttl,
'prevExist': True
}
if not obj.dir:
# prevIndex on a dir causes a 'not a file' error. d'oh!
kwdargs['prevIndex'] = obj.modifiedIndex
return self.write(obj.key, obj.value, **kwdargs)
def read(self, key, **kwdargs):
"""
Returns the value of the key 'key'.
Args:
key (str): Key.
Recognized kwd args
recursive (bool): If you should fetch recursively a dir
wait (bool): If we should wait and return next time the key is changed
waitIndex (int): The index to fetch results from.
sorted (bool): Sort the output keys (alphanumerically)
timeout (int): max seconds to wait for a read.
Returns:
client.EtcdResult (or an array of client.EtcdResult if a
subtree is queried)
Raises:
KeyValue: If the key doesn't exists.
urllib3.exceptions.TimeoutError: If timeout is reached.
>>> print client.get('/key').value
'value'
"""
key = self._sanitize_key(key)
params = {}
for (k, v) in kwdargs.items():
if k in self._read_options:
if type(v) == bool:
params[k] = v and "true" or "false"
else:
params[k] = v
timeout = kwdargs.get('timeout', None)
response = self.api_execute(
self.key_endpoint + key, self._MGET, params=params, timeout=timeout)
return self._result_from_response(response)
def delete(self, key, recursive=None, dir=None, **kwdargs):
"""
Removed a key from etcd.
Args:
key (str): Key.
recursive (bool): if we want to recursively delete a directory, set
it to true
dir (bool): if we want to delete a directory, set it to true
prevValue (str): compare key to this value, and swap only if
corresponding (optional).
prevIndex (int): modify key only if actual modifiedIndex matches the
provided one (optional).
Returns:
client.EtcdResult
Raises:
KeyValue: If the key doesn't exists.
>>> print client.delete('/key').key
'/key'
"""
key = self._sanitize_key(key)
kwds = {}
if recursive is not None:
kwds['recursive'] = recursive and "true" or "false"
if dir is not None:
kwds['dir'] = dir and "true" or "false"
for k in self._del_conditions:
if k in kwdargs:
kwds[k] = kwdargs[k]
response = self.api_execute(
self.key_endpoint + key, self._MDELETE, params=kwds)
return self._result_from_response(response)
# Higher-level methods on top of the basic primitives
def test_and_set(self, key, value, prev_value, ttl=None):
"""
Atomic test & set operation.
It will check if the value of 'key' is 'prev_value',
if the the check is correct will change the value for 'key' to 'value'
if the the check is false an exception will be raised.
Args:
key (str): Key.
value (object): value to set
prev_value (object): previous value.
ttl (int): Time in seconds of expiration (optional).
Returns:
client.EtcdResult
Raises:
ValueError: When the 'prev_value' is not the current value.
>>> print client.test_and_set('/key', 'new', 'old', ttl=60).value
'new'
"""
return self.write(key, value, prevValue=prev_value, ttl=ttl)
def set(self, key, value, ttl=None):
"""
Compatibility: sets the value of the key 'key' to the value 'value'
Args:
key (str): Key.
value (object): value to set
ttl (int): Time in seconds of expiration (optional).
Returns:
client.EtcdResult
Raises:
etcd.EtcdException: when something weird goes wrong.
"""
return self.write(key, value, ttl=ttl)
def get(self, key):
"""
Returns the value of the key 'key'.
Args:
key (str): Key.
Returns:
client.EtcdResult
Raises:
KeyError: If the key doesn't exists.
>>> print client.get('/key').value
'value'
"""
return self.read(key)
def watch(self, key, index=None, timeout=None):
"""
Blocks until a new event has been received, starting at index 'index'
Args:
key (str): Key.
index (int): Index to start from.
timeout (int): max seconds to wait for a read.
Returns:
client.EtcdResult
Raises:
KeyValue: If the key doesn't exists.
urllib3.exceptions.TimeoutError: If timeout is reached.
>>> print client.watch('/key').value
'value'
"""
if index:
return self.read(key, wait=True, waitIndex=index, timeout=timeout)
else:
return self.read(key, wait=True, timeout=timeout)
def eternal_watch(self, key, index=None):
"""
Generator that will yield changes from a key.
Note that this method will block forever until an event is generated.
Args:
key (str): Key to subcribe to.
index (int): Index from where the changes will be received.
Yields:
client.EtcdResult
>>> for event in client.eternal_watch('/subcription_key'):
... print event.value
...
value1
value2
"""
local_index = index
while True:
response = self.watch(key, index=local_index, timeout=0)
if local_index is not None:
local_index += 1
yield response
def | (self, *args, **kwargs):
return etcd.Lock(self, *args, **kwargs)
@property
def election(self):
return etcd.LeaderElection(self)
def _result_from_response(self, response):
""" Creates an EtcdResult from json dictionary """
try:
res = json.loads(response.data.decode('utf-8'))
r = etcd.EtcdResult(**res)
if response.status == 201:
r.newKey = True
r.parse_headers(response)
return r
except Exception as e:
raise etcd.EtcdException(
'Unable to decode server response: %s' % e)
def _next_server(self):
""" Selects the next server in the list, refreshes the server list. """
try:
return self._machines_cache.pop()
except IndexError:
raise etcd.EtcdException('No more machines in the cluster')
def api_execute(self, path, method, params=None, timeout=None):
""" Executes the query. """
some_request_failed = False
response = False
if timeout is None:
timeout = self.read_timeout
if timeout == 0:
timeout = None
if not path.startswith('/'):
raise ValueError('Path does not start with /')
while not response:
try:
url = self._base_uri + path
if (method == self._MGET) or (method == self._MDELETE):
response = self.http.request(
method,
url,
timeout=timeout,
fields=params,
redirect=self.allow_redirect)
elif (method == self._MPUT) or (method == self._MPOST):
response = self.http.request_encode_body(
method,
url,
fields=params,
timeout=timeout,
encode_multipart=False,
redirect=self.allow_redirect)
else:
raise etcd.EtcdException(
'HTTP method {} not supported'.format(method))
except urllib3.exceptions.MaxRetryError:
self._base_uri = self._next_server()
some_request_failed = True
if some_request_failed:
self._machines_cache = self.machines
self._machines_cache.remove(self._base_uri)
return self._handle_server_response(response)
def _handle_server_response(self, response):
""" Handles the server response """
if response.status in [200, 201]:
return response
else:
resp = response.data.decode('utf-8')
# throw the appropriate exception
try:
r = json.loads(resp)
except ValueError:
r = None
if r:
etcd.EtcdError.handle(**r)
else:
raise etcd.EtcdException(resp)
| get_lock |
pt-br.js | /*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. | */
CKEDITOR.plugins.setLang("language","pt-br",{button:"Configure o Idioma",remove:"Remover Idioma"}); | For licensing, see LICENSE.md or http://ckeditor.com/license |
setup.py | import pandas as p
import numpy as np
from file_setup_helper import FileSetupHelper as fsh
from preprocess_data import PreprocessData as pd
from model_export import ModelExport as me
import sys
from sklearn.linear_model import Ridge
def main():
#call for file download with given date
|
if __name__ == '__main__':
main()
| file_name = fsh(sys.argv[1], 1460, 0).download_csv()
#aquire features and target data filenames
features_file_name, target_file_name = pd(file_name).preprocess(True, None)
#init model, and open the features and target file
#(drop column added by pandas and bypass 29.02 potential error)
model = Ridge(alpha=1, fit_intercept=True)
X_train = p.read_csv(features_file_name).drop(['Unnamed: 0', 'Date_29.02'], axis=1)
y_train = p.read_csv(target_file_name).drop(['Unnamed: 0'], axis=1)
#export model with the given datasets and model
me(model, X_train, y_train).fit_and_export(sys.argv[2]) |
unsafe_utility.py | class UnsafeUtility: pass |
||
util.rs | use itertools::Itertools;
use proto::prelude::{NTBinaryMessage, NTMessage};
pub fn batch_messages(messages: Vec<NTBinaryMessage>, batch_size: usize) -> Vec<NTMessage> | {
messages
.into_iter()
.chunks(batch_size)
.into_iter()
.map(|batch| NTMessage::Binary(batch.collect()))
.collect()
} |
|
Window.Events.ts | import { firstValueFrom } from 'rxjs';
import { filter, takeUntil } from 'rxjs/operators';
import { RuntimeUri, rx, slug, t } from '../common';
/**
* Event API for working with Electron windows.
*/
export function | (args: { bus: t.EventBus<any> }): t.WindowEvents {
const { dispose$, dispose } = rx.disposable();
const bus = rx.busAsType<t.WindowEvent>(args.bus);
const is = Events.is;
const $ = bus.$.pipe(
takeUntil(dispose$),
filter((e) => is.base(e)),
);
/**
* Events that create a window.
*/
const create = {
req$: rx.payload<t.WindowCreateReqEvent>($, 'runtime.electron/Window/create:req'),
res$: rx.payload<t.WindowCreateResEvent>($, 'runtime.electron/Window/create:res'),
fire(args: {
url: string;
devTools?: t.WindowCreateReq['devTools'];
props?: t.WindowCreateReq['props'];
}) {
const { url, devTools, props = {} } = args;
const tx = slug();
const res = firstValueFrom(create.res$.pipe(filter((e) => e.tx === tx)));
bus.fire({
type: 'runtime.electron/Window/create:req',
payload: { tx, url, devTools, props },
});
return res;
},
};
/**
* Window status
*/
const status = {
req$: rx.payload<t.WindowStatusReqEvent>($, 'runtime.electron/Window/status:req'),
res$: rx.payload<t.WindowsStatusResEvent>($, 'runtime.electron/Window/status:res'),
async get() {
const tx = slug();
const res = firstValueFrom(status.res$.pipe(filter((e) => e.tx === tx)));
bus.fire({
type: 'runtime.electron/Window/status:req',
payload: { tx },
});
const { windows } = await res;
return { windows };
},
};
/**
* Change window state (eg, move, resize)
*/
const change = {
before$: rx.payload<t.WindowChangeEvent>($, 'runtime.electron/Window/change'),
after$: rx.payload<t.WindowChangedEvent>($, 'runtime.electron/Window/changed'),
fire(
window: t.WindowIdParam,
options: { bounds?: Partial<t.WindowBounds>; isVisible?: boolean } = {},
) {
const { bounds, isVisible } = options;
const uri = typeof window === 'string' ? window : RuntimeUri.window.create(window);
bus.fire({
type: 'runtime.electron/Window/change',
payload: { uri, bounds, isVisible },
});
},
};
return { $, is, dispose$, dispose, create, status, change };
}
/**
* Event matching.
*/
const matcher = (startsWith: string) => (input: any) => rx.isEvent(input, { startsWith });
Events.is = {
base: matcher('runtime.electron/Window/'),
};
| Events |
types.rs | // Copyright 2017 CoreOS, 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.
use chrono::prelude::*;
use expr::ast::Value;
#[derive(Deserialize, Value)]
pub struct | {
pub name: String,
pub email: String,
pub date: DateTime<Utc>,
pub github_login: Option<String>,
}
#[derive(Deserialize)]
pub struct Collaborator {
pub permission: Permission,
}
#[derive(Deserialize, Value)]
pub struct Comment {
pub user: User,
pub body: String,
pub created_at: DateTime<Utc>,
}
#[derive(Deserialize)]
pub struct Commit {
pub sha: String,
pub commit: CommitBody,
pub author: User,
pub committer: User,
}
#[derive(Deserialize)]
pub struct CommitBody {
pub author: Author,
pub committer: Author,
pub message: String,
}
#[derive(Debug, Deserialize, Value)]
pub struct CommitReference {
pub sha: String,
pub label: String,
pub user: User,
}
#[derive(Deserialize)]
pub struct Content {
pub content: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct Empty {}
#[derive(Debug, Deserialize)]
pub struct ErrorResponse {
pub message: String,
pub errors: Option<Vec<Error>>,
}
#[derive(Debug, Deserialize)]
pub struct Error {
pub resource: String,
pub field: String,
pub code: String,
pub message: Option<String>,
}
#[derive(Debug, Deserialize)]
pub struct Event {
pub repository: Repository,
pub action: Option<String>,
pub hook: Option<Empty>,
pub pull_request: Option<PullRequest>,
}
#[derive(Deserialize, PartialEq)]
pub enum Permission {
#[serde(rename = "admin")]
Admin,
#[serde(rename = "write")]
Write,
#[serde(rename = "read")]
Read,
#[serde(rename = "none")]
None,
}
#[derive(Debug, Deserialize)]
pub struct PullRequest {
pub user: User,
pub number: usize,
pub title: String,
pub body: Option<String>,
pub base: CommitReference,
pub head: CommitReference,
}
#[derive(Debug, Deserialize)]
pub struct Repository {
pub owner: User,
pub name: String,
}
#[derive(Debug, Deserialize, Value)]
pub struct User {
pub login: String,
}
| Author |
init.go | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package v20150501preview
import (
"fmt"
"github.com/blang/semver"
"github.com/pulumi/pulumi-azure-nextgen/sdk/go/azure"
"github.com/pulumi/pulumi/sdk/v2/go/pulumi"
)
type module struct {
version semver.Version
}
func (m *module) Version() semver.Version {
return m.version
}
func (m *module) Construct(ctx *pulumi.Context, name, typ, urn string) (r pulumi.Resource, err error) {
switch typ {
case "azure-nextgen:storage/v20150501preview:StorageAccount":
r, err = NewStorageAccount(ctx, name, nil, pulumi.URN_(urn))
default:
return nil, fmt.Errorf("unknown resource type: %s", typ)
}
return
}
func | () {
version, err := azure.PkgVersion()
if err != nil {
fmt.Println("failed to determine package version. defaulting to v1: %v", err)
}
pulumi.RegisterResourceModule(
"azure-nextgen",
"storage/v20150501preview",
&module{version},
)
}
| init |
collection.service.ts | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { cardList } from 'app/game_model/cards/cardList';
import {
Collection,
Rewards,
SavedCollection
} from 'app/game_model/collection';
import { AuthenticationService } from 'app/user/authentication.service';
import { DailyDialogComponent } from './daily-dialog/daily-dialog.component';
import { apiURL } from './url';
import { ResourceTypeNames } from './game_model/resource';
import { Unit } from './game_model/card-types/unit';
import { Item } from './game_model/card-types/item';
import { Enchantment } from './game_model/card-types/enchantment';
import { CardType } from './game_model/cardType';
const saveURL = `${apiURL}/api/cards/storeCollection`;
const loadUrl = `${apiURL}/api/cards/getCollection`;
const buyPackURL = `${apiURL}/api/cards/buy`;
const openPackURL = `${apiURL}/api/cards/openPack`;
const dailyURL = `${apiURL}/api/cards/checkDaily`;
interface DailyRewardData {
daily: boolean;
cards: string[];
nextRewardTime: number;
}
@Injectable()
export class | {
private collection = new Collection();
static describeReward(reward: Rewards): string {
let msg = `You earned ${reward.gold} gold`;
if (reward.packs === 1) {
msg += ` and a card pack`;
} else if (reward.packs > 1) {
msg += ` and ${reward.packs} card packs`;
}
return msg + '.';
}
constructor(
private auth: AuthenticationService,
private http: HttpClient,
private dialog: MatDialog
) {
auth.onAuth(data => {
if (data) {
this.load();
}
});
(window as any).getCardSheet = () => {
const cards = cardList
.getCards()
.sort((a, b) => (a.getName() > b.getName() ? 1 : -1));
let output = `Name\tType\tEnergy Cost\t${ResourceTypeNames.join(
'\t'
)}\tDamage/Empower\tLife/Power\tText\n`;
for (const card of cards) {
output += card.getName() + '\t';
output += CardType[card.getCardType()] + '\t';
output += card.getCost().getNumeric() + '\t';
for (const resourceName of ResourceTypeNames) {
output += card.getCost().getOfType(resourceName) + '\t';
}
if (card instanceof Unit) {
output += card.getDamage() + '\t';
output += card.getLife();
} else if (card instanceof Item) {
output += card.getDamage() + '\t';
output += card.getLife();
} else if (card instanceof Enchantment) {
output += card.getModifyCost().getNumeric() + '\t';
output += card.getPower();
}
output += card.getText() + '\n';
}
return output;
};
}
private checkDaily() {
this.http
.get<DailyRewardData>(dailyURL, {
headers: this.auth.getAuthHeader()
})
.toPromise()
.then(res => {
if (!res.daily) {
// const wait = res.nextRewardTime / 1000 / 60 / 60;
// dialogRef.componentInstance.nextRewardTime = wait;
return;
} else {
const dialogRef = this.dialog.open(DailyDialogComponent);
dialogRef.componentInstance.rewards = res.cards.map(id =>
cardList.getCard(id)
);
}
});
}
public unlockAll() {
for (const card of cardList.getCards()) {
const diff = 4 - this.collection.getCardCount(card);
this.collection.addCard(card, Math.max(diff, 0));
}
}
public save() {
return this.http
.post(
saveURL,
{ collection: this.collection.getSavable() },
{ headers: this.auth.getAuthHeader() }
)
.toPromise();
}
public load() {
return this.http
.get<SavedCollection>(loadUrl, {
headers: this.auth.getAuthHeader()
})
.toPromise()
.then(res => {
this.collection.fromSavable(res);
this.checkDaily();
});
}
public async openPack() {
return this.http
.post<string[]>(
openPackURL,
{ item: 'pack' },
{ headers: this.auth.getAuthHeader() }
)
.toPromise()
.then(ids => {
this.collection.removePack();
return ids.map(id => {
const card = cardList.getCard(id);
this.collection.addCard(card);
return card;
});
})
.catch(errData => {
if (errData.error) {
this.collection.removePack();
}
return errData.error ? errData.error.message : errData.message;
});
}
public buyPack() {
return this.http
.post(
buyPackURL,
{ item: 'pack' },
{ headers: this.auth.getAuthHeader() }
)
.toPromise()
.then(() => {
this.collection.buyPack();
return true;
})
.catch(err => {
return false;
});
}
public getCollection() {
return this.collection;
}
public async onGameEnd(won: boolean, quit: boolean) {
if (!won && quit) {
return '';
}
let reward: Rewards;
try {
reward = await this.http
.post<Rewards>(
`${apiURL}/api/cards/reward`,
{ won: won },
{ headers: this.auth.getAuthHeader() }
)
.toPromise();
} catch (e) {
console.error(e);
return 'Error loading rewards.';
}
this.collection.addReward(reward);
return CollectionService.describeReward(reward);
}
}
| CollectionService |
mod.rs | pub mod part1;
pub mod part2;
#[cfg(test)]
mod tests {
use crate::aoc_test_suite;
| (part1_main, 822, include_str!("input.txt")),
(part1_sanity1, 567, "BFFFBBFRRR"),
(part1_sanity2, 119, "FFFBBBFRRR"),
(part1_sanity3, 820, "BBFFBBFRLL"),
);
aoc_test_suite!(
super::part2::run,
(part2_main, 705, include_str!("input.txt")),
);
} | aoc_test_suite!(
super::part1::run, |
create_addon_istio.go | package cmd
import (
"fmt"
"io"
"io/ioutil"
"path/filepath"
"strings"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
const (
defaultIstioNamespace = "istio-system"
defaultIstioReleaseName = "istio"
defaultIstioPassword = "istio"
defaultIstioConfigDir = "/istio_service_dir"
)
var (
createAddonIstioLong = templates.LongDesc(`
Creates the istio addon for service mesh on kubernetes
`)
createAddonIstioExample = templates.Examples(`
# Create the istio addon
jx create addon istio
# Create the istio addon in a custom namespace
jx create addon istio -n mynamespace
`)
)
// CreateAddonIstioOptions the options for the create spring command
type CreateAddonIstioOptions struct {
CreateAddonOptions
Chart string
Password string
ConfigDir string
NoInjectorWebhook bool
Dir string
}
// NewCmdCreateAddonIstio creates a command object for the "create" command
func NewCmdCreateAddonIstio(f Factory, out io.Writer, errOut io.Writer) *cobra.Command |
// Run implements the command
func (o *CreateAddonIstioOptions) Run() error {
if o.Chart == "" {
// lets git clone the source to find the istio charts as they are not published anywhere yet
dir, err := o.getIstioChartsFromGitHub()
if err != nil {
return err
}
chartDir := filepath.Join(dir, kube.ChartIstio)
exists, err := util.FileExists(chartDir)
if !exists {
return fmt.Errorf("Could not find folder %s inside istio clone at %s", kube.ChartIstio, dir)
}
o.Dir = dir
o.Chart = kube.ChartIstio
}
if o.ReleaseName == "" {
return util.MissingOption(optionRelease)
}
if o.Chart == "" {
return util.MissingOption(optionChart)
}
err := o.ensureHelm()
if err != nil {
return errors.Wrap(err, "failed to ensure that helm is present")
}
_, _, err = o.KubeClient()
if err != nil {
return err
}
devNamespace, _, err := kube.GetDevNamespace(o.kubeClient, o.currentNamespace)
if err != nil {
return fmt.Errorf("cannot find a dev team namespace to get existing exposecontroller config from. %v", err)
}
log.Infof("found dev namespace %s\n", devNamespace)
values := []string{}
if o.NoInjectorWebhook {
values = append(values, "sidecarInjectorWebhook.enabled=false")
}
setValues := strings.Split(o.SetValues, ",")
values = append(values, setValues...)
err = o.installChartAt(o.Dir, o.ReleaseName, o.Chart, o.Version, o.Namespace, true, values)
if err != nil {
return fmt.Errorf("istio deployment failed: %v", err)
}
return nil
}
func (o *CreateAddonIstioOptions) getIstioChartsFromGitHub() (string, error) {
answer, err := ioutil.TempDir("", "istio")
if err != nil {
return answer, err
}
gitRepo := "https://github.com/istio/istio.git"
log.Infof("Cloning %s to %s\n", util.ColorInfo(gitRepo), util.ColorInfo(answer))
err = o.Git().Clone(gitRepo, answer)
if err != nil {
return answer, err
}
return answer, nil
}
| {
options := &CreateAddonIstioOptions{
CreateAddonOptions: CreateAddonOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
},
}
cmd := &cobra.Command{
Use: "istio",
Short: "Create the Istio addon for service mesh",
Aliases: []string{"env"},
Long: createAddonIstioLong,
Example: createAddonIstioExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
options.addCommonFlags(cmd)
options.addFlags(cmd, defaultIstioNamespace, defaultIstioReleaseName)
cmd.Flags().StringVarP(&options.Version, "version", "v", "", "The version of the Istio chart to use")
cmd.Flags().StringVarP(&options.Password, "password", "p", defaultIstioPassword, "The default password to use for Istio")
cmd.Flags().StringVarP(&options.ConfigDir, "config-dir", "d", defaultIstioConfigDir, "The config directory to use")
cmd.Flags().StringVarP(&options.Chart, optionChart, "c", "", "The name of the chart to use")
cmd.Flags().BoolVarP(&options.NoInjectorWebhook, "no-injector-webhook", "", false, "Disables the injector webhook")
return cmd
} |
osc-sender.py | import random
import time
from pythonosc import osc_message_builder
from pythonosc import udp_client
client=udp_client.SimpleUDPClient("127.0.0.1",8000)
dest = [
"/red/scale",
"/red/offset",
"/red/speed",
"/green/scale",
"/green/offset",
"/green/speed",
"/blue/scale",
"/blue/offset",
"/blue/speed",
"/shape/size",
"/shape/sides",
"/shape/xinc",
"/shape/yinc",
"/shape/xcenter",
"/shape/ycenter",
"/shape/shapecount",
"/shape/shapeskip",
"/global/strobe",
"/global/invert"
]
def random_test():
val_set = random.randrange(0,255)
dest_s = dest[random.randrange(0, len(dest))]
client.send_message(dest_s,val_set)
print("sent {} to {}".format(val_set,dest_s))
while True:
random_test() | time.sleep(1) | |
main.rs | use once_cell::sync::Lazy;
use regex::Regex;
fn main() {
println!("Implement me!");
}
mod parser {
pub use crate::{Precision, Sign};
use nom::{
branch::alt,
bytes::complete::{tag, take_while},
character::complete::{alpha1, anychar, char, one_of},
combinator::{all_consuming, map, opt, peek},
error::ErrorKind,
sequence::{delimited, pair, preceded, terminated, tuple},
IResult,
};
/// Matches `[<>^]?`
fn align(i: &str) -> IResult<&str, char> {
one_of("<>^")(i)
}
/// Matches `[a-zA-Z0-9_]?`
fn is_identifier_char(c: char) -> bool {
c.is_alphanumeric() || c == '_'
}
/// Peeks `_[a-zA-Z0-9_]`
fn is_underscore_then_ident_char(i: &str) -> IResult<&str, ()> {
if i.len() < 2 {
return Err(nom::Err::Error((i, ErrorKind::IsNot)));
}
if i.starts_with('_') && is_identifier_char(i.chars().nth(1).unwrap()) {
Ok((i, ()))
} else {
Err(nom::Err::Error((i, ErrorKind::IsNot)))
}
}
/// Matches `(([a-zA-Z][a-zA-Z0-9_]*)|(_[a-zA-Z0-9_]+))`
fn identifier(i: &str) -> IResult<&str, &str> {
// Matches [a-zA-Z][a-zA-Z0-9_]*
let alpha = preceded(peek(alpha1), take_while(is_identifier_char));
// Matches _[a-zA-Z0-9_]+
let underscore = preceded(
is_underscore_then_ident_char,
take_while(is_identifier_char),
);
alt((alpha, underscore))(i)
}
/// Matches `[+-]?`
fn sign(i: &str) -> IResult<&str, Sign> {
one_of("+-")(i).map(|(rest, s)| {
(
rest,
match s {
'+' => Sign::Plus,
'-' => Sign::Minus,
_ => unreachable!(),
},
)
})
}
fn is_digit_char(c: char) -> bool {
c.is_ascii_digit()
}
/// Matches `0|[1-9][0-9]*`
fn integer(i: &str) -> IResult<&str, usize> {
// Matches [1-9][0-9]*
let one = preceded(peek(one_of("123456789")), take_while(is_digit_char));
alt((tag("0"), one))(i).and_then(|(rest, i)| {
i.parse::<usize>()
.map(|i| (rest, i))
.map_err(|_| nom::Err::Error((rest, ErrorKind::IsNot)))
})
}
/// Matches [`integer`]`$`
fn parameter(i: &str) -> IResult<&str, usize> {
terminated(integer, char('$'))(i)
}
/// Matches [`parameter`] | [`integer`]
fn width(i: &str) -> IResult<&str, usize> {
alt((parameter, integer))(i)
}
/// Matches [`width`] | `*`
fn precision(i: &str) -> IResult<&str, Precision> {
alt((
map(parameter, Precision::Argument),
map(integer, Precision::Integer),
map(char('*'), |_| Precision::Asterisk),
))(i)
}
type ParseOutput = (Option<Sign>, Option<usize>, Option<Precision>);
pub fn parse(i: &str) -> IResult<&str, ParseOutput> {
let fill = anychar;
let hash = char('#');
let zero = char('0');
let dot = char('.');
let type_ = alt((identifier, tag("?")));
all_consuming(terminated(
tuple((
delimited(
opt(alt((preceded(fill, align), align))),
opt(sign),
pair(opt(hash), opt(zero)),
),
opt(width),
opt(preceded(dot, precision)),
)),
opt(type_),
))(i)
}
pub fn parse_without_err(i: &str) -> ParseOutput {
let parsed = parse(i);
dbg!(&parsed);
if let Ok((_, output)) = parsed {
return output;
}
(None, None, None)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn align_test() {
assert_eq!(align("<>ab"), Ok((">ab", '<')));
assert_eq!(align("ab"), Err(nom::Err::Error(("ab", ErrorKind::OneOf))));
}
#[test]
fn sign_test() {
assert_eq!(sign("+-ab"), Ok(("-ab", Sign::Plus)));
assert_eq!(sign("-ab"), Ok(("ab", Sign::Minus)));
assert_eq!(sign("ab"), Err(nom::Err::Error(("ab", ErrorKind::OneOf))));
}
#[test]
fn identifier_test() {
assert_eq!(identifier("ident_0"), Ok(("", "ident_0")));
assert_eq!(identifier("_ident_0*"), Ok(("*", "_ident_0")));
assert_eq!(identifier("__"), Ok(("", "__")));
assert_eq!(
identifier("_"),
Err(nom::Err::Error(("_", ErrorKind::IsNot)))
);
}
#[test]
fn integer_test() |
}
}
fn parse(input: &str) -> (Option<Sign>, Option<usize>, Option<Precision>) {
static RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(r"(.?[<>^])?(?P<sign>[+-])?#?0?(?P<width>(((0|[1-9][0-9]*)|([A-Za-z]\w*))\$)|(0|[1-9][0-9]*))?(\.(?P<precision>((((0|[1-9][0-9]*)|([A-Za-z]\w*))\$)|(0|[1-9][0-9]*))|\*))?(([A-Za-z]\w*)|\?)?").unwrap()
});
if let Some(names) = RE.captures(input) {
let sign = names.name("sign").map(|m| match m {
m if m.as_str() == "+" => Sign::Plus,
m if m.as_str() == "-" => Sign::Minus,
_ => unreachable!(),
});
let precision = names.name("precision").and_then(|m| match m {
m if m.as_str() == "*" => Some(Precision::Asterisk),
m if !m.as_str().ends_with('$') => {
m.as_str().parse::<usize>().map(Precision::Integer).ok()
}
m if m.as_str().ends_with('$') => {
let without_last_char = &m.as_str()[..m.as_str().len() - 1];
without_last_char
.parse::<usize>()
.map(Precision::Argument)
.ok()
}
_ => unreachable!(),
});
let width = names.name("width").and_then(|m| match m {
m if !m.as_str().ends_with('$') => m.as_str().parse::<usize>().ok(),
m if m.as_str().ends_with('$') => {
let without_last_char = &m.as_str()[..m.as_str().len() - 1];
without_last_char.parse::<usize>().ok()
}
_ => unreachable!(),
});
return (sign, width, precision);
}
(None, None, None)
}
#[derive(Debug, PartialEq)]
pub enum Sign {
Plus,
Minus,
}
#[derive(Debug, PartialEq)]
pub enum Precision {
Integer(usize),
Argument(usize),
Asterisk,
}
#[cfg(test)]
mod spec {
use super::*;
#[test]
fn parses_sign() {
for (input, expected) in vec![
("", None),
(">8.*", None),
(">+8.*", Some(Sign::Plus)),
("-.1$x", Some(Sign::Minus)),
("a^#043.8?", None),
] {
let (sign, ..) = parse(input);
assert_eq!(sign, expected);
let (sign, ..) = parser::parse_without_err(input);
assert_eq!(sign, expected);
}
}
#[test]
fn parses_width() {
for (input, expected) in &[
("", None),
(">8.*", Some(8)),
(">+8.*", Some(8)),
("-.1$x", None),
("a^#043.8?", Some(43)),
] {
let (_, width, _) = parse(input);
assert_eq!(width, *expected);
let (_, width, _) = parser::parse_without_err(input);
assert_eq!(width, *expected);
}
}
#[test]
fn parses_precision() {
for (input, expected) in vec![
("", None),
(">8.*", Some(Precision::Asterisk)),
(">+8.*", Some(Precision::Asterisk)),
("-.1$x", Some(Precision::Argument(1))),
("a^#043.8?", Some(Precision::Integer(8))),
] {
let (_, _, precision) = parse(input);
assert_eq!(precision, expected);
let (_, _, precision) = parser::parse_without_err(input);
assert_eq!(precision, expected);
}
}
}
| {
assert_eq!(integer("123"), Ok(("", 123)));
assert_eq!(integer("01"), Ok(("1", 0)));
assert_eq!(
integer("ab"),
Err(nom::Err::Error(("ab", ErrorKind::OneOf)))
);
} |
operations.rs | #![doc = "generated by AutoRust 0.1.0"]
#![allow(unused_mut)]
#![allow(unused_variables)]
#![allow(unused_imports)]
use crate::models::*;
pub mod marketplace_agreements {
use crate::models::*;
pub async fn get(
operation_config: &crate::OperationConfig,
subscription_id: &str,
offer_type: &str,
publisher_id: &str,
offer_id: &str,
plan_id: &str,
) -> std::result::Result<AgreementTerms, get::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.MarketplaceOrdering/offerTypes/{}/publishers/{}/offers/{}/plans/{}/agreements/current",
operation_config.base_path(),
subscription_id,
offer_type,
publisher_id,
offer_id,
plan_id
);
let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: AgreementTerms =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get {
use crate::{models, models::*};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn create(
operation_config: &crate::OperationConfig,
offer_type: &str,
subscription_id: &str,
publisher_id: &str,
offer_id: &str,
plan_id: &str,
parameters: &AgreementTerms,
) -> std::result::Result<AgreementTerms, create::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.MarketplaceOrdering/offerTypes/{}/publishers/{}/offers/{}/plans/{}/agreements/current",
operation_config.base_path(),
subscription_id,
offer_type,
publisher_id,
offer_id,
plan_id
);
let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::PUT);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(create::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = azure_core::to_json(parameters).map_err(create::Error::SerializeError)?;
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: AgreementTerms =
serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?;
Err(create::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod create {
use crate::{models, models::*};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn sign(
operation_config: &crate::OperationConfig,
subscription_id: &str,
publisher_id: &str,
offer_id: &str,
plan_id: &str,
) -> std::result::Result<OldAgreementTerms, sign::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.MarketplaceOrdering/agreements/{}/offers/{}/plans/{}/sign",
operation_config.base_path(),
subscription_id,
publisher_id,
offer_id,
plan_id
);
let mut url = url::Url::parse(url_str).map_err(sign::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(sign::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(sign::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(sign::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: OldAgreementTerms =
serde_json::from_slice(rsp_body).map_err(|source| sign::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| sign::Error::DeserializeError(source, rsp_body.clone()))?;
Err(sign::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod sign {
use crate::{models, models::*};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn cancel(
operation_config: &crate::OperationConfig,
subscription_id: &str,
publisher_id: &str,
offer_id: &str,
plan_id: &str,
) -> std::result::Result<OldAgreementTerms, cancel::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.MarketplaceOrdering/agreements/{}/offers/{}/plans/{}/cancel",
operation_config.base_path(),
subscription_id,
publisher_id,
offer_id,
plan_id
);
let mut url = url::Url::parse(url_str).map_err(cancel::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::POST);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(cancel::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(cancel::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(cancel::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: OldAgreementTerms =
serde_json::from_slice(rsp_body).map_err(|source| cancel::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| cancel::Error::DeserializeError(source, rsp_body.clone()))?;
Err(cancel::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod cancel {
use crate::{models, models::*};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn get_agreement(
operation_config: &crate::OperationConfig,
subscription_id: &str,
publisher_id: &str,
offer_id: &str,
plan_id: &str,
) -> std::result::Result<OldAgreementTerms, get_agreement::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.MarketplaceOrdering/agreements/{}/offers/{}/plans/{}",
operation_config.base_path(),
subscription_id,
publisher_id,
offer_id,
plan_id
);
let mut url = url::Url::parse(url_str).map_err(get_agreement::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() |
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(get_agreement::Error::BuildRequestError)?;
let rsp = http_client
.execute_request(req)
.await
.map_err(get_agreement::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: OldAgreementTerms =
serde_json::from_slice(rsp_body).map_err(|source| get_agreement::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| get_agreement::Error::DeserializeError(source, rsp_body.clone()))?;
Err(get_agreement::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod get_agreement {
use crate::{models, models::*};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
pub async fn list(
operation_config: &crate::OperationConfig,
subscription_id: &str,
) -> std::result::Result<AgreementTermsList, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/subscriptions/{}/providers/Microsoft.MarketplaceOrdering/agreements",
operation_config.base_path(),
subscription_id
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: AgreementTermsList =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use crate::{models, models::*};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
pub mod operations {
use crate::models::*;
pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationListResult, list::Error> {
let http_client = operation_config.http_client();
let url_str = &format!(
"{}/providers/Microsoft.MarketplaceOrdering/operations",
operation_config.base_path(),
);
let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?;
let mut req_builder = http::request::Builder::new();
req_builder = req_builder.method(http::Method::GET);
if let Some(token_credential) = operation_config.token_credential() {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(list::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
}
url.query_pairs_mut().append_pair("api-version", operation_config.api_version());
let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY);
req_builder = req_builder.uri(url.as_str());
let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?;
let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?;
match rsp.status() {
http::StatusCode::OK => {
let rsp_body = rsp.body();
let rsp_value: OperationListResult =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Ok(rsp_value)
}
status_code => {
let rsp_body = rsp.body();
let rsp_value: ErrorResponse =
serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?;
Err(list::Error::DefaultResponse {
status_code,
value: rsp_value,
})
}
}
}
pub mod list {
use crate::{models, models::*};
#[derive(Debug, thiserror :: Error)]
pub enum Error {
#[error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {0}")]
ParseUrlError(url::ParseError),
#[error("Failed to build request: {0}")]
BuildRequestError(http::Error),
#[error("Failed to execute request: {0}")]
ExecuteRequestError(azure_core::HttpError),
#[error("Failed to serialize request body: {0}")]
SerializeError(serde_json::Error),
#[error("Failed to deserialize response: {0}, body: {1:?}")]
DeserializeError(serde_json::Error, bytes::Bytes),
#[error("Failed to get access token: {0}")]
GetTokenError(azure_core::Error),
}
}
}
| {
let token_response = token_credential
.get_token(operation_config.token_credential_resource())
.await
.map_err(get_agreement::Error::GetTokenError)?;
req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret()));
} |
session.go | package testing
import (
"bytes"
"context"
"sort"
"testing"
"time"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
platform "github.com/influxdata/influxdb"
"github.com/influxdata/influxdb/mock"
)
const (
sessionOneID = "020f755c3c082000"
sessionTwoID = "020f755c3c082001"
)
var sessionCmpOptions = cmp.Options{
cmp.Comparer(func(x, y []byte) bool {
return bytes.Equal(x, y)
}),
cmp.Transformer("Sort", func(in []*platform.Session) []*platform.Session {
out := append([]*platform.Session(nil), in...) // Copy input to avoid mutating it
sort.Slice(out, func(i, j int) bool {
return out[i].ID.String() > out[j].ID.String()
})
return out
}),
cmpopts.IgnoreFields(platform.Session{}, "CreatedAt", "ExpiresAt", "Permissions"),
cmpopts.EquateEmpty(),
}
// SessionFields will include the IDGenerator, TokenGenerator, Sessions, and Users
type SessionFields struct {
IDGenerator platform.IDGenerator
TokenGenerator platform.TokenGenerator
Sessions []*platform.Session
Users []*platform.User
}
type sessionServiceFunc func(
init func(SessionFields, *testing.T) (platform.SessionService, string, func()),
t *testing.T,
)
// SessionService tests all the service functions.
func SessionService(
init func(SessionFields, *testing.T) (platform.SessionService, string, func()), t *testing.T,
) |
// CreateSession testing
func CreateSession(
init func(SessionFields, *testing.T) (platform.SessionService, string, func()),
t *testing.T,
) {
type args struct {
user string
}
type wants struct {
err error
session *platform.Session
}
tests := []struct {
name string
fields SessionFields
args args
wants wants
}{
{
name: "create sessions with empty set",
fields: SessionFields{
IDGenerator: mock.NewIDGenerator(sessionTwoID, t),
TokenGenerator: mock.NewTokenGenerator("abc123xyz", nil),
Users: []*platform.User{
{
ID: MustIDBase16(sessionOneID),
Name: "user1",
},
},
},
args: args{
user: "user1",
},
wants: wants{
session: &platform.Session{
ID: MustIDBase16(sessionTwoID),
UserID: MustIDBase16(sessionOneID),
Key: "abc123xyz",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, opPrefix, done := init(tt.fields, t)
defer done()
ctx := context.Background()
session, err := s.CreateSession(ctx, tt.args.user)
diffPlatformErrors(tt.name, err, tt.wants.err, opPrefix, t)
if diff := cmp.Diff(session, tt.wants.session, sessionCmpOptions...); diff != "" {
t.Errorf("sessions are different -got/+want\ndiff %s", diff)
}
})
}
}
// FindSession testing
func FindSession(
init func(SessionFields, *testing.T) (platform.SessionService, string, func()),
t *testing.T,
) {
type args struct {
key string
}
type wants struct {
err error
session *platform.Session
}
tests := []struct {
name string
fields SessionFields
args args
wants wants
}{
{
name: "basic find session",
fields: SessionFields{
IDGenerator: mock.NewIDGenerator(sessionTwoID, t),
TokenGenerator: mock.NewTokenGenerator("abc123xyz", nil),
Sessions: []*platform.Session{
{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC),
},
},
},
args: args{
key: "abc123xyz",
},
wants: wants{
session: &platform.Session{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC),
},
},
},
{
name: "look for not existing session",
args: args{
key: "abc123xyz",
},
wants: wants{
err: &platform.Error{
Code: platform.ENotFound,
Op: platform.OpFindSession,
Msg: platform.ErrSessionNotFound,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, opPrefix, done := init(tt.fields, t)
defer done()
ctx := context.Background()
session, err := s.FindSession(ctx, tt.args.key)
diffPlatformErrors(tt.name, err, tt.wants.err, opPrefix, t)
if diff := cmp.Diff(session, tt.wants.session, sessionCmpOptions...); diff != "" {
t.Errorf("session is different -got/+want\ndiff %s", diff)
}
})
}
}
// ExpireSession testing
func ExpireSession(
init func(SessionFields, *testing.T) (platform.SessionService, string, func()),
t *testing.T,
) {
type args struct {
key string
}
type wants struct {
err error
session *platform.Session
}
tests := []struct {
name string
fields SessionFields
args args
wants wants
}{
{
name: "basic find session",
fields: SessionFields{
IDGenerator: mock.NewIDGenerator(sessionTwoID, t),
TokenGenerator: mock.NewTokenGenerator("abc123xyz", nil),
Sessions: []*platform.Session{
{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC),
},
},
},
args: args{
key: "abc123xyz",
},
wants: wants{
session: &platform.Session{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, opPrefix, done := init(tt.fields, t)
defer done()
ctx := context.Background()
err := s.ExpireSession(ctx, tt.args.key)
diffPlatformErrors(tt.name, err, tt.wants.err, opPrefix, t)
session, err := s.FindSession(ctx, tt.args.key)
if err == nil {
t.Errorf("expected session to be expired got %v", err)
}
if diff := cmp.Diff(session, tt.wants.session, sessionCmpOptions...); diff != "" {
t.Errorf("session is different -got/+want\ndiff %s", diff)
}
})
}
}
// RenewSession testing
func RenewSession(
init func(SessionFields, *testing.T) (platform.SessionService, string, func()),
t *testing.T,
) {
type args struct {
session *platform.Session
key string
expireAt time.Time
}
type wants struct {
err error
session *platform.Session
}
tests := []struct {
name string
fields SessionFields
args args
wants wants
}{
{
name: "basic renew session",
fields: SessionFields{
IDGenerator: mock.NewIDGenerator(sessionTwoID, t),
TokenGenerator: mock.NewTokenGenerator("abc123xyz", nil),
Sessions: []*platform.Session{
{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC),
},
},
},
args: args{
session: &platform.Session{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC),
},
key: "abc123xyz",
expireAt: time.Date(2031, 9, 26, 0, 0, 10, 0, time.UTC),
},
wants: wants{
session: &platform.Session{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2031, 9, 26, 0, 0, 10, 0, time.UTC),
},
},
},
{
name: "renew nil session",
fields: SessionFields{
IDGenerator: mock.NewIDGenerator(sessionTwoID, t),
TokenGenerator: mock.NewTokenGenerator("abc123xyz", nil),
Sessions: []*platform.Session{
{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2030, 9, 26, 0, 0, 0, 0, time.UTC),
},
},
},
args: args{
key: "abc123xyz",
expireAt: time.Date(2031, 9, 26, 0, 0, 10, 0, time.UTC),
},
wants: wants{
err: &platform.Error{
Code: platform.EInternal,
Msg: "session is nil",
Op: platform.OpRenewSession,
},
session: &platform.Session{
ID: MustIDBase16(sessionOneID),
UserID: MustIDBase16(sessionTwoID),
Key: "abc123xyz",
ExpiresAt: time.Date(2031, 9, 26, 0, 0, 10, 0, time.UTC),
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, opPrefix, done := init(tt.fields, t)
defer done()
ctx := context.Background()
err := s.RenewSession(ctx, tt.args.session, tt.args.expireAt)
diffPlatformErrors(tt.name, err, tt.wants.err, opPrefix, t)
session, err := s.FindSession(ctx, tt.args.key)
if err != nil {
t.Errorf("err in find session %v", err)
}
if diff := cmp.Diff(session, tt.wants.session, sessionCmpOptions...); diff != "" {
t.Errorf("session is different -got/+want\ndiff %s", diff)
}
})
}
}
| {
tests := []struct {
name string
fn sessionServiceFunc
}{
{
name: "CreateSession",
fn: CreateSession,
},
{
name: "FindSession",
fn: FindSession,
},
{
name: "ExpireSession",
fn: ExpireSession,
},
{
name: "RenewSession",
fn: RenewSession,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.fn(init, t)
})
}
} |
ICELinkSlotManager.ts | /**
* Copyright (c) 2022 大漠穷秋.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import bigZIndexNum from '../../consts/BIG_ZINDEX_NUMBER';
import ICE_EVENT_NAME_CONSTS from '../../consts/ICE_EVENT_NAME_CONSTS';
import ICEEvent from '../../event/ICEEvent';
import ICEBoundingBox from '../../geometry/ICEBoundingBox';
import ICE from '../../ICE';
import ICEComponent from '../ICEComponent';
import ICELinkSlot from './ICELinkSlot';
import ICEPolyLine from './ICEPolyLine';
/**
* @class ICELinkSlotManager
*
* - ICELinkSlotManager 连接插槽管理器,用于管理连接插槽,共4个,所有可连接的组件都复用这4个插槽的实例。
* - ICELinkSlotManager 的实例是在 ICE 初始化时创建的。
* - ICELinkSlotManager 是全局单例,同一个 ICE 实例上只能有一个 ICELinkSlotManager 实例。
*
* @see ICE
* @author 大漠穷秋<[email protected]>
*/
export default class ICELinkSlotManager {
private slotRadius = 10;
private ice: ICE;
private collision: ICEComponent; //用来缓存鼠标移动过程中碰撞到的组件,鼠标弹起之后会清空
constructor(ice: ICE) {
| ;
}
start() {
this.createLinkSlots();
this.ice.evtBus.on(ICE_EVENT_NAME_CONSTS.HOOK_MOUSEMOVE, this.hookMouseMoveHandler, this);
this.ice.evtBus.on(ICE_EVENT_NAME_CONSTS.HOOK_MOUSEUP, this.hookMouseUpHandler, this);
this.ice.evtBus.on('mouseup', this.globalMouseUpHandler, this);
return this;
}
stop() {
this.ice.evtBus.off(ICE_EVENT_NAME_CONSTS.HOOK_MOUSEMOVE, this.hookMouseMoveHandler, this);
this.ice.evtBus.off(ICE_EVENT_NAME_CONSTS.HOOK_MOUSEUP, this.hookMouseUpHandler, this);
this.ice.evtBus.off('mouseup', this.globalMouseUpHandler, this);
return this;
}
private hookMouseMoveHandler(evt: ICEEvent) {
let linkHook = evt.target as any;
let hookBounding: ICEBoundingBox = linkHook.getMaxBoundingBox();
//连接钩子是否碰到了某个可连接组件的边缘
// let collision = null;
const childNodes = [...this.ice.childNodes];
for (let i = 0; i < childNodes.length; i++) {
const component = childNodes[i];
if (!component || !component.state.linkable) {
continue;
}
let componentBounding: ICEBoundingBox = component.getMaxBoundingBox();
if (componentBounding.isIntersect(hookBounding)) {
this.collision = component;
break;
}
}
if (!this.collision) {
//@ts-ignore
for (let i = 0; i < this.ice._linkSlots.length; i++) {
//@ts-ignore
let slot = this.ice._linkSlots[i];
slot.setState({
display: false,
style: {
fillStyle: '#3ce92c',
},
});
}
linkHook.setState({
style: {
fillStyle: '#3ce92c',
},
});
return;
}
let isIntersect = false;
//@ts-ignore
for (let i = 0; i < this.ice._linkSlots.length; i++) {
//@ts-ignore
let slot = this.ice._linkSlots[i];
if (slot.hostComponent !== this.collision) {
slot.hostComponent = this.collision;
}
slot.setState({
display: true,
style: {
fillStyle: '#3ce92c',
},
});
linkHook.setState({
style: {
fillStyle: '#3ce92c',
},
});
//判断连接钩子是否碰到了某个 linkSlot
let slotBox: ICEBoundingBox = slot.getMaxBoundingBox();
if (slotBox.isIntersect(hookBounding)) {
isIntersect = true;
slot.setState({
style: {
fillStyle: '#fffb00',
},
});
}
}
if (isIntersect) {
linkHook.setState({
style: {
fillStyle: '#fffb00',
},
});
}
}
private hookMouseUpHandler(evt: ICEEvent) {
let linkHook = evt.target as any;
let position: string = linkHook.state.position;
let linkLine: ICEPolyLine = linkHook.parentNode.targetComponent;
let hookBounding: ICEBoundingBox = linkHook.getMaxBoundingBox();
let isIntersect = false;
if (this.collision) {
//@ts-ignore
for (let i = 0; i < this.ice._linkSlots.length; i++) {
//@ts-ignore
let slot = this.ice._linkSlots[i];
slot.setState({
display: false,
style: {
fillStyle: '#3ce92c',
},
});
//判断连接钩子是否碰到了某个 linkSlot
let slotBox: ICEBoundingBox = slot.getMaxBoundingBox();
if (slotBox.isIntersect(hookBounding)) {
isIntersect = true;
//建立连接关系
let param = {};
param[position] = {
id: slot.hostComponent.state.id,
position: slot.state.position,
};
linkLine && linkLine.setState({ links: param });
break;
}
}
}
//如果钩子与所有插槽都没有发生碰撞,则删掉对应线条上的连接关系
if (!isIntersect) {
let param = {};
param[position] = null;
linkLine && linkLine.setState({ links: param });
} else {
linkHook.setState({
display: false,
style: {
fillStyle: '#3ce92c',
},
});
}
this.collision = null;
}
protected globalMouseUpHandler(evt?: ICEEvent) {
//@ts-ignore
for (let i = 0; i < this.ice._linkSlots.length; i++) {
//@ts-ignore
let slot = this.ice._linkSlots[i];
slot.setState({
display: false,
style: {
fillStyle: '#3ce92c',
},
});
}
}
/**
* @method createLinkSlots
* 创建5个连接插槽,插槽默认分布在组件最小边界盒子的4条边中点和几何中心点。
*/
protected createLinkSlots() {
//@ts-ignore
if (this.ice._linkSlots && this.ice._linkSlots.length) {
return;
}
let slot_1 = new ICELinkSlot({
zIndex: bigZIndexNum + 10,
display: false,
transformable: false,
draggable: false,
radius: this.slotRadius,
position: 'T',
style: {
strokeStyle: '#0c09d4',
fillStyle: '#3ce92c',
lineWidth: 1,
},
});
this.ice.addTool(slot_1);
let slot_2 = new ICELinkSlot({
zIndex: bigZIndexNum + 11,
display: false,
transformable: false,
draggable: false,
radius: this.slotRadius,
position: 'R',
style: {
strokeStyle: '#0c09d4',
fillStyle: '#3ce92c',
lineWidth: 1,
},
});
this.ice.addTool(slot_2);
let slot_3 = new ICELinkSlot({
zIndex: bigZIndexNum + 12,
display: false,
transformable: false,
draggable: false,
radius: this.slotRadius,
position: 'B',
style: {
strokeStyle: '#0c09d4',
fillStyle: '#3ce92c',
lineWidth: 1,
},
});
this.ice.addTool(slot_3);
let slot_4 = new ICELinkSlot({
zIndex: bigZIndexNum + 13,
display: false,
transformable: false,
draggable: false,
radius: this.slotRadius,
position: 'L',
style: {
strokeStyle: '#0c09d4',
fillStyle: '#3ce92c',
lineWidth: 1,
},
});
this.ice.addTool(slot_4);
let slot_5 = new ICELinkSlot({
zIndex: bigZIndexNum + 14,
display: false,
transformable: false,
draggable: false,
radius: this.slotRadius,
position: 'C',
style: {
strokeStyle: '#0c09d4',
fillStyle: '#3ce92c',
lineWidth: 1,
},
});
this.ice.addTool(slot_5);
//缓存一份,方便操作
//@ts-ignore
this.ice._linkSlots = [slot_1, slot_2, slot_3, slot_4, slot_5];
}
}
| this.ice = ice |
test_nw_flow_log.py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from azure.cli.testsdk import (ScenarioTest, ResourceGroupPreparer, StorageAccountPreparer)
class NWFlowLogScenarioTest(ScenarioTest):
@ResourceGroupPreparer(name_prefix='test_nw_flow_log_', location='eastus')
@StorageAccountPreparer(name_prefix='testflowlog', location='eastus', kind='StorageV2')
def test_nw_flow_log_create(self, resource_group, resource_group_location, storage_account):
self.kwargs.update({
'rg': resource_group,
'location': resource_group_location,
'storage_account': storage_account,
'nsg': 'nsg1',
'watcher_rg': 'NetworkWatcherRG',
'watcher_name': 'NetworkWatcher_{}'.format(resource_group_location),
'flow_log': 'flow_log_test',
'workspace': self.create_random_name('clitest', 20),
})
# enable network watcher
# self.cmd('network watcher configure -g {rg} --locations {location} --enabled')
# prepare the target resource | # prepare workspace
workspace = self.cmd('monitor log-analytics workspace create '
'--resource-group {rg} '
'--location {location} '
'--workspace-name {workspace} ').get_output_in_json()
self.kwargs.update({
'workspace_id': workspace['id']
})
self.cmd('network watcher flow-log create '
'--location {location} '
'--resource-group {rg} '
'--nsg {nsg} '
'--storage-account {storage_account} '
'--workspace {workspace_id} '
'--name {flow_log} ')
self.cmd('network watcher flow-log list --location {location}')
# This output is Azure Management Resource formatted.
self.cmd('network watcher flow-log show --location {location} --name {flow_log}', checks=[
self.check('name', self.kwargs['flow_log']),
self.check('flowAnalyticsConfiguration.networkWatcherFlowAnalyticsConfiguration.enabled', False),
self.check('flowAnalyticsConfiguration.networkWatcherFlowAnalyticsConfiguration.workspaceResourceId',
self.kwargs['workspace_id']),
self.check('retentionPolicy.days', 0),
self.check('retentionPolicy.enabled', False),
])
@ResourceGroupPreparer(name_prefix='test_nw_flow_log_', location='westus')
@StorageAccountPreparer(name_prefix='testflowlog', location='westus', kind='StorageV2')
def test_nw_flow_log_delete(self, resource_group, resource_group_location, storage_account):
self.kwargs.update({
'rg': resource_group,
'location': resource_group_location,
'storage_account': storage_account,
'nsg': 'nsg1',
'watcher_rg': 'NetworkWatcherRG',
'watcher_name': 'NetworkWatcher_{}'.format(resource_group_location),
'flow_log': 'flow_log_test2',
'workspace': self.create_random_name('clitest', 20),
})
# enable network watcher
# self.cmd('network watcher configure -g {rg} --locations {location} --enabled')
# prepare the target resource
self.cmd('network nsg create -g {rg} -n {nsg}')
# prepare workspace
workspace = self.cmd('monitor log-analytics workspace create '
'--resource-group {rg} '
'--location {location} '
'--workspace-name {workspace} ').get_output_in_json()
self.kwargs.update({
'workspace_id': workspace['id']
})
self.cmd('network watcher flow-log create '
'--location {location} '
'--resource-group {rg} '
'--nsg {nsg} '
'--storage-account {storage_account} '
'--workspace {workspace_id} '
'--name {flow_log} ')
self.cmd('network watcher flow-log show --location {location} --name {flow_log}')
self.cmd('network watcher flow-log delete --location {location} --name {flow_log}')
with self.assertRaisesRegexp(SystemExit, '3'):
self.cmd('network watcher flow-log show --location {location} --name {flow_log}')
@ResourceGroupPreparer(name_prefix='test_nw_flow_log_', location='westus')
@StorageAccountPreparer(name_prefix='testflowlog', location='westus', kind='StorageV2')
def test_nw_flow_log_show(self, resource_group, resource_group_location, storage_account):
"""
This test is used to demonstrate different outputs between the new and deprecating parameters
:param resource_group:
:param resource_group_location:
:param storage_account:
:return:
"""
self.kwargs.update({
'rg': resource_group,
'location': resource_group_location,
'storage_account': storage_account,
'nsg': 'nsg1',
'watcher_rg': 'NetworkWatcherRG',
'watcher_name': 'NetworkWatcher_{}'.format(resource_group_location),
'flow_log': 'flow_log_test2',
'workspace': self.create_random_name('clitest', 20),
})
# enable network watcher
# self.cmd('network watcher configure -g {rg} --locations {location} --enabled')
# prepare the target resource
nsg_info = self.cmd('network nsg create -g {rg} -n {nsg}').get_output_in_json()
self.kwargs.update({
'nsg_id': nsg_info['NewNSG']['id']
})
# prepare workspace
workspace = self.cmd('monitor log-analytics workspace create '
'--resource-group {rg} '
'--location {location} '
'--workspace-name {workspace} ').get_output_in_json()
self.kwargs.update({
'workspace_id': workspace['id']
})
self.cmd('network watcher flow-log create '
'--location {location} '
'--resource-group {rg} '
'--nsg {nsg} '
'--storage-account {storage_account} '
'--workspace {workspace_id} '
'--name {flow_log} ')
# This output is new Azure Management Resource formatted.
self.cmd('network watcher flow-log show --location {location} --name {flow_log}', checks=[
self.check('name', self.kwargs['flow_log']),
self.check('enabled', True),
self.check('format.type', 'JSON'),
self.check('format.version', 1),
self.check('flowAnalyticsConfiguration.networkWatcherFlowAnalyticsConfiguration.enabled', False),
self.check('flowAnalyticsConfiguration.networkWatcherFlowAnalyticsConfiguration.workspaceResourceId',
self.kwargs['workspace_id']),
self.check('retentionPolicy.days', 0),
self.check('retentionPolicy.enabled', False),
])
# This output is deprecating
self.cmd('network watcher flow-log show --nsg {nsg_id}', checks=[
self.check('enabled', True),
self.check('format.type', 'JSON'),
self.check('format.version', 1),
self.check('flowAnalyticsConfiguration.networkWatcherFlowAnalyticsConfiguration.enabled', False),
self.check('flowAnalyticsConfiguration.networkWatcherFlowAnalyticsConfiguration.workspaceResourceId',
self.kwargs['workspace_id']),
self.check('retentionPolicy.days', 0),
self.check('retentionPolicy.enabled', False)
])
@ResourceGroupPreparer(name_prefix='test_nw_flow_log_', location='eastus')
@StorageAccountPreparer(name_prefix='testflowlog', location='eastus', kind='StorageV2')
def test_nw_flow_log_update(self, resource_group, resource_group_location, storage_account):
self.kwargs.update({
'rg': resource_group,
'location': resource_group_location,
'storage_account': storage_account,
'storage_account_2': 'storageaccount0395',
'nsg': 'nsg1',
'watcher_rg': 'NetworkWatcherRG',
'watcher_name': 'NetworkWatcher_{}'.format(resource_group_location),
'flow_log': 'flow_log_test2',
'workspace': self.create_random_name('clitest', 20),
})
# enable network watcher
# self.cmd('network watcher configure -g {rg} --locations {location} --enabled')
# prepare the target resource
nsg_info = self.cmd('network nsg create -g {rg} -n {nsg}').get_output_in_json()
self.kwargs.update({
'nsg_id': nsg_info['NewNSG']['id']
})
# prepare another storage account in another resource group
storage_info = self.cmd('storage account create '
'--resource-group {rg} '
'--name {storage_account_2} --https-only').get_output_in_json()
self.kwargs.update({
'another_storage': storage_info['id']
})
# prepare workspace
workspace = self.cmd('monitor log-analytics workspace create '
'--resource-group {rg} '
'--location {location} '
'--workspace-name {workspace} ').get_output_in_json()
self.kwargs.update({
'workspace_id': workspace['id']
})
self.cmd('network watcher flow-log create '
'--location {location} '
'--resource-group {rg} '
'--nsg {nsg} '
'--storage-account {storage_account} '
'--workspace {workspace_id} '
'--name {flow_log} ')
res1 = self.cmd('network watcher flow-log show --location {location} --name {flow_log}').get_output_in_json()
self.assertEqual(res1['name'], self.kwargs['flow_log'])
self.assertEqual(res1['enabled'], True)
self.assertEqual(res1['retentionPolicy']['days'], 0)
self.assertEqual(res1['retentionPolicy']['enabled'], False)
self.assertTrue(res1['storageId'].endswith(self.kwargs['storage_account']))
self.assertIsNone(res1['tags'])
res2 = self.cmd('network watcher flow-log update '
'--location {location} '
'--name {flow_log} '
'--retention 2 '
'--storage-account {another_storage} '
'--tags foo=bar ').get_output_in_json()
self.assertEqual(res2['name'], self.kwargs['flow_log'])
self.assertEqual(res2['enabled'], True)
self.assertEqual(res2['retentionPolicy']['days'], 2)
self.assertEqual(res2['retentionPolicy']['enabled'], True)
self.assertTrue(res2['storageId'].endswith(self.kwargs['storage_account_2']))
self.assertIsNotNone(res2['tags']) | self.cmd('network nsg create -g {rg} -n {nsg}')
|
steg.py | #Image Stego using LSB
import cv2
def encode(input_image_name, output_image_name, file_name):
input_image = cv2.imread(input_image_name)
height, width, nbchannels = input_image.shape
size = width*height
current_width = 0
current_height = 0
current_channel = 0
maskonevalues = [1, 2, 4, 8, 16, 32, 64, 128]
maskone = maskonevalues.pop(0)
maskzerovalues = [254, 253, 251, 247, 239, 223, 191, 127]
maskzero = maskzerovalues.pop(0)
data = open(file_name, "rb").read()
length = len(data)
if(width*height*nbchannels < length + 64):
raise Exception("Not enough space to hold all steganographic data")
binary_value = bin(length)[2:]
if(len(binary_value) > 64):
raise Exception("Binary Value larger than expected")
else:
while(len(binary_value) < 64):
binary_value = "0" + binary_value
for c in binary_value:
value = list(input_image[current_height, current_width])
if(int(c) == 1):
value[current_channel] = int(value[current_channel]) | maskone
else:
value[current_channel] = int(value[current_channel]) & maskzero
input_image[current_height, current_width] = tuple(value)
if(current_channel == nbchannels-1):
current_channel = 0
if(current_width == width-1):
current_width = 0
if(current_height == height-1):
current_height = 0
if maskone == 128:
raise Exception("No more space available in image")
else:
maskone = maskonevalues.pop(0)
maskzero = maskzerovalues.pop(0)
else:
current_height += 1
else:
current_width += 1
else:
current_channel += 1
for byte in data:
if(isinstance(byte, int)):
pass
else:
byte = ord(byte)
binv = bin(byte)[2:]
if(len(binv) > 8):
raise Exception("Binary Value larger than expected")
else:
while(len(binv) < 8):
binv = "0" + binv
for c in binv:
val = list(input_image[current_height, current_width])
if(int(c) == 1):
val[current_channel] = int(val[current_channel]) | maskone
else:
val[current_channel] = int(val[current_channel]) & maskzero
input_image[current_height, current_width] = tuple(val)
if(current_channel == nbchannels-1):
current_channel = 0
if(current_width == width-1):
current_width = 0
if(current_height == height-1):
current_height = 0
if maskone == 128:
raise Exception("No more space available in image")
else:
maskone = maskonevalues.pop(0)
maskzero = maskzerovalues.pop(0)
else:
current_height += 1
else:
current_width += 1
else:
current_channel += 1
cv2.imwrite(output_image_name, input_image)
def decode(encoded_image_name, extracted_file_name):
encoded_image = cv2.imread(encoded_image_name)
height, width, nbchannels = encoded_image.shape
size = width*height
current_width = 0
current_height = 0
current_channel = 0
maskonevalues = [1, 2, 4, 8, 16, 32, 64, 128]
maskone = maskonevalues.pop(0)
maskzerovalues = [254, 253, 251, 247, 239, 223, 191, 127]
maskzero = maskzerovalues.pop(0)
bits = ""
for i in range(64):
value = encoded_image[current_height, current_width][current_channel]
value = int(value) & maskone
if(current_channel == nbchannels-1):
current_channel = 0
if(current_width == width-1):
current_width = 0
if(current_height == height-1):
current_height = 0
if(maskone == 128):
raise Exception("No more space available in image")
else:
maskone = maskonevalues.pop(0)
maskzero = maskzerovalues.pop(0)
else:
current_height += 1 | if(value > 0):
bits += "1"
else:
bits += "0"
length = int(bits, 2)
output = b""
for i in range(length):
bits = ""
for i in range(8):
value = encoded_image[current_height, current_width][current_channel]
value = int(value) & maskone
if(current_channel == nbchannels-1):
current_channel = 0
if(current_width == width-1):
current_width = 0
if(current_height == height-1):
current_height = 0
if(maskone == 128):
raise Exception("No more space available in image")
else:
maskone = maskonevalues.pop(0)
maskzero = maskzerovalues.pop(0)
else:
current_height += 1
else:
current_width += 1
else:
current_channel += 1
if(value > 0):
bits += "1"
else:
bits += "0"
output += bytearray([int(bits, 2)])
f = open(extracted_file_name, "wb")
f.write(output)
f.close()
if __name__ == "__main__":
input_string = input()
#encode input_image_name output_image_name file_name
#decode encoded_image_name extracted_file_name
input_list = input_string.split()
if input_list[0] == "encode":
encode(input_list[1], input_list[2], input_list[3])
print(f"{input_list[2]}")
elif input_list[0] == "decode":
decode(input_list[1], input_list[2])
print(f"{input_list[2]}")
else:
print("Invalid Entry") | else:
current_width += 1
else:
current_channel += 1 |
scripts_smoke_unittest.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import json
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from telemetry import decorators
from telemetry.testing import options_for_unittests
RUNNER_SCRIPTS_DIR = os.path.join(os.path.dirname(__file__),
'..', '..', 'testing', 'scripts')
sys.path.append(RUNNER_SCRIPTS_DIR)
import run_performance_tests # pylint: disable=wrong-import-position,import-error
class ScriptsSmokeTest(unittest.TestCase):
perf_dir = os.path.dirname(__file__)
def setUp(self):
self.options = options_for_unittests.GetCopy()
def RunPerfScript(self, args, env=None):
# TODO(crbug.com/985712): Switch all clients to pass a list of args rather
# than a string which we may not be parsing correctly.
if not isinstance(args, list):
args = args.split(' ')
proc = subprocess.Popen([sys.executable] + args, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, cwd=self.perf_dir,
env=env)
stdout = proc.communicate()[0]
return_code = proc.returncode
return return_code, stdout.decode('utf-8')
def testRunBenchmarkHelp(self):
return_code, stdout = self.RunPerfScript('run_benchmark --help')
self.assertEquals(return_code, 0, stdout)
self.assertIn('usage: run_benchmark', stdout)
@decorators.Disabled('chromeos') # crbug.com/754913
def testRunBenchmarkListBenchmarks(self):
cmdline = ['run_benchmark', 'list', '--browser', self.options.browser_type]
if self.options.browser_type == 'exact':
# If we're running with an exact browser and it was not specified with
# an absolute path, then there's no guarantee that we can actually find it
# now, so make the test a no-op.
if not os.path.isabs(self.options.browser_executable):
return
cmdline.extend(['--browser-executable', self.options.browser_executable])
return_code, stdout = self.RunPerfScript(cmdline)
self.assertRegexpMatches(stdout, r'Available benchmarks .*? are:')
self.assertEqual(return_code, 0)
def testRunBenchmarkRunListsOutBenchmarks(self):
return_code, stdout = self.RunPerfScript('run_benchmark run')
self.assertIn('Pass --browser to list benchmarks', stdout)
self.assertNotEquals(return_code, 0)
def testRunBenchmarkRunNonExistingBenchmark(self):
return_code, stdout = self.RunPerfScript('run_benchmark foo')
self.assertIn('no such benchmark: foo', stdout)
self.assertNotEquals(return_code, 0)
def testRunRecordWprHelp(self):
return_code, stdout = self.RunPerfScript('record_wpr')
self.assertEquals(return_code, 0, stdout)
self.assertIn('optional arguments:', stdout)
@decorators.Disabled('chromeos') # crbug.com/814068
def testRunRecordWprList(self):
return_code, stdout = self.RunPerfScript('record_wpr --list-benchmarks')
# TODO(nednguyen): Remove this once we figure out why importing
# small_profile_extender fails on Android dbg.
# crbug.com/561668
if 'ImportError: cannot import name small_profile_extender' in stdout:
self.skipTest('small_profile_extender is missing')
self.assertEquals(return_code, 0, stdout)
self.assertIn('kraken', stdout)
@decorators.Disabled('chromeos') # crbug.com/754913
def testRunPerformanceTestsTelemetry_end2end(self):
tempdir = tempfile.mkdtemp()
benchmarks = ['dummy_benchmark.stable_benchmark_1',
'dummy_benchmark.noisy_benchmark_1']
cmdline = ('../../testing/scripts/run_performance_tests.py '
'../../tools/perf/run_benchmark '
'--benchmarks=%s '
'--browser=%s '
'--isolated-script-test-also-run-disabled-tests '
'--isolated-script-test-output=%s' %
(','.join(benchmarks), self.options.browser_type,
os.path.join(tempdir, 'output.json')))
if self.options.browser_type == 'exact':
# If the path to the browser executable is not absolute, there is no
# guarantee that we can actually find it at this point, so no-op the
# test.
if not os.path.isabs(self.options.browser_executable):
return
cmdline += ' --browser-executable=%s' % self.options.browser_executable
return_code, stdout = self.RunPerfScript(cmdline)
self.assertEquals(return_code, 0, stdout)
try:
with open(os.path.join(tempdir, 'output.json')) as f:
test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json_test_results should be populated: ' + stdout)
benchmarks_run = [str(b) for b in test_results['tests'].keys()]
self.assertEqual(sorted(benchmarks_run), sorted(benchmarks))
story_runs = test_results['num_failures_by_type']['PASS']
self.assertEqual(
story_runs, 2,
'Total runs should be 2 since each benchmark has one story.')
for benchmark in benchmarks:
with open(os.path.join(tempdir, benchmark, 'test_results.json')) as f:
test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json_test_results should be populated: ' + stdout)
with open(os.path.join(tempdir, benchmark, 'perf_results.json')) as f:
perf_results = json.load(f)
self.assertIsNotNone(
perf_results, 'json perf results should be populated: ' + stdout)
except IOError as e:
self.fail('json_test_results should be populated: ' + stdout + str(e))
except AssertionError as e:
self.fail('Caught assertion error: ' + str(e) + 'With stdout: ' + stdout)
finally:
shutil.rmtree(tempdir)
@decorators.Enabled('linux') # Testing platform-independent code.
def testRunPerformanceTestsTelemetry_NoTestResults(self):
"""Test that test results output gets returned for complete failures."""
tempdir = tempfile.mkdtemp()
benchmarks = ['benchmark1', 'benchmark2']
return_code, stdout = self.RunPerfScript(
'../../testing/scripts/run_performance_tests.py '
'../../tools/perf/testdata/fail_and_do_nothing '
'--benchmarks=%s '
'--browser=%s '
'--isolated-script-test-output=%s' % (
','.join(benchmarks),
self.options.browser_type,
os.path.join(tempdir, 'output.json')
))
self.assertNotEqual(return_code, 0)
try:
with open(os.path.join(tempdir, 'output.json')) as f:
test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json_test_results should be populated: ' + stdout)
self.assertTrue(
test_results['interrupted'],
'if the benchmark does not populate test results, then we should '
'populate it with a failure.')
for benchmark in benchmarks:
with open(os.path.join(tempdir, benchmark, 'test_results.json')) as f:
test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json_test_results should be populated: ' + stdout)
self.assertTrue(
test_results['interrupted'],
'if the benchmark does not populate test results, then we should '
'populate it with a failure.')
except IOError as e:
self.fail('json_test_results should be populated: ' + stdout + str(e))
finally:
shutil.rmtree(tempdir)
# Android: crbug.com/932301
# ChromeOS: crbug.com/754913
# Windows: crbug.com/1024767
# Linux: crbug.com/1024767
# all: Disabled everywhere because the smoke test shard map
# needed to be changed to fix crbug.com/1024767.
@decorators.Disabled('all')
def testRunPerformanceTestsTelemetrySharded_end2end(self):
tempdir = tempfile.mkdtemp()
env = os.environ.copy()
env['GTEST_SHARD_INDEX'] = '0'
env['GTEST_TOTAL_SHARDS'] = '2'
return_code, stdout = self.RunPerfScript(
'../../testing/scripts/run_performance_tests.py '
'../../tools/perf/run_benchmark '
'--test-shard-map-filename=smoke_test_benchmark_shard_map.json '
'--browser=%s '
'--run-ref-build '
'--isolated-script-test-filter=dummy_benchmark.noisy_benchmark_1/'
'dummy_page.html::dummy_benchmark.stable_benchmark_1/dummy_page.html '
'--isolated-script-test-repeat=2 '
'--isolated-script-test-also-run-disabled-tests '
'--isolated-script-test-output=%s' % (
self.options.browser_type,
os.path.join(tempdir, 'output.json')
), env=env)
test_results = None
try:
self.assertEquals(return_code, 0)
expected_benchmark_folders = (
'dummy_benchmark.stable_benchmark_1',
'dummy_benchmark.stable_benchmark_1.reference',
'dummy_gtest')
with open(os.path.join(tempdir, 'output.json')) as f:
test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json_test_results should be populated.')
test_runs = test_results['num_failures_by_type']['PASS']
# 1 gtest runs (since --isolated-script-test-repeat doesn't work for gtest
# yet) plus 2 dummy_benchmark runs = 3 runs.
self.assertEqual(
test_runs, 3, '--isolated-script-test-repeat=2 should work.')
for folder in expected_benchmark_folders: | test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json test results should be populated.')
test_repeats = test_results['num_failures_by_type']['PASS']
if 'dummy_gtest' not in folder: # Repeats don't work for gtest yet.
self.assertEqual(
test_repeats, 2, '--isolated-script-test-repeat=2 should work.')
with open(os.path.join(tempdir, folder, 'perf_results.json')) as f:
perf_results = json.load(f)
self.assertIsNotNone(
perf_results, 'json perf results should be populated.')
except Exception as exc:
logging.error(
'Failed with error: %s\nOutput from run_performance_tests.py:\n\n%s',
exc, stdout)
if test_results is not None:
logging.error(
'Got test_results: %s\n', json.dumps(test_results, indent=2))
raise
finally:
shutil.rmtree(tempdir)
def RunGtest(self, generate_trace):
tempdir = tempfile.mkdtemp()
benchmark = 'dummy_gtest'
return_code, stdout = self.RunPerfScript(
'../../testing/scripts/run_performance_tests.py ' +
('../../tools/perf/run_gtest_benchmark.py ' if generate_trace else '') +
os.path.join('..', '..', 'tools', 'perf', 'testdata',
'dummy_gtest') +
(' --use-gtest-benchmark-script --output-format=histograms'
if generate_trace else '') +
' --non-telemetry=true '
'--this-arg=passthrough '
'--argument-to-check-that-arguments-work '
'--gtest-benchmark-name dummy_gtest '
'--isolated-script-test-output=%s' % (
os.path.join(tempdir, 'output.json')
))
try:
self.assertEquals(return_code, 0, stdout)
except AssertionError:
try:
with open(os.path.join(tempdir, benchmark, 'benchmark_log.txt')) as fh:
print(fh.read())
# pylint: disable=bare-except
except:
# pylint: enable=bare-except
pass
raise
try:
with open(os.path.join(tempdir, 'output.json')) as f:
test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json_test_results should be populated: ' + stdout)
with open(os.path.join(tempdir, benchmark, 'test_results.json')) as f:
test_results = json.load(f)
self.assertIsNotNone(
test_results, 'json_test_results should be populated: ' + stdout)
with open(os.path.join(tempdir, benchmark, 'perf_results.json')) as f:
perf_results = json.load(f)
self.assertIsNotNone(
perf_results, 'json perf results should be populated: ' + stdout)
except IOError as e:
self.fail('json_test_results should be populated: ' + stdout + str(e))
finally:
shutil.rmtree(tempdir)
# Windows: ".exe" is auto-added which breaks Windows.
# ChromeOS: crbug.com/754913.
@decorators.Disabled('win', 'chromeos')
def testRunPerformanceTestsGtest_end2end(self):
self.RunGtest(generate_trace=False)
# Windows: ".exe" is auto-added which breaks Windows.
# ChromeOS: crbug.com/754913.
@decorators.Disabled('win', 'chromeos')
def testRunPerformanceTestsGtestTrace_end2end(self):
self.RunGtest(generate_trace=True)
def testRunPerformanceTestsShardedArgsParser(self):
options = run_performance_tests.parse_arguments([
'../../tools/perf/run_benchmark', '-v', '--browser=release_x64',
'--upload-results', '--run-ref-build',
'--test-shard-map-filename=win-10-perf_map.json',
'--assert-gpu-compositing',
r'--isolated-script-test-output=c:\a\b\c\output.json',
r'--isolated-script-test-perf-output=c:\a\b\c\perftest-output.json',
'--passthrough-arg=--a=b',
])
self.assertIn('--assert-gpu-compositing', options.passthrough_args)
self.assertIn('--browser=release_x64', options.passthrough_args)
self.assertIn('-v', options.passthrough_args)
self.assertIn('--a=b', options.passthrough_args)
self.assertEqual(options.executable, '../../tools/perf/run_benchmark')
self.assertEqual(options.isolated_script_test_output,
r'c:\a\b\c\output.json')
def testRunPerformanceTestsTelemetryCommandGenerator_ReferenceBrowserComeLast(self):
"""This tests for crbug.com/928928."""
options = run_performance_tests.parse_arguments([
'../../tools/perf/run_benchmark', '--browser=release_x64',
'--run-ref-build',
'--test-shard-map-filename=win-10-perf_map.json',
r'--isolated-script-test-output=c:\a\b\c\output.json',
])
self.assertIn('--browser=release_x64', options.passthrough_args)
command = run_performance_tests.TelemetryCommandGenerator(
'fake_benchmark_name', options, is_reference=True).generate(
'fake_output_dir')
original_browser_arg_index = command.index('--browser=release_x64')
reference_browser_arg_index = command.index('--browser=reference')
self.assertTrue(reference_browser_arg_index > original_browser_arg_index)
def testRunPerformanceTestsTelemetryCommandGenerator_StorySelectionConfig_Unabridged(self):
options = run_performance_tests.parse_arguments([
'../../tools/perf/run_benchmark', '--browser=release_x64',
'--run-ref-build',
r'--isolated-script-test-output=c:\a\b\c\output.json',
])
story_selection_config = {
'abridged': False,
'begin': 1,
'end': 5,
}
command = run_performance_tests.TelemetryCommandGenerator(
'fake_benchmark_name', options, story_selection_config).generate(
'fake_output_dir')
self.assertNotIn('--run-abridged-story-set', command)
self.assertIn('--story-shard-begin-index=1', command)
self.assertIn('--story-shard-end-index=5', command)
def testRunPerformanceTestsTelemetryCommandGenerator_StorySelectionConfig_Abridged(self):
options = run_performance_tests.parse_arguments([
'../../tools/perf/run_benchmark', '--browser=release_x64',
'--run-ref-build',
r'--isolated-script-test-output=c:\a\b\c\output.json',
])
story_selection_config = {
'abridged': True,
}
command = run_performance_tests.TelemetryCommandGenerator(
'fake_benchmark_name', options, story_selection_config).generate(
'fake_output_dir')
self.assertIn('--run-abridged-story-set', command)
def testRunPerformanceTestsGtestArgsParser(self):
options = run_performance_tests.parse_arguments([
'media_perftests',
'--non-telemetry=true',
'--single-process-tests',
'--test-launcher-retry-limit=0',
'--isolated-script-test-filter=*::-*_unoptimized::*_unaligned::'
'*unoptimized_aligned',
'--gtest-benchmark-name',
'media_perftests',
'--isolated-script-test-output=/x/y/z/output.json',
])
self.assertIn('--single-process-tests', options.passthrough_args)
self.assertIn('--test-launcher-retry-limit=0', options.passthrough_args)
self.assertEqual(options.executable, 'media_perftests')
self.assertEqual(options.isolated_script_test_output, r'/x/y/z/output.json')
def testRunPerformanceTestsExecuteGtest_OSError(self):
class FakeCommandGenerator(object):
def __init__(self):
self.executable_name = 'binary_that_doesnt_exist'
self._ignore_shard_env_vars = False
def generate(self, unused_path):
return [self.executable_name]
tempdir = tempfile.mkdtemp()
try:
fake_command_generator = FakeCommandGenerator()
output_paths = run_performance_tests.OutputFilePaths(
tempdir, 'fake_gtest')
output_paths.SetUp()
return_code = run_performance_tests.execute_gtest_perf_test(
fake_command_generator, output_paths, is_unittest=True)
self.assertEqual(return_code, 1)
with open(output_paths.test_results) as fh:
json_test_results = json.load(fh)
self.assertGreater(json_test_results['num_failures_by_type']['FAIL'], 0)
finally:
shutil.rmtree(tempdir) | with open(os.path.join(tempdir, folder, 'test_results.json')) as f: |
single.min.js | webpackJsonp([2],{"+1qq":function(t,e,n){var r=n("VU/8")(n("I8eF"),n("sklR"),!1,null,null,null);t.exports=r.exports},"/DOn":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("+1qq"),i=n.n(r),o=n("fhbW");e.default={components:{commentBox:i.a},props:{discussionDetailsShown:{required:!0,type:Boolean},discussion:{required:!0,type:Object},index:{required:!0}},data:function(){return{dropdownMenuShown:!1,faArrowLeft:o.b,faEllipsisH:o.l}},methods:{closeDiscussionDetails:function(){this.dropdownMenuShown=!1,this.$emit("close")},toggleMenu:function(){this.dropdownMenuShown=!this.dropdownMenuShown},hideMenu:function(){this.dropdownMenuShown=!1},deleteDiscussion:function(){var t=this;axios.delete("/discussions/"+this.discussion.id).then(function(e){t.$emit("deleted",t.index),t.closeDiscussionDetails(),EventBus.$emit("notification",e.data.message,e.data.status)}).catch(function(e){t.closeDiscussionDetails(),EventBus.$emit("notification",e.response.data.message,e.response.data.status)})}}}},"/r2q":function(t,e,n){var r=n("VU/8")(n("M+J2"),n("3Z0g"),!1,null,null,null);t.exports=r.exports},"08EX":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=[],i="M444.788 291.1l42.616 24.599c4.867 2.809 7.126 8.618 5.459 13.985-11.07 35.642-29.97 67.842-54.689 94.586a12.016 12.016 0 0 1-14.832 2.254l-42.584-24.595a191.577 191.577 0 0 1-60.759 35.13v49.182a12.01 12.01 0 0 1-9.377 11.718c-34.956 7.85-72.499 8.256-109.219.007-5.49-1.233-9.403-6.096-9.403-11.723v-49.184a191.555 191.555 0 0 1-60.759-35.13l-42.584 24.595a12.016 12.016 0 0 1-14.832-2.254c-24.718-26.744-43.619-58.944-54.689-94.586-1.667-5.366.592-11.175 5.459-13.985L67.212 291.1a193.48 193.48 0 0 1 0-70.199l-42.616-24.599c-4.867-2.809-7.126-8.618-5.459-13.985 11.07-35.642 29.97-67.842 54.689-94.586a12.016 12.016 0 0 1 14.832-2.254l42.584 24.595a191.577 191.577 0 0 1 60.759-35.13V25.759a12.01 12.01 0 0 1 9.377-11.718c34.956-7.85 72.499-8.256 109.219-.007 5.49 1.233 9.403 6.096 9.403 11.723v49.184a191.555 191.555 0 0 1 60.759 35.13l42.584-24.595a12.016 12.016 0 0 1 14.832 2.254c24.718 26.744 43.619 58.944 54.689 94.586 1.667 5.366-.592 11.175-5.459 13.985L444.788 220.9a193.485 193.485 0 0 1 0 70.2zM336 256c0-44.112-35.888-80-80-80s-80 35.888-80 80 35.888 80 80 80 80-35.888 80-80z";e.definition={prefix:"fas",iconName:"cog",icon:[512,512,r,"f013",i]},e.faCog=e.definition,e.prefix="fas",e.iconName="cog",e.width=512,e.height=512,e.ligatures=r,e.unicode="f013",e.svgPathData=i},"0yX3":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("g7/Z"),i=n.n(r);e.default={components:{message:i.a},data:function(){return{isDisabled:!0,message:"",messages:[],nextPageUrl:null,messageBoxShown:!1,messageTextareaHeight:"auto",authUser:navbar.user,title:"",unreadMessage:0,users:[],selectedUser:{}}},created:function(){var t=this;EventBus.$on("show-message-box",this.showMessageBox),axios.get("/users").then(function(e){t.users=e.data.users}).catch(function(t){console.log(t)}),this.title=document.title,this.listen(),document.addEventListener("visibilitychange",this.clearTitleNotification)},beforeDestroy:function(){EventBus.$off("show-message-box",this.showMessageBox),document.removeEventListener("visibilitychange",this.clearTitleNotification)},watch:{message:function(t){this.messageTextareaHeight=t?this.$refs.messageTextarea.scrollHeight+"px":"auto"}},methods:{scrollToBottom:function(){var t=this;this.$nextTick(function(){var e=t.$el.querySelector("#message-box");e.scrollTop=e.lastElementChild.scrollHeight})},showMessageBox:function(){this.messageBoxShown=!0},hideMessageBox:function(){this.messageBoxShown=!1},sendMessage:function(t){var e=this;if(!this.selectedUser.id)return!1;if(t.shiftKey)this.message=this.message+"\n";else{var n=this.message;this.message="",axios.post("/messages",{message:n,resource_type:"user",resource_id:this.selectedUser.id}).then(function(t){"success"===t.data.status&&(t.data.message.user=navbar.user,e.messages.push(t.data.message))}).catch(function(t){console.log(t)})}},selectUserMessage:function(t){var e=this;this.selectedUser=t,this.isDisabled=!1,axios.get("/direct-messages",{params:{resource_type:"user",resource_id:t.id}}).then(function(t){e.messages=t.data.messages.data.reverse(),e.nextPageUrl=t.data.messages.next_page_url,e.scrollToBottom()}).catch(function(t){console.log(t)})},deleteMessage:function(t){this.messages.splice(t,1)},listen:function(){var t=this;Echo.join("user."+this.authUser.id).listen("MessageCreated",function(e){e.message.user=e.user,t.messageBoxShown||EventBus.$emit("new-direct-message"),document.hidden&&(t.unreadMessage+=1,document.title="("+t.unreadMessage+") "+t.title),t.messages.push(e.message),t.scrollToBottom()})},clearTitleNotification:function(){document.hidden||(document.title=this.title,this.unreadMessage=0)}}}},"1N+w":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("901k"),i=n.n(r),o=n("g7/Z"),a=n.n(o);e.default={components:{message:a.a,userSuggestionBox:i.a},props:["resource","resourceType","activeTab"],data:function(){return{messages:[],nextPageUrl:null,message:"",messageTextareaHeight:"auto",title:"",unreadMessage:0,members:[],name:"",mentionStarted:!1,startIndex:0,suggestionHighlightDirection:1,suggestionHighlightIndex:0,suggestionSelected:!1,suggestionShown:!1,mentions:[],user:navbar.user,users:[]}},created:function(){var t=this;EventBus.$on("clear-title-notification",this.clearTitleNotification),axios.get("/members",{params:{resource_type:this.resourceType,resource_id:this.resource.id}}).then(function(e){t.members=e.data.members}).catch(function(t){console.log(t)})},beforeDestroy:function(){EventBus.$off("clear-title-notification",this.clearTitleNotification)},mounted:function(){var t=this;axios.get("/messages",{params:{resource_type:this.resourceType,resource_id:this.resource.id}}).then(function(e){t.messages=e.data.messages.data.reverse(),t.nextPageUrl=e.data.messages.next_page_url}).catch(function(t){console.log(t)}),this.title=document.title,this.listen(),document.getElementById("message-box").scrollTop=document.getElementById("message-box").scrollHeight},updated:function(){document.getElementById("message-box").scrollTop=document.getElementById("message-box").scrollHeight},watch:{message:function(t){this.messageTextareaHeight=t?this.$refs.messageTextarea.scrollHeight+"px":"auto"}},methods:{sendMessage:function(t){var e=this;if(t.shiftKey)this.message=this.message+"\n";else if(this.mentionStarted)this.suggestionSelected=!0;else{var n=this.message;this.message="",axios.post("/messages",{message:n,resource_type:this.resourceType,resource_id:this.resource.id,mentions:this.mentions}).then(function(t){"success"===t.data.status&&(t.data.message.user=navbar.user,e.pushMessage(t.data.message))}).catch(function(t){console.error(t)})}},listen:function(){var t=this;Echo.join(this.resourceType+"."+this.resource.id).here(function(e){t.users=e}).joining(function(e){t.users.push(e),t.pushSystemMessage(e.name+" has joined"),document.activeElement===document.getElementById("send-message")&&document.hasFocus()||(t.unreadMessage+=1,document.title="("+t.unreadMessage+") "+t.title)}).leaving(function(e){t.users=t.users.filter(function(t){return t.username!==e.username}),t.pushSystemMessage(e.name+" has left"),document.activeElement===document.getElementById("send-message")&&document.hasFocus()||(t.unreadMessage+=1,document.title="("+t.unreadMessage+") "+t.title)}).listen("MessageCreated",function(e){e.message.user=e.user,t.pushMessage(e.message),document.activeElement===document.getElementById("send-message")&&document.hasFocus()||(t.unreadMessage+=1,document.title="("+t.unreadMessage+") "+t.title)})},clearTitleNotification:function(){document.title=this.title,this.unreadMessage=0},deleteMessage:function(t){this.messages.splice(t,1)},pushMessage:function(t){this.messages.push(t),EventBus.$emit("messagePushed")},pushSystemMessage:function(t){this.pushMessage({body:t,system:!0})},checkForMention:function(t){"@"===t.key?(this.suggestionShown=!0,this.mentionStarted=!0,this.startIndex=document.getElementById("send-message").selectionStart):32===t.keyCode||27===t.keyCode||8===t.keyCode&&document.getElementById("send-message").selectionStart<this.startIndex?(this.mentionStarted=!1,this.suggestionShown=!1,this.suggestionHighlightIndex=0,this.name=""):this.mentionStarted&&(this.name=t.target.value.substring(this.startIndex))},mentionHighlightMove:function(t){!this.mentionStarted||38!==t.keyCode&&40!==t.keyCode||(38===t.keyCode?(this.suggestionHighlightIndex-=1,this.suggestionHighlightDirection=-1):40===t.keyCode&&(this.suggestionHighlightIndex+=1,this.suggestionHighlightDirection=1),t.preventDefault())},userSelected:function(t){this.message=this.message.substring(0,this.startIndex)+t,this.mentions.every(function(e){return e!==t})&&this.mentions.push(t),this.mentionStarted=!1,this.suggestionShown=!1,this.suggestionSelected=!1,this.suggestionHighlightIndex=0,this.name="",document.getElementById("send-message").focus()}}}},"2eDP":function(t,e,n){var r=n("VU/8")(n("/DOn"),n("qiXB"),!1,null,null,null);t.exports=r.exports},"3Z0g":function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",[n("div",{staticClass:"absolute container mx-auto w-1/3 bg-white rounded shadow-lg z-10 mb-12 pb-4",staticStyle:{top:"10vh",left:"0",right:"0"}},[n("div",{staticClass:"text-grey-dark text-center py-4 text-2xl"},[t._v("\n Your Github Repositories\n ")]),t._v(" "),n("ul",{staticClass:"pl-0"},t._l(t.repositories,function(e,r){return n("li",{staticClass:"list-reset flex flex-row justify-between items-center py-4 px-8 hover:bg-blue-lightest"},[n("div",{staticClass:"text-grey-darker text-xl"},[t._v("\n "+t._s(e.name)+"\n ")]),t._v(" "),n("div",[n("button",{staticClass:"text-teal-dark font-semibold text-sm border border-teal-light p-2 rounded",on:{click:function(n){t.connectGithubRepo(e.id,e.name)}}},[t._v("Connect")])])])}))]),t._v(" "),n("div",{staticClass:"h-screen w-screen fixed pin bg-grey-darkest opacity-25",on:{click:t.closeModal}})])},staticRenderFns:[]}},5:function(t,e,n){t.exports=n("myy1")},"7/jY":function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"flex flex-col p-4"},[t.displayDate?n("div",{staticClass:"w-full flex flex-row py-4"},[n("div",{staticClass:"border-b w-1/5 flex-grow mb-2"}),t._v(" "),n("div",{staticClass:"text-grey-dark text-sm text-center px-4"},[t._v("\n "+t._s(t.getDate(t.message.created_at))+"\n ")]),t._v(" "),n("div",{staticClass:"border-b w-1/5 flex-grow mb-2"})]):t._e(),t._v(" "),t.message.system?n("div",{staticClass:"flex flex-row justify-center"},[n("div",{staticClass:"bg-blue-lighter text-grey-darker text-xs text-center px-4 rounded p-2"},[t._v("\n "+t._s(t.message.body)+"\n ")])]):n("div",{staticClass:"flex flex-row text-grey-darker py-3",class:[t.message.user_id===t.user.id?"self-end flex-row-reverse":""]},[n("div",{staticClass:"flex flex-col items-center relative",class:[t.message.user_id===t.user.id?"flex-col-reverse justify-end":""]},[n("img",{staticClass:"w-10 h-10 rounded-full",class:[t.message.user_id===t.user.id?"order-1":""],attrs:{src:t.generateUrl(t.message.user.avatar),alt:t.message.user.name}}),t._v(" "),t.message.user_id===t.user.id?n("div",{directives:[{name:"click-outside",rawName:"v-click-outside",value:t.hideMessageMenu,expression:"hideMessageMenu"}],staticClass:"cursor-pointer",on:{click:t.toggleMessageMenu}},[n("font-awesome-icon",{attrs:{icon:t.faEllipsisH}})],1):t._e(),t._v(" "),t.message.user_id===t.user.id&&t.dropdownMenuShown?n("div",{staticClass:"absolute rounded shadow-lg pin-t mt-16 mr-2 p-3 text-grey-darker hover:bg-grey-light",class:[t.message.user_id===t.user.id?"pin-r":"pin-l"]},[n("div",{staticClass:"cursor-pointer",on:{click:function(e){t.deleteMessage()}}},[t._v("\n Delete\n ")])]):t._e()]),t._v(" "),n("div",{staticClass:"mx-2"},[n("div",{staticClass:"rounded-lg p-3 w-64 leading-normal text-grey-darkest break-words",class:[t.message.user_id===t.user.id?"bg-teal-lightest rounded-tr-none":"bg-pink-lightest rounded-tl-none"]},[t._v("\n "+t._s(t.message.body)+"\n ")]),t._v(" "),n("div",{staticClass:"text-grey-darkest text-xs pt-2 flex flex-row",class:[t.message.user_id===t.user.id?"justify-end":""]},[n("div",{staticClass:"pr-1"},[t._v("\n "+t._s(t.message.user.name)+"\n ")]),t._v(" "),n("div",[t._v("•")]),t._v(" "),n("div",{staticClass:"pl-1"},[t._v("\n "+t._s(t.getTime(t.message.created_at))+"\n ")])])])])])},staticRenderFns:[]}},"7EUu":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW");e.default={data:function(){return{user:navbar.user,token:Laravel.csrfToken,url:navbar.navUrl,notificationShown:!1,notifications:[],unreadNotification:!1,faBell:r.c,faCircle:r.g}},created:function(){var t=this;axios.get("/notifications").then(function(e){t.notifications=e.data.notifications,-1!==t.notifications.findIndex(function(t){return null===t.read_at})&&t.showIndicator()}).catch(function(t){console.log(t.response.data.message)})},mounted:function(){this.listen()},methods:{toggleNotification:function(t){this.notificationShown?(document.body.removeEventListener("keyup",this.hideNotification),this.hideNotification(t)):(document.body.addEventListener("keyup",this.hideNotification),this.showNotification())},showNotification:function(t){this.profileDropdownShown&&(this.profileDropdownShown=!1),this.notificationShown=!0,this.unreadNotification&&(this.unreadNotification=!1,this.notificationRead())},hideNotification:function(t){if("keyup"===t.type&&"Escape"!==t.key)return!1;this.notificationShown=!1},listen:function(){var t=this;Echo.private("App.User."+this.user.id).notification(function(e){t.unreadNotification=!0,t.notifications.push(e),t.showIndicator()})},showIndicator:function(){this.unreadNotification=!0},notificationRead:function(){axios.put("notifications").catch(function(t){console.error(t.response.data.message)})}}}},"7K14":function(t,e,n){var r=n("VU/8")(n("1N+w"),n("UJh6"),!1,null,null,null);t.exports=r.exports},"7psb":function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"flex flex-row justify-around my-6 py-4 bg-white shadow rounded text-grey"},[n("div",{class:["tasks"===t.active?"text-teal-dark font-semibold border-teal border-b-2 pb-4 -mb-4":"cursor-pointer","text-center w-1/6"],on:{click:function(e){t.activateThisTab("tasks")}}},[n("font-awesome-icon",{staticClass:"text-2xl",attrs:{icon:t.faTasks}}),t._v(" "),n("span",{staticClass:"hidden md:block text-xs font-regular pt-2"},[t._v(t._s(t._f("localize")("Tasks")))])],1),t._v(" "),n("div",{class:["discussions"===t.active?"text-teal-dark font-semibold border-teal border-b-2 pb-4 -mb-4":"cursor-pointer","text-center w-1/6"],on:{click:function(e){t.activateThisTab("discussions")}}},[n("font-awesome-icon",{staticClass:"text-2xl",attrs:{icon:t.faClipboardList}}),t._v(" "),n("span",{staticClass:"hidden md:block text-xs font-regular pt-2"},[t._v(t._s(t._f("localize")("Discussions")))])],1),t._v(" "),n("div",{class:["messages"===t.active?"text-teal-dark font-semibold border-teal border-b-2 pb-4 -mb-4":"cursor-pointer","text-center w-1/6"],on:{click:t.onMessagesTabClicked}},[n("span",{staticClass:"relative inline-block"},[n("font-awesome-icon",{staticClass:"text-2xl",attrs:{icon:t.faComments}}),t._v(" "),t.displayUnreadMessageBadge?n("font-awesome-icon",{staticClass:"absolute text-xs text-teal",staticStyle:{right:"-3px",top:"-6px"},attrs:{icon:t.faCircle}}):t._e()],1),t._v(" "),n("span",{staticClass:"hidden md:block text-xs font-regular pt-2"},[t._v(t._s(t._f("localize")("Messages")))])]),t._v(" "),n("div",{class:["events"===t.active?"text-teal-dark font-semibold border-teal border-b-2 pb-4 -mb-4":"cursor-pointer","text-center w-1/6"],on:{click:function(e){t.activateThisTab("events")}}},[n("font-awesome-icon",{staticClass:"text-2xl",attrs:{icon:t.faCalendarAlt}}),t._v(" "),n("span",{staticClass:"hidden md:block text-xs font-regular pt-2"},[t._v(t._s(t._f("localize")("Events")))])],1),t._v(" "),n("div",{class:["files"===t.active?"text-teal-dark font-semibold border-teal border-b-2 pb-4 -mb-4":"cursor-pointer","text-center w-1/6"],on:{click:function(e){t.activateThisTab("files")}}},[n("font-awesome-icon",{staticClass:"text-2xl",attrs:{icon:t.faFileAlt}}),t._v(" "),n("span",{staticClass:"hidden md:block text-xs font-regular pt-2"},[t._v(t._s(t._f("localize")("Files")))])],1),t._v(" "),n("div",{class:["activities"===t.active?"text-teal-dark font-semibold border-teal border-b-2 pb-4 -mb-4":"cursor-pointer","text-center w-1/6"],on:{click:function(e){t.activateThisTab("activities")}}},[n("font-awesome-icon",{staticClass:"text-2xl",attrs:{icon:t.faBolt}}),t._v(" "),n("span",{staticClass:"hidden md:block text-xs font-regular pt-2"},[t._v(t._s(t._f("localize")("Activities")))])],1)])},staticRenderFns:[]}},"84B/":function(t,e,n){var r=n("VU/8")(n("RPMJ"),n("8f2Z"),!1,function(t){n("xNbt")},null,null);t.exports=r.exports},"8f2Z":function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{class:{hidden:!t.show}},[n("div",{staticClass:"absolute pin opacity-75 bg-grey z-10",on:{click:t.closeModal}}),t._v(" "),n("div",{staticClass:"fixed md:w-1/3 md:mx-auto pin z-50 overflow-auto bg-grey-lighter flex",attrs:{id:"members-list-modal"}},[n("div",{staticClass:"relative p-8 w-full max-w-md m-auto flex-col flex"},[n("h2",{staticClass:"mb-5"},[t._v("Members List")]),t._v(" "),t._l(t.members,function(e){return n("ul",{key:"member-"+e.id,staticClass:"list-reset"},[n("li",{staticClass:"mb-3"},[n("a",{staticClass:"no-underline text-grey-dark",attrs:{href:"/users/"+e.username}},[n("img",{staticClass:"rounded-full w-12 h-12 mr-1 align-middle",attrs:{src:t.generateUrl(e.avatar)}}),t._v(" "),n("span",[t._v(t._s(e.name))])])])])}),t._v(" "),n("div",{staticClass:"flex flex-row-reverse pt-8 bg-grey-lighter rounded"},[n("button",{staticClass:"text-red-light hover:font-bold",on:{click:t.closeModal}},[t._v("Close")])])],2)])])},staticRenderFns:[]}},"8tCw":function(t,e,n){var r=n("VU/8")(n("7EUu"),n("dcwu"),!1,null,null,null);t.exports=r.exports},"8zbO":function(t,e,n){var r=n("VU/8")(n("WgZf"),n("x3ax"),!1,null,null,null);t.exports=r.exports},"9/p9":function(t,e,n){var r=n("VU/8")(n("v4BQ"),n("lgjm"),!1,null,null,null);t.exports=r.exports},"901k":function(t,e,n){var r=n("VU/8")(n("Ha4T"),n("zqwX"),!1,null,null,null);t.exports=r.exports},"9Oya":function(t,e,n){var r=n("fxt6");"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals),n("rjj0")("cd58d502",r,!0,{})},"AGK/":function(t,e,n){var r=n("VU/8")(n("0yX3"),n("Z4Xw"),!1,null,null,null);t.exports=r.exports},AmgE:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=[],i="M328 256c0 39.8-32.2 72-72 72s-72-32.2-72-72 32.2-72 72-72 72 32.2 72 72zm104-72c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72zm-352 0c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72z";e.definition={prefix:"fas",iconName:"ellipsis-h",icon:[512,512,r,"f141",i]},e.faEllipsisH=e.definition,e.prefix="fas",e.iconName="ellipsis-h",e.width=512,e.height=512,e.ligatures=r,e.unicode="f141",e.svgPathData=i},"C/JF":function(t,e,n){"use strict";function r(t){if(t&&U){var e=R.createElement("style");e.setAttribute("type","text/css"),e.innerHTML=t;for(var n=R.head.childNodes,r=null,i=n.length-1;i>-1;i--){var o=n[i];["STYLE","LINK"].indexOf((o.tagName||"").toUpperCase())>-1&&(r=o)}return R.head.insertBefore(e,r),t}}function i(){for(var t=12,e="";t-- >0;)e+=gt[62*Math.random()|0];return e}function o(t){for(var e=[],n=(t||[]).length>>>0;n--;)e[n]=t[n];return e}function a(t){return t.classList?o(t.classList):(t.getAttribute("class")||"").split(" ").filter(function(t){return t})}function s(t,e){var n,r=e.split("-"),i=r[0],o=r.slice(1).join("-");return i!==t||""===o||(n=o,~et.indexOf(n))?null:o}function l(t){return(""+t).replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">")}function c(t){return Object.keys(t||{}).reduce(function(e,n){return e+(n+": ")+t[n]+";"},"")}function u(t){return t.size!==vt.size||t.x!==vt.x||t.y!==vt.y||t.rotate!==vt.rotate||t.flipX||t.flipY}function f(t){var e=t.transform,n=t.containerWidth,r=t.iconWidth;return{outer:{transform:"translate("+n/2+" 256)"},inner:{transform:"translate("+32*e.x+", "+32*e.y+") scale("+e.size/16*(e.flipX?-1:1)+", "+e.size/16*(e.flipY?-1:1)+") rotate("+e.rotate+" 0 0)"},path:{transform:"translate("+r/2*-1+" -256)"}}}function d(t){var e=t.icons,n=e.main,r=e.mask,o=t.prefix,a=t.iconName,s=t.transform,l=t.symbol,c=t.title,u=t.extra,f=t.watchable,d=void 0!==f&&f,h=r.found?r:n,p=h.width,v=h.height,g="fa-w-"+Math.ceil(p/v*16),m=[ct.replacementClass,a?ct.familyPrefix+"-"+a:"",g].filter(function(t){return-1===u.classes.indexOf(t)}).concat(u.classes).join(" "),y={children:[],attributes:it({},u.attributes,{"data-prefix":o,"data-icon":a,class:m,role:"img",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 "+p+" "+v})};d&&(y.attributes[Y]=""),c&&y.children.push({tag:"title",attributes:{id:y.attributes["aria-labelledby"]||"title-"+i()},children:[c]});var b=it({},y,{prefix:o,iconName:a,main:n,mask:r,transform:s,symbol:l,styles:u.styles}),w=r.found&&n.found?yt(b):bt(b),_=w.children,x=w.attributes;return b.children=_,b.attributes=x,l?_t(b):wt(b)}function h(t){var e=t.content,n=t.width,r=t.height,i=t.transform,o=t.title,a=t.extra,s=t.watchable,l=void 0!==s&&s,f=it({},a.attributes,o?{title:o}:{},{class:a.classes.join(" ")});l&&(f[Y]="");var d=it({},a.styles);u(i)&&(d.transform=function(t){var e=t.transform,n=t.width,r=void 0===n?V:n,i=t.height,o=void 0===i?V:i,a=t.startCentered,s=void 0!==a&&a,l="";return l+=s&&H?"translate("+(e.x/pt-r/2)+"em, "+(e.y/pt-o/2)+"em) ":s?"translate(calc(-50% + "+e.x/pt+"em), calc(-50% + "+e.y/pt+"em)) ":"translate("+e.x/pt+"em, "+e.y/pt+"em) ",l+="scale("+e.size/pt*(e.flipX?-1:1)+", "+e.size/pt*(e.flipY?-1:1)+") ",l+="rotate("+e.rotate+"deg) "}({transform:i,startCentered:!0,width:n,height:r}),d["-webkit-transform"]=d.transform);var h=c(d);h.length>0&&(f.style=h);var p=[];return p.push({tag:"span",attributes:f,children:[e]}),o&&p.push({tag:"span",attributes:{class:"sr-only"},children:[o]}),p}function p(t,e){return St[t][e]}function v(t){return t.reduce(function(t,e){var n=s(ct.familyPrefix,e);if(Mt[e])t.prefix=e;else if(n){var r="fa"===t.prefix?Nt[n]||{prefix:null,iconName:null}:{};t.iconName=r.iconName||n,t.prefix=r.prefix||t.prefix}else e!==ct.replacementClass&&0!==e.indexOf("fa-w-")&&t.rest.push(e);return t},Pt())}function g(t,e,n){if(t&&t[e]&&t[e][n])return{prefix:e,iconName:n,icon:t[e][n]}}function m(t){var e=t.tag,n=t.attributes,r=void 0===n?{}:n,i=t.children,o=void 0===i?[]:i;return"string"==typeof t?l(t):"<"+e+" "+function(t){return Object.keys(t||{}).reduce(function(e,n){return e+(n+'="')+l(t[n])+'" '},"").trim()}(r)+">"+o.map(m).join("")+"</"+e+">"}function y(t){return"string"==typeof(t.getAttribute?t.getAttribute(Y):null)}function b(t,e){var n="function"==typeof e?e:Dt;0===t.length?n():(I.requestAnimationFrame||function(t){return t()})(function(){var e=!0===ct.autoReplaceSvg?Lt.replace:Lt[ct.autoReplaceSvg]||Lt.replace,r=Ot.begin("mutate");t.map(e),r(),n()})}function w(t){for(var e="",n=0;n<t.length;n++)e+=("000"+t.charCodeAt(n).toString(16)).slice(-4);return e}function _(t){this.name="MissingIcon",this.message=t||"Icon unavailable",this.stack=(new Error).stack}function x(t,e){var n={found:!1,width:512,height:512,icon:Xt};if(t&&e&&Qt[e]&&Qt[e][t]){var r=Qt[e][t];n={found:!0,width:r[0],height:r[1],icon:{tag:"path",attributes:{fill:"currentColor",d:r.slice(4)[0]}}}}else if(t&&e&&!ct.showMissingIcons)throw new _("Icon is missing for prefix "+e+" with icon name "+t);return n}function k(t){var e=function(t){var e=Ft(t),n=e.iconName,r=e.prefix,i=e.rest,o=Rt(t),a=Ut(t),s=Ht(t),l=Vt(t),c=Yt(t);return{iconName:n,title:t.getAttribute("title"),prefix:r,transform:a,symbol:s,mask:c,extra:{classes:i,styles:o,attributes:l}}}(t);return~e.extra.classes.indexOf(te)?function(t,e){var n=e.title,r=e.transform,i=e.extra,o=null,a=null;if(H){var s=parseInt(getComputedStyle(t).fontSize,10),l=t.getBoundingClientRect();o=l.width/s,a=l.height/s}return ct.autoA11y&&!n&&(i.attributes["aria-hidden"]="true"),[t,h({content:t.innerHTML,width:o,height:a,transform:r,title:n,extra:i,watchable:!0})]}(t,e):function(t,e){var n=e.iconName,r=e.title,i=e.prefix,o=e.transform,a=e.symbol,s=e.mask,l=e.extra;return[t,d({icons:{main:x(n,i),mask:x(s.iconName,s.prefix)},prefix:i,iconName:n,transform:o,symbol:a,mask:s,title:r,extra:l,watchable:!0})]}(t,e)}function q(t){if(U){var e=Ot.begin("searchPseudoElements");Bt=!0,function(){o(t.querySelectorAll("*")).filter(function(t){return!(t.parentNode===document.head||~G.indexOf(t.tagName.toUpperCase())||t.getAttribute($)||t.parentNode&&"svg"===t.parentNode.tagName)}).forEach(function(t){[":before",":after"].forEach(function(e){var n=o(t.children).filter(function(t){return t.getAttribute($)===e})[0],r=I.getComputedStyle(t,e),i=r.getPropertyValue("font-family").match(ee),a=r.getPropertyValue("font-weight");if(n&&!i)t.removeChild(n);else if(i){var s=r.getPropertyValue("content"),l=~["Light","Regular","Solid","Brands"].indexOf(i[1])?ne[i[1]]:re[a],c=p(l,w(3===s.length?s.substr(1,1):s));if(!n||n.getAttribute(J)!==l||n.getAttribute(K)!==c){n&&t.removeChild(n);var u=$t.extra;u.attributes[$]=e;var f=d(it({},$t,{icons:{main:x(c,l),mask:Pt()},prefix:l,iconName:c,extra:u,watchable:!0})),h=R.createElement("svg");":before"===e?t.insertBefore(h,t.firstChild):t.appendChild(h),h.outerHTML=f.map(function(t){return m(t)}).join("\n")}}})})}(),Bt=!1,e()}}function O(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(U){var n=R.documentElement.classList,r=function(t){return n.add(W+"-"+t)},i=function(t){return n.remove(W+"-"+t)},a=Object.keys(Qt),s=["."+te+":not(["+Y+"])"].concat(a.map(function(t){return"."+t+":not(["+Y+"])"})).join(", ");if(0!==s.length){var l=o(t.querySelectorAll(s));if(l.length>0){r("pending"),i("complete");var c=Ot.begin("onTree"),u=l.reduce(function(t,e){try{var n=k(e);n&&t.push(n)}catch(t){Z||t instanceof _&&console.error(t)}return t},[]);c(),b(u,function(){r("active"),r("complete"),i("pending"),"function"==typeof e&&e()})}}}}function A(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,n=k(t);n&&b([n],e)}function C(t){return{found:!0,width:t[0],height:t[1],icon:{tag:"path",attributes:{fill:"currentColor",d:t.slice(4)[0]}}}}function E(){ct.autoAddCss&&!se&&(r(ie()),se=!0)}function S(t,e){return Object.defineProperty(t,"abstract",{get:e}),Object.defineProperty(t,"html",{get:function(){return t.abstract.map(function(t){return m(t)})}}),Object.defineProperty(t,"node",{get:function(){if(U){var e=R.createElement("div");return e.innerHTML=t.html,e.children}}}),t}function T(t){var e=t.prefix,n=void 0===e?"fa":e,r=t.iconName;if(r)return g(oe.definitions,n,r)||g(ft.styles,n,r)}Object.defineProperty(e,"__esModule",{value:!0}),n.d(e,"icon",function(){return ue}),n.d(e,"noAuto",function(){return ae}),n.d(e,"config",function(){return ct}),n.d(e,"toHtml",function(){return m}),n.d(e,"layer",function(){return he}),n.d(e,"text",function(){return fe}),n.d(e,"counter",function(){return de}),n.d(e,"library",function(){return oe}),n.d(e,"dom",function(){return le}),n.d(e,"parse",function(){return ce}),n.d(e,"findIconDefinition",function(){return T});var N=function(){},j={},M={},P=null,D={mark:N,measure:N};try{"undefined"!=typeof window&&(j=window),"undefined"!=typeof document&&(M=document),"undefined"!=typeof MutationObserver&&(P=MutationObserver),"undefined"!=typeof performance&&(D=performance)}catch(t){}var L=(j.navigator||{}).userAgent,B=void 0===L?"":L,I=j,R=M,F=P,z=D,U=!!R.documentElement&&!!R.head&&"function"==typeof R.addEventListener&&"function"==typeof R.createElement,H=~B.indexOf("MSIE")||~B.indexOf("Trident/"),V=16,Y="data-fa-i2svg",$="data-fa-pseudo-element",J="data-prefix",K="data-icon",W="fontawesome-i2svg",G=["HTML","HEAD","STYLE","SCRIPT"],Z=function(){try{return!0}catch(t){return!1}}(),X=[1,2,3,4,5,6,7,8,9,10],Q=X.concat([11,12,13,14,15,16,17,18,19,20]),tt=["class","data-prefix","data-icon","data-fa-transform","data-fa-mask"],et=["xs","sm","lg","fw","ul","li","border","pull-left","pull-right","spin","pulse","rotate-90","rotate-180","rotate-270","flip-horizontal","flip-vertical","stack","stack-1x","stack-2x","inverse","layers","layers-text","layers-counter"].concat(X.map(function(t){return t+"x"})).concat(Q.map(function(t){return"w-"+t})),nt=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},rt=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),it=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},ot=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),at=function(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)},st=I.FontAwesomeConfig||{};R&&"function"==typeof R.querySelector&&[["data-family-prefix","familyPrefix"],["data-replacement-class","replacementClass"],["data-auto-replace-svg","autoReplaceSvg"],["data-auto-add-css","autoAddCss"],["data-auto-a11y","autoA11y"],["data-search-pseudo-elements","searchPseudoElements"],["data-observe-mutations","observeMutations"],["data-keep-original-source","keepOriginalSource"],["data-measure-performance","measurePerformance"],["data-show-missing-icons","showMissingIcons"]].forEach(function(t){var e=ot(t,2),n=e[0],r=e[1],i=function(t){return""===t||"false"!==t&&("true"===t||t)}(function(t){var e=R.querySelector("script["+t+"]");if(e)return e.getAttribute(t)}(n));void 0!==i&&null!==i&&(st[r]=i)});var lt=it({familyPrefix:"fa",replacementClass:"svg-inline--fa",autoReplaceSvg:!0,autoAddCss:!0,autoA11y:!0,searchPseudoElements:!1,observeMutations:!0,keepOriginalSource:!0,measurePerformance:!1,showMissingIcons:!0},st);lt.autoReplaceSvg||(lt.observeMutations=!1);var ct=it({},lt);I.FontAwesomeConfig=ct;var ut=I||{};ut.___FONT_AWESOME___||(ut.___FONT_AWESOME___={}),ut.___FONT_AWESOME___.styles||(ut.___FONT_AWESOME___.styles={}),ut.___FONT_AWESOME___.hooks||(ut.___FONT_AWESOME___.hooks={}),ut.___FONT_AWESOME___.shims||(ut.___FONT_AWESOME___.shims=[]);var ft=ut.___FONT_AWESOME___,dt=[],ht=!1;U&&((ht=(R.documentElement.doScroll?/^loaded|^c/:/^loaded|^i|^c/).test(R.readyState))||R.addEventListener("DOMContentLoaded",function t(){R.removeEventListener("DOMContentLoaded",t),ht=1,dt.map(function(t){return t()})}));var pt=V,vt={size:16,x:0,y:0,rotate:0,flipX:!1,flipY:!1},gt="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",mt={x:0,y:0,width:"100%",height:"100%"},yt=function(t){var e=t.children,n=t.attributes,r=t.main,o=t.mask,a=t.transform,s=r.width,l=r.icon,c=o.width,u=o.icon,d=f({transform:a,containerWidth:c,iconWidth:s}),h={tag:"rect",attributes:it({},mt,{fill:"white"})},p={tag:"g",attributes:it({},d.inner),children:[{tag:"path",attributes:it({},l.attributes,d.path,{fill:"black"})}]},v={tag:"g",attributes:it({},d.outer),children:[p]},g="mask-"+i(),m="clip-"+i(),y={tag:"defs",children:[{
tag:"clipPath",attributes:{id:m},children:[u]},{tag:"mask",attributes:it({},mt,{id:g,maskUnits:"userSpaceOnUse",maskContentUnits:"userSpaceOnUse"}),children:[h,v]}]};return e.push(y,{tag:"rect",attributes:it({fill:"currentColor","clip-path":"url(#"+m+")",mask:"url(#"+g+")"},mt)}),{children:e,attributes:n}},bt=function(t){var e=t.children,n=t.attributes,r=t.main,i=t.transform,o=c(t.styles);if(o.length>0&&(n.style=o),u(i)){var a=f({transform:i,containerWidth:r.width,iconWidth:r.width});e.push({tag:"g",attributes:it({},a.outer),children:[{tag:"g",attributes:it({},a.inner),children:[{tag:r.icon.tag,children:r.icon.children,attributes:it({},r.icon.attributes,a.path)}]}]})}else e.push(r.icon);return{children:e,attributes:n}},wt=function(t){var e=t.children,n=t.main,r=t.mask,i=t.attributes,o=t.styles,a=t.transform;if(u(a)&&n.found&&!r.found){var s={x:n.width/n.height/2,y:.5};i.style=c(it({},o,{"transform-origin":s.x+a.x/16+"em "+(s.y+a.y/16)+"em"}))}return[{tag:"svg",attributes:i,children:e}]},_t=function(t){var e=t.prefix,n=t.iconName,r=t.children,i=t.attributes,o=t.symbol,a=!0===o?e+"-"+ct.familyPrefix+"-"+n:o;return[{tag:"svg",attributes:{style:"display: none;"},children:[{tag:"symbol",attributes:it({},i,{id:a}),children:r}]}]},xt=function(){},kt=ct.measurePerformance&&z&&z.mark&&z.measure?z:{mark:xt,measure:xt},qt=function(t){kt.mark('FA "5.4.1" '+t+" ends"),kt.measure('FA "5.4.1" '+t,'FA "5.4.1" '+t+" begins",'FA "5.4.1" '+t+" ends")},Ot={begin:function(t){return kt.mark('FA "5.4.1" '+t+" begins"),function(){return qt(t)}},end:qt},At=function(t,e,n,r){var i,o,a,s=Object.keys(t),l=s.length,c=void 0!==r?function(t,e){return function(n,r,i,o){return t.call(e,n,r,i,o)}}(e,r):e;for(void 0===n?(i=1,a=t[s[0]]):(i=0,a=n);i<l;i++)a=c(a,t[o=s[i]],o,t);return a},Ct=ft.styles,Et=ft.shims,St={},Tt={},Nt={},jt=function(){var t=function(t){return At(Ct,function(e,n,r){return e[r]=At(n,t,{}),e},{})};St=t(function(t,e,n){return t[e[3]]=n,t}),Tt=t(function(t,e,n){var r=e[2];return t[n]=n,r.forEach(function(e){t[e]=n}),t});var e="far"in Ct;Nt=At(Et,function(t,n){var r=n[0],i=n[1],o=n[2];return"far"!==i||e||(i="fas"),t[r]={prefix:i,iconName:o},t},{})};jt();var Mt=ft.styles,Pt=function(){return{prefix:null,iconName:null,rest:[]}},Dt=function(){},Lt={replace:function(t){var e=t[0],n=t[1].map(function(t){return m(t)}).join("\n");if(e.parentNode&&e.outerHTML)e.outerHTML=n+(ct.keepOriginalSource&&"svg"!==e.tagName.toLowerCase()?"\x3c!-- "+e.outerHTML+" --\x3e":"");else if(e.parentNode){var r=document.createElement("span");e.parentNode.replaceChild(r,e),r.outerHTML=n}},nest:function(t){var e=t[0],n=t[1];if(~a(e).indexOf(ct.replacementClass))return Lt.replace(t);var r=new RegExp(ct.familyPrefix+"-.*");delete n[0].attributes.style;var i=n[0].attributes.class.split(" ").reduce(function(t,e){return e===ct.replacementClass||e.match(r)?t.toSvg.push(e):t.toNode.push(e),t},{toNode:[],toSvg:[]});n[0].attributes.class=i.toSvg.join(" ");var o=n.map(function(t){return m(t)}).join("\n");e.setAttribute("class",i.toNode.join(" ")),e.setAttribute(Y,""),e.innerHTML=o}},Bt=!1,It=null,Rt=function(t){var e=t.getAttribute("style"),n=[];return e&&(n=e.split(";").reduce(function(t,e){var n=e.split(":"),r=n[0],i=n.slice(1);return r&&i.length>0&&(t[r]=i.join(":").trim()),t},{})),n},Ft=function(t){var e,n,r=t.getAttribute("data-prefix"),i=t.getAttribute("data-icon"),o=void 0!==t.innerText?t.innerText.trim():"",s=v(a(t));return r&&i&&(s.prefix=r,s.iconName=i),s.prefix&&o.length>1?s.iconName=(e=s.prefix,n=t.innerText,Tt[e][n]):s.prefix&&1===o.length&&(s.iconName=p(s.prefix,w(t.innerText))),s},zt=function(t){var e={size:16,x:0,y:0,flipX:!1,flipY:!1,rotate:0};return t?t.toLowerCase().split(" ").reduce(function(t,e){var n=e.toLowerCase().split("-"),r=n[0],i=n.slice(1).join("-");if(r&&"h"===i)return t.flipX=!0,t;if(r&&"v"===i)return t.flipY=!0,t;if(i=parseFloat(i),isNaN(i))return t;switch(r){case"grow":t.size=t.size+i;break;case"shrink":t.size=t.size-i;break;case"left":t.x=t.x-i;break;case"right":t.x=t.x+i;break;case"up":t.y=t.y-i;break;case"down":t.y=t.y+i;break;case"rotate":t.rotate=t.rotate+i}return t},e):e},Ut=function(t){return zt(t.getAttribute("data-fa-transform"))},Ht=function(t){var e=t.getAttribute("data-fa-symbol");return null!==e&&(""===e||e)},Vt=function(t){var e=o(t.attributes).reduce(function(t,e){return"class"!==t.name&&"style"!==t.name&&(t[e.name]=e.value),t},{}),n=t.getAttribute("title");return ct.autoA11y&&(n?e["aria-labelledby"]=ct.replacementClass+"-title-"+i():e["aria-hidden"]="true"),e},Yt=function(t){var e=t.getAttribute("data-fa-mask");return e?v(e.split(" ").map(function(t){return t.trim()})):Pt()},$t={iconName:null,title:null,prefix:null,transform:vt,symbol:!1,mask:null,extra:{classes:[],styles:{},attributes:{}}};_.prototype=Object.create(Error.prototype),_.prototype.constructor=_;var Jt,Kt={fill:"currentColor"},Wt={attributeType:"XML",repeatCount:"indefinite",dur:"2s"},Gt={tag:"path",attributes:it({},Kt,{d:"M156.5,447.7l-12.6,29.5c-18.7-9.5-35.9-21.2-51.5-34.9l22.7-22.7C127.6,430.5,141.5,440,156.5,447.7z M40.6,272H8.5 c1.4,21.2,5.4,41.7,11.7,61.1L50,321.2C45.1,305.5,41.8,289,40.6,272z M40.6,240c1.4-18.8,5.2-37,11.1-54.1l-29.5-12.6 C14.7,194.3,10,216.7,8.5,240H40.6z M64.3,156.5c7.8-14.9,17.2-28.8,28.1-41.5L69.7,92.3c-13.7,15.6-25.5,32.8-34.9,51.5 L64.3,156.5z M397,419.6c-13.9,12-29.4,22.3-46.1,30.4l11.9,29.8c20.7-9.9,39.8-22.6,56.9-37.6L397,419.6z M115,92.4 c13.9-12,29.4-22.3,46.1-30.4l-11.9-29.8c-20.7,9.9-39.8,22.6-56.8,37.6L115,92.4z M447.7,355.5c-7.8,14.9-17.2,28.8-28.1,41.5 l22.7,22.7c13.7-15.6,25.5-32.9,34.9-51.5L447.7,355.5z M471.4,272c-1.4,18.8-5.2,37-11.1,54.1l29.5,12.6 c7.5-21.1,12.2-43.5,13.6-66.8H471.4z M321.2,462c-15.7,5-32.2,8.2-49.2,9.4v32.1c21.2-1.4,41.7-5.4,61.1-11.7L321.2,462z M240,471.4c-18.8-1.4-37-5.2-54.1-11.1l-12.6,29.5c21.1,7.5,43.5,12.2,66.8,13.6V471.4z M462,190.8c5,15.7,8.2,32.2,9.4,49.2h32.1 c-1.4-21.2-5.4-41.7-11.7-61.1L462,190.8z M92.4,397c-12-13.9-22.3-29.4-30.4-46.1l-29.8,11.9c9.9,20.7,22.6,39.8,37.6,56.9 L92.4,397z M272,40.6c18.8,1.4,36.9,5.2,54.1,11.1l12.6-29.5C317.7,14.7,295.3,10,272,8.5V40.6z M190.8,50 c15.7-5,32.2-8.2,49.2-9.4V8.5c-21.2,1.4-41.7,5.4-61.1,11.7L190.8,50z M442.3,92.3L419.6,115c12,13.9,22.3,29.4,30.5,46.1 l29.8-11.9C470,128.5,457.3,109.4,442.3,92.3z M397,92.4l22.7-22.7c-15.6-13.7-32.8-25.5-51.5-34.9l-12.6,29.5 C370.4,72.1,384.4,81.5,397,92.4z"})},Zt=it({},Wt,{attributeName:"opacity"}),Xt={tag:"g",children:[Gt,{tag:"circle",attributes:it({},Kt,{cx:"256",cy:"364",r:"28"}),children:[{tag:"animate",attributes:it({},Wt,{attributeName:"r",values:"28;14;28;28;14;28;"})},{tag:"animate",attributes:it({},Zt,{values:"1;0;1;1;0;1;"})}]},{tag:"path",attributes:it({},Kt,{opacity:"1",d:"M263.7,312h-16c-6.6,0-12-5.4-12-12c0-71,77.4-63.9,77.4-107.8c0-20-17.8-40.2-57.4-40.2c-29.1,0-44.3,9.6-59.2,28.7 c-3.9,5-11.1,6-16.2,2.4l-13.1-9.2c-5.6-3.9-6.9-11.8-2.6-17.2c21.2-27.2,46.4-44.7,91.2-44.7c52.3,0,97.4,29.8,97.4,80.2 c0,67.6-77.4,63.5-77.4,107.8C275.7,306.6,270.3,312,263.7,312z"}),children:[{tag:"animate",attributes:it({},Zt,{values:"1;0;0;0;0;1;"})}]},{tag:"path",attributes:it({},Kt,{opacity:"0",d:"M232.5,134.5l7,168c0.3,6.4,5.6,11.5,12,11.5h9c6.4,0,11.7-5.1,12-11.5l7-168c0.3-6.8-5.2-12.5-12-12.5h-23 C237.7,122,232.2,127.7,232.5,134.5z"}),children:[{tag:"animate",attributes:it({},Zt,{values:"0;0;1;1;0;0;"})}]}]},Qt=ft.styles,te="fa-layers-text",ee=/Font Awesome 5 (Solid|Regular|Light|Brands|Free|Pro)/,ne={Solid:"fas",Regular:"far",Light:"fal",Brands:"fab"},re={900:"fas",400:"far",300:"fal"},ie=function(){var t="svg-inline--fa",e=ct.familyPrefix,n=ct.replacementClass,r='svg:not(:root).svg-inline--fa {\n overflow: visible; }\n\n.svg-inline--fa {\n display: inline-block;\n font-size: inherit;\n height: 1em;\n overflow: visible;\n vertical-align: -.125em; }\n .svg-inline--fa.fa-lg {\n vertical-align: -.225em; }\n .svg-inline--fa.fa-w-1 {\n width: 0.0625em; }\n .svg-inline--fa.fa-w-2 {\n width: 0.125em; }\n .svg-inline--fa.fa-w-3 {\n width: 0.1875em; }\n .svg-inline--fa.fa-w-4 {\n width: 0.25em; }\n .svg-inline--fa.fa-w-5 {\n width: 0.3125em; }\n .svg-inline--fa.fa-w-6 {\n width: 0.375em; }\n .svg-inline--fa.fa-w-7 {\n width: 0.4375em; }\n .svg-inline--fa.fa-w-8 {\n width: 0.5em; }\n .svg-inline--fa.fa-w-9 {\n width: 0.5625em; }\n .svg-inline--fa.fa-w-10 {\n width: 0.625em; }\n .svg-inline--fa.fa-w-11 {\n width: 0.6875em; }\n .svg-inline--fa.fa-w-12 {\n width: 0.75em; }\n .svg-inline--fa.fa-w-13 {\n width: 0.8125em; }\n .svg-inline--fa.fa-w-14 {\n width: 0.875em; }\n .svg-inline--fa.fa-w-15 {\n width: 0.9375em; }\n .svg-inline--fa.fa-w-16 {\n width: 1em; }\n .svg-inline--fa.fa-w-17 {\n width: 1.0625em; }\n .svg-inline--fa.fa-w-18 {\n width: 1.125em; }\n .svg-inline--fa.fa-w-19 {\n width: 1.1875em; }\n .svg-inline--fa.fa-w-20 {\n width: 1.25em; }\n .svg-inline--fa.fa-pull-left {\n margin-right: .3em;\n width: auto; }\n .svg-inline--fa.fa-pull-right {\n margin-left: .3em;\n width: auto; }\n .svg-inline--fa.fa-border {\n height: 1.5em; }\n .svg-inline--fa.fa-li {\n width: 2em; }\n .svg-inline--fa.fa-fw {\n width: 1.25em; }\n\n.fa-layers svg.svg-inline--fa {\n bottom: 0;\n left: 0;\n margin: auto;\n position: absolute;\n right: 0;\n top: 0; }\n\n.fa-layers {\n display: inline-block;\n height: 1em;\n position: relative;\n text-align: center;\n vertical-align: -.125em;\n width: 1em; }\n .fa-layers svg.svg-inline--fa {\n -webkit-transform-origin: center center;\n transform-origin: center center; }\n\n.fa-layers-text, .fa-layers-counter {\n display: inline-block;\n position: absolute;\n text-align: center; }\n\n.fa-layers-text {\n left: 50%;\n top: 50%;\n -webkit-transform: translate(-50%, -50%);\n transform: translate(-50%, -50%);\n -webkit-transform-origin: center center;\n transform-origin: center center; }\n\n.fa-layers-counter {\n background-color: #ff253a;\n border-radius: 1em;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n color: #fff;\n height: 1.5em;\n line-height: 1;\n max-width: 5em;\n min-width: 1.5em;\n overflow: hidden;\n padding: .25em;\n right: 0;\n text-overflow: ellipsis;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right; }\n\n.fa-layers-bottom-right {\n bottom: 0;\n right: 0;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom right;\n transform-origin: bottom right; }\n\n.fa-layers-bottom-left {\n bottom: 0;\n left: 0;\n right: auto;\n top: auto;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: bottom left;\n transform-origin: bottom left; }\n\n.fa-layers-top-right {\n right: 0;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top right;\n transform-origin: top right; }\n\n.fa-layers-top-left {\n left: 0;\n right: auto;\n top: 0;\n -webkit-transform: scale(0.25);\n transform: scale(0.25);\n -webkit-transform-origin: top left;\n transform-origin: top left; }\n\n.fa-lg {\n font-size: 1.33333em;\n line-height: 0.75em;\n vertical-align: -.0667em; }\n\n.fa-xs {\n font-size: .75em; }\n\n.fa-sm {\n font-size: .875em; }\n\n.fa-1x {\n font-size: 1em; }\n\n.fa-2x {\n font-size: 2em; }\n\n.fa-3x {\n font-size: 3em; }\n\n.fa-4x {\n font-size: 4em; }\n\n.fa-5x {\n font-size: 5em; }\n\n.fa-6x {\n font-size: 6em; }\n\n.fa-7x {\n font-size: 7em; }\n\n.fa-8x {\n font-size: 8em; }\n\n.fa-9x {\n font-size: 9em; }\n\n.fa-10x {\n font-size: 10em; }\n\n.fa-fw {\n text-align: center;\n width: 1.25em; }\n\n.fa-ul {\n list-style-type: none;\n margin-left: 2.5em;\n padding-left: 0; }\n .fa-ul > li {\n position: relative; }\n\n.fa-li {\n left: -2em;\n position: absolute;\n text-align: center;\n width: 2em;\n line-height: inherit; }\n\n.fa-border {\n border: solid 0.08em #eee;\n border-radius: .1em;\n padding: .2em .25em .15em; }\n\n.fa-pull-left {\n float: left; }\n\n.fa-pull-right {\n float: right; }\n\n.fa.fa-pull-left,\n.fas.fa-pull-left,\n.far.fa-pull-left,\n.fal.fa-pull-left,\n.fab.fa-pull-left {\n margin-right: .3em; }\n\n.fa.fa-pull-right,\n.fas.fa-pull-right,\n.far.fa-pull-right,\n.fal.fa-pull-right,\n.fab.fa-pull-right {\n margin-left: .3em; }\n\n.fa-spin {\n -webkit-animation: fa-spin 2s infinite linear;\n animation: fa-spin 2s infinite linear; }\n\n.fa-pulse {\n -webkit-animation: fa-spin 1s infinite steps(8);\n animation: fa-spin 1s infinite steps(8); }\n\n@-webkit-keyframes fa-spin {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg); }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg); } }\n\n@keyframes fa-spin {\n 0% {\n -webkit-transform: rotate(0deg);\n transform: rotate(0deg); }\n 100% {\n -webkit-transform: rotate(360deg);\n transform: rotate(360deg); } }\n\n.fa-rotate-90 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";\n -webkit-transform: rotate(90deg);\n transform: rotate(90deg); }\n\n.fa-rotate-180 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";\n -webkit-transform: rotate(180deg);\n transform: rotate(180deg); }\n\n.fa-rotate-270 {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";\n -webkit-transform: rotate(270deg);\n transform: rotate(270deg); }\n\n.fa-flip-horizontal {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";\n -webkit-transform: scale(-1, 1);\n transform: scale(-1, 1); }\n\n.fa-flip-vertical {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";\n -webkit-transform: scale(1, -1);\n transform: scale(1, -1); }\n\n.fa-flip-horizontal.fa-flip-vertical {\n -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";\n -webkit-transform: scale(-1, -1);\n transform: scale(-1, -1); }\n\n:root .fa-rotate-90,\n:root .fa-rotate-180,\n:root .fa-rotate-270,\n:root .fa-flip-horizontal,\n:root .fa-flip-vertical {\n -webkit-filter: none;\n filter: none; }\n\n.fa-stack {\n display: inline-block;\n height: 2em;\n position: relative;\n width: 2em; }\n\n.fa-stack-1x,\n.fa-stack-2x {\n bottom: 0;\n left: 0;\n margin: auto;\n position: absolute;\n right: 0;\n top: 0; }\n\n.svg-inline--fa.fa-stack-1x {\n height: 1em;\n width: 1em; }\n\n.svg-inline--fa.fa-stack-2x {\n height: 2em;\n width: 2em; }\n\n.fa-inverse {\n color: #fff; }\n\n.sr-only {\n border: 0;\n clip: rect(0, 0, 0, 0);\n height: 1px;\n margin: -1px;\n overflow: hidden;\n padding: 0;\n position: absolute;\n width: 1px; }\n\n.sr-only-focusable:active, .sr-only-focusable:focus {\n clip: auto;\n height: auto;\n margin: 0;\n overflow: visible;\n position: static;\n width: auto; }\n';if("fa"!==e||n!==t){var i=new RegExp("\\.fa\\-","g"),o=new RegExp("\\."+t,"g");r=r.replace(i,"."+e+"-").replace(o,"."+n)}return r},oe=new(function(){function t(){nt(this,t),this.definitions={}}return rt(t,[{key:"add",value:function(){for(var t=this,e=arguments.length,n=Array(e),r=0;r<e;r++)n[r]=arguments[r];var i=n.reduce(this._pullDefinitions,{});Object.keys(i).forEach(function(e){t.definitions[e]=it({},t.definitions[e]||{},i[e]),function t(e,n){var r=Object.keys(n).reduce(function(t,e){var r=n[e];return r.icon?t[r.iconName]=r.icon:t[e]=r,t},{});"function"==typeof ft.hooks.addPack?ft.hooks.addPack(e,r):ft.styles[e]=it({},ft.styles[e]||{},r),"fas"===e&&t("fa",n)}(e,i[e]),jt()})}},{key:"reset",value:function(){this.definitions={}}},{key:"_pullDefinitions",value:function(t,e){var n=e.prefix&&e.iconName&&e.icon?{0:e}:e;return Object.keys(n).map(function(e){var r=n[e],i=r.prefix,o=r.iconName,a=r.icon;t[i]||(t[i]={}),t[i][o]=a}),t}}]),t}()),ae=function(){ct.autoReplaceSvg=!1,ct.observeMutations=!1,It&&It.disconnect()},se=!1,le={i2svg:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(U){E();var e=t.node,n=void 0===e?R:e,r=t.callback,i=void 0===r?function(){}:r;ct.searchPseudoElements&&q(n),O(n,i)}},css:ie,insertCss:function(){se||(r(ie()),se=!0)},watch:function(){var t,e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=e.autoReplaceSvgRoot,r=e.observeMutationsRoot;!1===ct.autoReplaceSvg&&(ct.autoReplaceSvg=!0),ct.observeMutations=!0,t=function(){ve({autoReplaceSvgRoot:n}),function(t){if(F&&ct.observeMutations){var e=t.treeCallback,n=t.nodeCallback,r=t.pseudoElementsCallback,i=t.observeMutationsRoot,s=void 0===i?R.body:i;It=new F(function(t){Bt||o(t).forEach(function(t){if("childList"===t.type&&t.addedNodes.length>0&&!y(t.addedNodes[0])&&(ct.searchPseudoElements&&r(t.target),e(t.target)),"attributes"===t.type&&t.target.parentNode&&ct.searchPseudoElements&&r(t.target.parentNode),"attributes"===t.type&&y(t.target)&&~tt.indexOf(t.attributeName))if("class"===t.attributeName){var i=v(a(t.target)),o=i.prefix,s=i.iconName;o&&t.target.setAttribute("data-prefix",o),s&&t.target.setAttribute("data-icon",s)}else n(t.target)})}),U&&It.observe(s,{childList:!0,attributes:!0,characterData:!0,subtree:!0})}}({treeCallback:O,nodeCallback:A,pseudoElementsCallback:q,observeMutationsRoot:r})},U&&(ht?setTimeout(t,0):dt.push(t))}},ce={transform:function(t){return zt(t)}},ue=(Jt=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.transform,r=void 0===n?vt:n,o=e.symbol,a=void 0!==o&&o,s=e.mask,l=void 0===s?null:s,c=e.title,u=void 0===c?null:c,f=e.classes,h=void 0===f?[]:f,p=e.attributes,v=void 0===p?{}:p,g=e.styles,m=void 0===g?{}:g;if(t){var y=t.prefix,b=t.iconName,w=t.icon;return S(it({type:"icon"},t),function(){return E(),ct.autoA11y&&(u?v["aria-labelledby"]=ct.replacementClass+"-title-"+i():v["aria-hidden"]="true"),d({icons:{main:C(w),mask:l?C(l.icon):{found:!1,width:null,height:null,icon:{}}},prefix:y,iconName:b,transform:it({},vt,r),symbol:a,title:u,extra:{attributes:v,styles:m,classes:h}})})}},function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(t||{}).icon?t:T(t||{}),r=e.mask;return r&&(r=(r||{}).icon?r:T(r||{})),Jt(n,it({},e,{mask:r}))}),fe=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.transform,r=void 0===n?vt:n,i=e.title,o=void 0===i?null:i,a=e.classes,s=void 0===a?[]:a,l=e.attributes,c=void 0===l?{}:l,u=e.styles,f=void 0===u?{}:u;return S({type:"text",content:t},function(){return E(),h({content:t,transform:it({},vt,r),title:o,extra:{attributes:c,styles:f,classes:[ct.familyPrefix+"-layers-text"].concat(at(s))}})})},de=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=e.title,r=void 0===n?null:n,i=e.classes,o=void 0===i?[]:i,a=e.attributes,s=void 0===a?{}:a,l=e.styles,u=void 0===l?{}:l;return S({type:"counter",content:t},function(){return E(),function(t){var e=t.content,n=t.title,r=t.extra,i=it({},r.attributes,n?{title:n}:{},{class:r.classes.join(" ")}),o=c(r.styles);o.length>0&&(i.style=o);var a=[];return a.push({tag:"span",attributes:i,children:[e]}),n&&a.push({tag:"span",attributes:{class:"sr-only"},children:[n]}),a}({content:t.toString(),title:r,extra:{attributes:s,styles:u,classes:[ct.familyPrefix+"-layers-counter"].concat(at(o))}})})},he=function(t){return S({type:"layer"},function(){E();var e=[];return t(function(t){Array.isArray(t)?t.map(function(t){e=e.concat(t.abstract)}):e=e.concat(t.abstract)}),[{tag:"span",attributes:{class:ct.familyPrefix+"-layers"},children:e}]})},pe={noAuto:ae,config:ct,dom:le,library:oe,parse:ce,findIconDefinition:T,icon:ue,text:fe,counter:de,layer:he,toHtml:m},ve=function(){var t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).autoReplaceSvgRoot,e=void 0===t?R:t;Object.keys(ft.styles).length>0&&U&&ct.autoReplaceSvg&&pe.dom.i2svg({node:e})}},CgeB:function(t,e,n){var r=n("VU/8")(n("Hjwt"),n("eSzc"),!1,null,null,null);t.exports=r.exports},CvX0:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"w-full",class:{hidden:"tasks"!=t.activeTab}},[n("create-task-form",{ref:"taskform",attrs:{resource:t.resource,resourceType:t.resourceType,"form-shown":t.createTaskFormShown,tasks:t.tasks},on:{close:t.closeCreateTaskForm}}),t._v(" "),t.task?n("task-details",{attrs:{index:t.index,task:t.task,taskDetailsShown:t.taskDetailsShown},on:{delete:t.deleteTask,close:t.closeTaskDetails}}):t._e(),t._v(" "),n("button",{staticClass:"no-underline p-3 my-4 bg-white text-base text-teal rounded shadow",on:{click:t.showCreateTaskForm}},[t._v(t._s(t._f("localize")("Create Task")))]),t._v(" "),n("div",{staticClass:"flex flex-row flex-wrap md:-mx-1/20 lg:-mx-1/60 xl:-mx-1/40"},t._l(t.tasks,function(e,r){return n("div",{key:r,staticClass:"bg-white rounded shadow my-4 md:mx-1/20 lg:mx-1/60 xl:mx-1/40 flex flex-row p-4 no-underline items-center w-full md:w-2/5 lg:w-3/10 xl:w-1/5 h-24 border-l-2 border-teal cursor-pointer",on:{click:function(e){t.showTaskDetails(r)}}},[e.assigned_to?n("img",{staticClass:"rounded-full w-8 h-8 mx-2 self-start",attrs:{src:t.generateUrl(e.user.avatar)}}):n("i",{staticClass:"fas fa-question-circle fa-2x mx-2 self-start text-grey-darker"}),t._v(" "),n("div",{staticClass:"w-4/5 text-grey-darker text-left pl-2 flex flex-col justify-between h-full"},[n("p",{staticClass:"text-base mb-2 overflow-hidden"},[t._v(t._s(e.name))]),t._v(" "),n("p",{staticClass:"text-sm text-grey-dark"},[t._v("\n Due by "+t._s(e.due_on)+"\n ")])])])}))],1)},staticRenderFns:[]}},DnYK:function(t,e,n){var r=n("VU/8")(n("Nabe"),n("CvX0"),!1,null,null,null);t.exports=r.exports},EKta:function(t,e,n){"use strict";function r(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function i(t,e,n){for(var r,i,a=[],s=e;s<n;s+=3)r=(t[s]<<16)+(t[s+1]<<8)+t[s+2],a.push(o[(i=r)>>18&63]+o[i>>12&63]+o[i>>6&63]+o[63&i]);return a.join("")}e.byteLength=function(t){return 3*t.length/4-r(t)},e.toByteArray=function(t){var e,n,i,o,l,c=t.length;o=r(t),l=new s(3*c/4-o),n=o>0?c-4:c;var u=0;for(e=0;e<n;e+=4)i=a[t.charCodeAt(e)]<<18|a[t.charCodeAt(e+1)]<<12|a[t.charCodeAt(e+2)]<<6|a[t.charCodeAt(e+3)],l[u++]=i>>16&255,l[u++]=i>>8&255,l[u++]=255&i;return 2===o?(i=a[t.charCodeAt(e)]<<2|a[t.charCodeAt(e+1)]>>4,l[u++]=255&i):1===o&&(i=a[t.charCodeAt(e)]<<10|a[t.charCodeAt(e+1)]<<4|a[t.charCodeAt(e+2)]>>2,l[u++]=i>>8&255,l[u++]=255&i),l},e.fromByteArray=function(t){for(var e,n=t.length,r=n%3,a="",s=[],l=0,c=n-r;l<c;l+=16383)s.push(i(t,l,l+16383>c?c:l+16383));return 1===r?(e=t[n-1],a+=o[e>>2],a+=o[e<<4&63],a+="=="):2===r&&(e=(t[n-2]<<8)+t[n-1],a+=o[e>>10],a+=o[e>>4&63],a+=o[e<<2&63],a+="="),s.push(a),s.join("")};for(var o=[],a=[],s="undefined"!=typeof Uint8Array?Uint8Array:Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,u=l.length;c<u;++c)o[c]=l[c],a[l.charCodeAt(c)]=c;a["-".charCodeAt(0)]=62,a["_".charCodeAt(0)]=63},EuP9:function(t,e,n){"use strict";(function(t){function r(){return o.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function i(t,e){if(r()<e)throw new RangeError("Invalid typed array length");return o.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=o.prototype:(null===t&&(t=new o(e)),t.length=e),t}function o(t,e,n){if(!(o.TYPED_ARRAY_SUPPORT||this instanceof o))return new o(t,e,n);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return l(this,t)}return a(this,t,e,n)}function a(t,e,n,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,n,r){if(e.byteLength,n<0||e.byteLength<n)throw new RangeError("'offset' is out of bounds");if(e.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");return e=void 0===n&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,n):new Uint8Array(e,n,r),o.TYPED_ARRAY_SUPPORT?(t=e).__proto__=o.prototype:t=c(t,e),t}(t,e,n,r):"string"==typeof e?function(t,e,n){if("string"==typeof n&&""!==n||(n="utf8"),!o.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|f(e,n),a=(t=i(t,r)).write(e,n);return a!==r&&(t=t.slice(0,a)),t}(t,e,n):function(t,e){if(o.isBuffer(e)){var n=0|u(e.length);return 0===(t=i(t,n)).length?t:(e.copy(t,0,0,n),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(r=e.length)!=r?i(t,0):c(t,e);if("Buffer"===e.type&&F(e.data))return c(t,e.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function s(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function l(t,e){if(s(e),t=i(t,e<0?0:0|u(e)),!o.TYPED_ARRAY_SUPPORT)for(var n=0;n<e;++n)t[n]=0;return t}function c(t,e){var n=e.length<0?0:0|u(e.length);t=i(t,n);for(var r=0;r<n;r+=1)t[r]=255&e[r];return t}function u(t){if(t>=r())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+r().toString(16)+" bytes");return 0|t}function f(t,e){if(o.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return D(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return L(t).length;default:if(r)return D(t).length;e=(""+e).toLowerCase(),r=!0}}function d(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function h(t,e,n,r,i){if(0===t.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=i?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(i)return-1;n=t.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof e&&(e=o.from(e,r)),o.isBuffer(e))return 0===e.length?-1:p(t,e,n,r,i);if("number"==typeof e)return e&=255,o.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):p(t,[e],n,r,i);throw new TypeError("val must be string, number or Buffer")}function p(t,e,n,r,i){function o(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}var a,s=1,l=t.length,c=e.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||e.length<2)return-1;s=2,l/=2,c/=2,n/=2}if(i){var u=-1;for(a=n;a<l;a++)if(o(t,a)===o(e,-1===u?0:a-u)){if(-1===u&&(u=a),a-u+1===c)return u*s}else-1!==u&&(a-=a-u),u=-1}else for(n+c>l&&(n=l-c),a=n;a>=0;a--){for(var f=!0,d=0;d<c;d++)if(o(t,a+d)!==o(e,d)){f=!1;break}if(f)return a}return-1}function v(t,e,n,r){n=Number(n)||0;var i=t.length-n;r?(r=Number(r))>i&&(r=i):r=i;var o=e.length;if(o%2!=0)throw new TypeError("Invalid hex string");r>o/2&&(r=o/2);for(var a=0;a<r;++a){var s=parseInt(e.substr(2*a,2),16);if(isNaN(s))return a;t[n+a]=s}return a}function g(t,e,n,r){return B(D(e,t.length-n),t,n,r)}function m(t,e,n,r){return B(function(t){for(var e=[],n=0;n<t.length;++n)e.push(255&t.charCodeAt(n));return e}(e),t,n,r)}function y(t,e,n,r){return m(t,e,n,r)}function b(t,e,n,r){return B(L(e),t,n,r)}function w(t,e,n,r){return B(function(t,e){for(var n,r,i,o=[],a=0;a<t.length&&!((e-=2)<0);++a)n=t.charCodeAt(a),r=n>>8,i=n%256,o.push(i),o.push(r);return o}(e,t.length-n),t,n,r)}function _(t,e,n){return 0===e&&n===t.length?I.fromByteArray(t):I.fromByteArray(t.slice(e,n))}function x(t,e,n){n=Math.min(t.length,n);for(var r=[],i=e;i<n;){var o,a,s,l,c=t[i],u=null,f=c>239?4:c>223?3:c>191?2:1;if(i+f<=n)switch(f){case 1:c<128&&(u=c);break;case 2:128==(192&(o=t[i+1]))&&(l=(31&c)<<6|63&o)>127&&(u=l);break;case 3:o=t[i+1],a=t[i+2],128==(192&o)&&128==(192&a)&&(l=(15&c)<<12|(63&o)<<6|63&a)>2047&&(l<55296||l>57343)&&(u=l);break;case 4:o=t[i+1],a=t[i+2],s=t[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(l=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&l<1114112&&(u=l)}null===u?(u=65533,f=1):u>65535&&(u-=65536,r.push(u>>>10&1023|55296),u=56320|1023&u),r.push(u),i+=f}return function(t){var e=t.length;if(e<=z)return String.fromCharCode.apply(String,t);for(var n="",r=0;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=z));return n}(r)}function k(t,e,n){var r="";n=Math.min(t.length,n);for(var i=e;i<n;++i)r+=String.fromCharCode(127&t[i]);return r}function q(t,e,n){var r="";n=Math.min(t.length,n);for(var i=e;i<n;++i)r+=String.fromCharCode(t[i]);return r}function O(t,e,n){var r=t.length;(!e||e<0)&&(e=0),(!n||n<0||n>r)&&(n=r);for(var i="",o=e;o<n;++o)i+=P(t[o]);return i}function A(t,e,n){for(var r=t.slice(e,n),i="",o=0;o<r.length;o+=2)i+=String.fromCharCode(r[o]+256*r[o+1]);return i}function C(t,e,n){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>n)throw new RangeError("Trying to access beyond buffer length")}function E(t,e,n,r,i,a){if(!o.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<a)throw new RangeError('"value" argument is out of bounds');if(n+r>t.length)throw new RangeError("Index out of range")}function S(t,e,n,r){e<0&&(e=65535+e+1);for(var i=0,o=Math.min(t.length-n,2);i<o;++i)t[n+i]=(e&255<<8*(r?i:1-i))>>>8*(r?i:1-i)}function T(t,e,n,r){e<0&&(e=4294967295+e+1);for(var i=0,o=Math.min(t.length-n,4);i<o;++i)t[n+i]=e>>>8*(r?i:3-i)&255}function N(t,e,n,r,i,o){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function j(t,e,n,r,i){return i||N(t,0,n,4),R.write(t,e,n,r,23,4),n+4}function M(t,e,n,r,i){return i||N(t,0,n,8),R.write(t,e,n,r,52,8),n+8}function P(t){return t<16?"0"+t.toString(16):t.toString(16)}function D(t,e){var n;e=e||1/0;for(var r=t.length,i=null,o=[],a=0;a<r;++a){if((n=t.charCodeAt(a))>55295&&n<57344){if(!i){if(n>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(a+1===r){(e-=3)>-1&&o.push(239,191,189);continue}i=n;continue}if(n<56320){(e-=3)>-1&&o.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,n<128){if((e-=1)<0)break;o.push(n)}else if(n<2048){if((e-=2)<0)break;o.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;o.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return o}function L(t){return I.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(U,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function B(t,e,n,r){for(var i=0;i<r&&!(i+n>=e.length||i>=t.length);++i)e[i+n]=t[i];return i}var I=n("EKta"),R=n("ujcs"),F=n("Ht8P");e.Buffer=o,e.SlowBuffer=function(t){return+t!=t&&(t=0),o.alloc(+t)},e.INSPECT_MAX_BYTES=50,o.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=r(),o.poolSize=8192,o._augment=function(t){return t.__proto__=o.prototype,t},o.from=function(t,e,n){return a(null,t,e,n)},o.TYPED_ARRAY_SUPPORT&&(o.prototype.__proto__=Uint8Array.prototype,o.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&o[Symbol.species]===o&&Object.defineProperty(o,Symbol.species,{value:null,configurable:!0})),o.alloc=function(t,e,n){return function(t,e,n,r){return s(e),
e<=0?i(t,e):void 0!==n?"string"==typeof r?i(t,e).fill(n,r):i(t,e).fill(n):i(t,e)}(null,t,e,n)},o.allocUnsafe=function(t){return l(null,t)},o.allocUnsafeSlow=function(t){return l(null,t)},o.isBuffer=function(t){return!(null==t||!t._isBuffer)},o.compare=function(t,e){if(!o.isBuffer(t)||!o.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var n=t.length,r=e.length,i=0,a=Math.min(n,r);i<a;++i)if(t[i]!==e[i]){n=t[i],r=e[i];break}return n<r?-1:r<n?1:0},o.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},o.concat=function(t,e){if(!F(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return o.alloc(0);var n;if(void 0===e)for(e=0,n=0;n<t.length;++n)e+=t[n].length;var r=o.allocUnsafe(e),i=0;for(n=0;n<t.length;++n){var a=t[n];if(!o.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(r,i),i+=a.length}return r},o.byteLength=f,o.prototype._isBuffer=!0,o.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)d(this,e,e+1);return this},o.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)d(this,e,e+3),d(this,e+1,e+2);return this},o.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)d(this,e,e+7),d(this,e+1,e+6),d(this,e+2,e+5),d(this,e+3,e+4);return this},o.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?x(this,0,t):function(t,e,n){var r=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return O(this,e,n);case"utf8":case"utf-8":return x(this,e,n);case"ascii":return k(this,e,n);case"latin1":case"binary":return q(this,e,n);case"base64":return _(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}.apply(this,arguments)},o.prototype.equals=function(t){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===o.compare(this,t)},o.prototype.inspect=function(){var t="",n=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,n).match(/.{2}/g).join(" "),this.length>n&&(t+=" ... ")),"<Buffer "+t+">"},o.prototype.compare=function(t,e,n,r,i){if(!o.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),e<0||n>t.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&e>=n)return 0;if(r>=i)return-1;if(e>=n)return 1;if(e>>>=0,n>>>=0,r>>>=0,i>>>=0,this===t)return 0;for(var a=i-r,s=n-e,l=Math.min(a,s),c=this.slice(r,i),u=t.slice(e,n),f=0;f<l;++f)if(c[f]!==u[f]){a=c[f],s=u[f];break}return a<s?-1:s<a?1:0},o.prototype.includes=function(t,e,n){return-1!==this.indexOf(t,e,n)},o.prototype.indexOf=function(t,e,n){return h(this,t,e,n,!0)},o.prototype.lastIndexOf=function(t,e,n){return h(this,t,e,n,!1)},o.prototype.write=function(t,e,n,r){if(void 0===e)r="utf8",n=this.length,e=0;else if(void 0===n&&"string"==typeof e)r=e,n=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var i=this.length-e;if((void 0===n||n>i)&&(n=i),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var o=!1;;)switch(r){case"hex":return v(this,t,e,n);case"utf8":case"utf-8":return g(this,t,e,n);case"ascii":return m(this,t,e,n);case"latin1":case"binary":return y(this,t,e,n);case"base64":return b(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,t,e,n);default:if(o)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),o=!0}},o.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var z=4096;o.prototype.slice=function(t,e){var n,r=this.length;if(t=~~t,e=void 0===e?r:~~e,t<0?(t+=r)<0&&(t=0):t>r&&(t=r),e<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t),o.TYPED_ARRAY_SUPPORT)(n=this.subarray(t,e)).__proto__=o.prototype;else{var i=e-t;n=new o(i,void 0);for(var a=0;a<i;++a)n[a]=this[a+t]}return n},o.prototype.readUIntLE=function(t,e,n){t|=0,e|=0,n||C(t,e,this.length);for(var r=this[t],i=1,o=0;++o<e&&(i*=256);)r+=this[t+o]*i;return r},o.prototype.readUIntBE=function(t,e,n){t|=0,e|=0,n||C(t,e,this.length);for(var r=this[t+--e],i=1;e>0&&(i*=256);)r+=this[t+--e]*i;return r},o.prototype.readUInt8=function(t,e){return e||C(t,1,this.length),this[t]},o.prototype.readUInt16LE=function(t,e){return e||C(t,2,this.length),this[t]|this[t+1]<<8},o.prototype.readUInt16BE=function(t,e){return e||C(t,2,this.length),this[t]<<8|this[t+1]},o.prototype.readUInt32LE=function(t,e){return e||C(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},o.prototype.readUInt32BE=function(t,e){return e||C(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},o.prototype.readIntLE=function(t,e,n){t|=0,e|=0,n||C(t,e,this.length);for(var r=this[t],i=1,o=0;++o<e&&(i*=256);)r+=this[t+o]*i;return r>=(i*=128)&&(r-=Math.pow(2,8*e)),r},o.prototype.readIntBE=function(t,e,n){t|=0,e|=0,n||C(t,e,this.length);for(var r=e,i=1,o=this[t+--r];r>0&&(i*=256);)o+=this[t+--r]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*e)),o},o.prototype.readInt8=function(t,e){return e||C(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},o.prototype.readInt16LE=function(t,e){e||C(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt16BE=function(t,e){e||C(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},o.prototype.readInt32LE=function(t,e){return e||C(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},o.prototype.readInt32BE=function(t,e){return e||C(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},o.prototype.readFloatLE=function(t,e){return e||C(t,4,this.length),R.read(this,t,!0,23,4)},o.prototype.readFloatBE=function(t,e){return e||C(t,4,this.length),R.read(this,t,!1,23,4)},o.prototype.readDoubleLE=function(t,e){return e||C(t,8,this.length),R.read(this,t,!0,52,8)},o.prototype.readDoubleBE=function(t,e){return e||C(t,8,this.length),R.read(this,t,!1,52,8)},o.prototype.writeUIntLE=function(t,e,n,r){t=+t,e|=0,n|=0,r||E(this,t,e,n,Math.pow(2,8*n)-1,0);var i=1,o=0;for(this[e]=255&t;++o<n&&(i*=256);)this[e+o]=t/i&255;return e+n},o.prototype.writeUIntBE=function(t,e,n,r){t=+t,e|=0,n|=0,r||E(this,t,e,n,Math.pow(2,8*n)-1,0);var i=n-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+n},o.prototype.writeUInt8=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,1,255,0),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},o.prototype.writeUInt16LE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):S(this,t,e,!0),e+2},o.prototype.writeUInt16BE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,2,65535,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):S(this,t,e,!1),e+2},o.prototype.writeUInt32LE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):T(this,t,e,!0),e+4},o.prototype.writeUInt32BE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,4,4294967295,0),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):T(this,t,e,!1),e+4},o.prototype.writeIntLE=function(t,e,n,r){if(t=+t,e|=0,!r){var i=Math.pow(2,8*n-1);E(this,t,e,n,i-1,-i)}var o=0,a=1,s=0;for(this[e]=255&t;++o<n&&(a*=256);)t<0&&0===s&&0!==this[e+o-1]&&(s=1),this[e+o]=(t/a>>0)-s&255;return e+n},o.prototype.writeIntBE=function(t,e,n,r){if(t=+t,e|=0,!r){var i=Math.pow(2,8*n-1);E(this,t,e,n,i-1,-i)}var o=n-1,a=1,s=0;for(this[e+o]=255&t;--o>=0&&(a*=256);)t<0&&0===s&&0!==this[e+o+1]&&(s=1),this[e+o]=(t/a>>0)-s&255;return e+n},o.prototype.writeInt8=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,1,127,-128),o.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},o.prototype.writeInt16LE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):S(this,t,e,!0),e+2},o.prototype.writeInt16BE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,2,32767,-32768),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):S(this,t,e,!1),e+2},o.prototype.writeInt32LE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,4,2147483647,-2147483648),o.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):T(this,t,e,!0),e+4},o.prototype.writeInt32BE=function(t,e,n){return t=+t,e|=0,n||E(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),o.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):T(this,t,e,!1),e+4},o.prototype.writeFloatLE=function(t,e,n){return j(this,t,e,!0,n)},o.prototype.writeFloatBE=function(t,e,n){return j(this,t,e,!1,n)},o.prototype.writeDoubleLE=function(t,e,n){return M(this,t,e,!0,n)},o.prototype.writeDoubleBE=function(t,e,n){return M(this,t,e,!1,n)},o.prototype.copy=function(t,e,n,r){if(n||(n=0),r||0===r||(r=this.length),e>=t.length&&(e=t.length),e||(e=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-e<r-n&&(r=t.length-e+n);var i,a=r-n;if(this===t&&n<e&&e<r)for(i=a-1;i>=0;--i)t[i+e]=this[i+n];else if(a<1e3||!o.TYPED_ARRAY_SUPPORT)for(i=0;i<a;++i)t[i+e]=this[i+n];else Uint8Array.prototype.set.call(t,this.subarray(n,n+a),e);return a},o.prototype.fill=function(t,e,n,r){if("string"==typeof t){if("string"==typeof e?(r=e,e=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===t.length){var i=t.charCodeAt(0);i<256&&(t=i)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!o.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<n)throw new RangeError("Out of range index");if(n<=e)return this;var a;if(e>>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(a=e;a<n;++a)this[a]=t;else{var s=o.isBuffer(t)?t:D(new o(t,r).toString()),l=s.length;for(a=0;a<n-e;++a)this[a+e]=s[a%l]}return this};var U=/[^+\/0-9A-Za-z-_]/g}).call(e,n("DuR2"))},F70e:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"w-full",class:{hidden:"events"!=t.activeTab}},[t._m(0),t._v(" "),n("div",{staticClass:"flex flex-row flex-wrap justify-center"},[n("div",{staticClass:"bg-white rounded shadow py-4 px-2 md:px-6 my-4 md:m-4",staticStyle:{width:"24rem"}},[n("div",{staticClass:"text-3xl text-grey-darker font-semibold text-center py-2"},[t._v("\n Product Release\n ")]),t._v(" "),t._m(1),t._v(" "),n("div",{staticClass:"text-grey-darker p-2 flex flex-col md:flex-row justify-center items-center"},[n("div",{staticClass:"px-3 pb-2 md:pb-0"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faClock}}),t._v("\n 10:30 am\n ")],1),t._v(" "),n("div",{staticClass:"px-3 pt-2 md:pt-0"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faCalendarAlt}}),t._v("\n 30 Dec, 2018\n ")],1)]),t._v(" "),n("div",{staticClass:"text-grey-darker p-2 flex flex-row justify-center"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faMapMarker}}),t._v("\n Goodwork Headquarter\n ")],1),t._v(" "),n("div",{staticClass:"text-grey-darker text-center p-4"},[t._v("\n Release of first version (v1.0) of Goodwork software\n ")])]),t._v(" "),n("div",{staticClass:"bg-white rounded shadow py-4 px-2 md:px-6 my-4 md:m-4",staticStyle:{width:"24rem"}},[n("div",{staticClass:"text-3xl text-grey-darker font-semibold text-center py-2"},[t._v("\n Blog Announcement\n ")]),t._v(" "),t._m(2),t._v(" "),n("div",{staticClass:"text-grey-darker p-2 flex flex-row justify-center"},[n("div",{staticClass:"px-3 pb-2 md:pb-0"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faClock}}),t._v("\n 4:30 pm\n ")],1),t._v(" "),n("div",{staticClass:"px-3 pt-2 md:pt-0"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faCalendarAlt}}),t._v("\n 30 Dec, 2018\n ")],1)]),t._v(" "),n("div",{staticClass:"text-grey-darker p-2 flex flex-row justify-center"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faMapMarker}}),t._v("\n Goodwork Headquarter\n ")],1),t._v(" "),n("div",{staticClass:"text-grey-darker text-center p-4"},[t._v("\n No description available\n ")])])]),t._v(" "),t._m(3),t._v(" "),n("div",{staticClass:"flex flex-row flex-wrap justify-center"},[n("div",{staticClass:"bg-white rounded shadow w-80"},[n("div",{staticClass:"text-xl text-grey-darker font-semibold text-center pt-4"},[t._v("\n Product Release\n ")]),t._v(" "),t._m(4),t._v(" "),n("div",{staticClass:"text-sm text-grey-darker p-1 flex flex-row justify-center"},[n("div",{staticClass:"px-3"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faClock}}),t._v("\n 8:30 pm\n ")],1),t._v(" "),n("div",{staticClass:"px-3"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faCalendarAlt}}),t._v("\n 30 Dec, 2018\n ")],1)]),t._v(" "),n("div",{staticClass:"text-sm text-grey-darker p-1 flex flex-row justify-center"},[n("font-awesome-icon",{staticClass:"text-grey-dark mr-1",attrs:{icon:t.faMapMarker}}),t._v("\n Goodwork Headquarter\n ")],1),t._v(" "),n("div",{staticClass:"text-grey-darker text-center p-4"},[t._v("\n Release of first version (v1.0) of Goodwork software\n ")])])])])},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"flex flex-row items-center"},[e("div",{staticClass:"border-t flex-1"}),this._v(" "),e("div",{staticClass:"p-4 text-grey-dark"},[this._v("Today")]),this._v(" "),e("div",{staticClass:"border-t flex-1"})])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"text-grey-darker text-center py-2 text-sm"},[e("span",{staticClass:"font-medium text-lg text-pink"},[this._v("2")]),this._v(" hour "),e("span",{staticClass:"font-medium text-lg text-pink"},[this._v("40")]),this._v(" min left\n ")])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"text-grey-darker text-center py-2 text-sm"},[e("span",{staticClass:"font-medium text-lg text-pink"},[this._v("6")]),this._v(" hour "),e("span",{staticClass:"font-medium text-lg text-pink"},[this._v("40")]),this._v(" min left\n ")])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"flex flex-row items-center"},[e("div",{staticClass:"border-t flex-1"}),this._v(" "),e("div",{staticClass:"p-4 text-grey-dark"},[this._v("This week")]),this._v(" "),e("div",{staticClass:"border-t flex-1"})])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"text-grey-darker text-center py-2 text-xs"},[e("span",{staticClass:"font-medium text-pink"},[this._v("2")]),this._v(" hour\n "),e("span",{staticClass:"font-medium text-pink"},[this._v("40")]),this._v(" min left\n ")])}]}},"FZ+f":function(t,e){t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var n=function(t,e){var n=t[1]||"",r=t[3];if(!r)return n;if(e&&"function"==typeof btoa){var i=(o=r,"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(o))))+" */");return[n].concat(r.sources.map(function(t){return"/*# sourceURL="+r.sourceRoot+t+" */"})).concat([i]).join("\n")}var o;return[n].join("\n")}(e,t);return e[2]?"@media "+e[2]+"{"+n+"}":n}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},i=0;i<this.length;i++){var o=this[i][0];"number"==typeof o&&(r[o]=!0)}for(i=0;i<t.length;i++){var a=t[i];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},FlIk:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"px-4 border-l flex items-center cursor-pointer p-4"},[n("div",{staticClass:"flex flex-row items-center",attrs:{id:"profile-dropdown"},on:{click:t.toggleProfileDropdown}},[n("img",{staticClass:"w-10 h-10 rounded-full md:mr-2",attrs:{src:t.generateUrl(t.user.avatar)}}),t._v(" "),n("span",{staticClass:"text-grey-darker text-base no-underline hidden md:block"},[t._v("\n "+t._s(t.user.name)+"\n "),n("font-awesome-icon",{attrs:{icon:t.faAngleDown}})],1)]),t._v(" "),t.profileDropdownShown?n("div",{directives:[{name:"click-outside",rawName:"v-click-outside",value:t.hideProfileDropdown,expression:"hideProfileDropdown"}],staticClass:"absolute bg-white w-48 pin-r mr-2 py-1 shadow-lg rounded z-50",staticStyle:{top:"3.5rem"},attrs:{id:"profile-menu"}},[n("a",{staticClass:"px-4 py-2 hover:bg-teal hover:text-white no-underline text-grey-dark block font-medium",attrs:{href:t.profileUrl}},[n("span",{staticClass:"w-6 inline-block"},[n("font-awesome-icon",{staticClass:"pr-1",attrs:{icon:t.faUser}})],1),t._v("\n "+t._s(t._f("localize")("Your Profile"))+"\n ")]),t._v(" "),n("a",{staticClass:"px-4 py-2 hover:bg-teal hover:text-white text-grey-dark font-medium no-underline block",attrs:{href:"/admin"}},[n("span",{staticClass:"w-6 inline-block"},[n("font-awesome-icon",{staticClass:"pr-1 font-regular",attrs:{icon:t.faShieldAlt}})],1),t._v("\n "+t._s(t._f("localize")("Admin"))+"\n ")]),t._v(" "),n("a",{staticClass:"px-4 py-2 hover:bg-teal hover:text-white text-grey-dark font-medium no-underline block",attrs:{href:"#"}},[n("span",{staticClass:"w-6 inline-block"},[n("font-awesome-icon",{staticClass:"pr-1 font-regular",attrs:{icon:t.faCog}})],1),t._v("\n "+t._s(t._f("localize")("Settings"))+"\n ")]),t._v(" "),n("span",{staticClass:"block border-t"}),t._v(" "),n("a",{staticClass:"px-4 py-2 hover:bg-teal hover:text-white text-grey-dark font-medium no-underline block",attrs:{href:t.url.logout},on:{click:t.logoutUser}},[n("span",{staticClass:"w-6 inline-block"},[n("font-awesome-icon",{staticClass:"pr-1 font-regular",attrs:{icon:t.faSignOutAlt}})],1),t._v("\n "+t._s(t._f("localize")("Logout"))+"\n ")])]):t._e(),t._v(" "),n("form",{staticStyle:{display:"none"},attrs:{id:"logout-form",action:t.url.logout,method:"POST"}},[n("input",{attrs:{type:"hidden",name:"_token"},domProps:{value:t.token}})])])},staticRenderFns:[]}},GaUX:function(t,e){t.exports={render:function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"px-4 h-full border-l flex items-center"},[e("div",{staticClass:"text-teal-light text-base no-underline cursor-pointer",attrs:{id:"notification"},on:{click:this.showMessageBox}},[e("font-awesome-icon",{staticClass:"font-bold text-xl",attrs:{icon:this.faEnvelope}}),this._v(" "),this.unreadMessage?e("font-awesome-icon",{staticClass:"text-red-light text-sm absolute pin-t mt-3 ml-4",attrs:{icon:this.faCircle,"aria-hidden":"true"}}):this._e()],1)])},staticRenderFns:[]}},HYRr:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"container mx-auto px-4 my-6 w-full md:w-md lg:w-lg xl:w-xl xxl:w-2xl"},[n("div",{staticClass:"text-grey-dark font-semibold text-2xl mb-4 flex items-center justify-center"},[t._v("\n "+t._s(t.office.name)+"\n "),n("span",{directives:[{name:"click-outside",rawName:"v-click-outside",value:t.closeDropdownMenu,expression:"closeDropdownMenu"}],staticClass:"bg-white p-1 text-sm rounded-full shadow ml-4 cursor-pointer flex items-center",on:{click:t.toggleDropdownMenu}},[n("font-awesome-icon",{attrs:{icon:t.faCog}})],1),t._v(" "),t.dropdownMenuShown?n("div",{staticClass:"relative"},[n("ul",{staticClass:"list-reset bg-white rounded shadow-lg py-2 absolute pin-r mt-4 text-base text-left font-normal whitespace-no-wrap"},[n("li",{staticClass:"px-4 py-2 hover:bg-grey-light cursor-pointer"},[n("a",{staticClass:"no-underline text-grey-dark",attrs:{href:"#"},on:{click:function(e){e.preventDefault(),t.showMembersListModal(e)}}},[t._v("\n Show All Members\n ")])]),t._v(" "),n("li",{staticClass:"px-4 py-2 hover:bg-grey-light cursor-pointer"},[t._v("\n Delete\n ")])])]):t._e()]),t._v(" "),t.addMemberFormShown?n("addMemberForm",{attrs:{resourceType:"office",resource:t.office},on:{close:t.closeAddMemberForm,addMember:t.addMember}}):t._e(),t._v(" "),t.githubRepoModalShown?n("show-github-repo",{attrs:{entityType:"team",entityId:t.team.id},on:{"close-github-repo-modal":t.closeGithubRepoModal}}):t._e(),t._v(" "),n("div",{staticClass:"h-16 flex flex-row justify-center items-center px-2"},[n("span",{staticClass:"bg-white shadow w-8 h-8 rounded-full text-teal hover:cursor-pointer text-center p-2",on:{click:t.showAddMemberForm}},[n("font-awesome-icon",{attrs:{icon:t.faPlus}})],1),t._v(" "),t._l(t.office.members,function(e,r){return r<5?n("a",{staticClass:"pl-2",attrs:{href:"/users/"+e.username}},[n("img",{staticClass:"rounded-full w-8 h-8 mr-1",attrs:{src:t.generateUrl(e.avatar)}})]):t._e()}),t._v(" "),t.office.members.length>5?n("span",{staticClass:"bg-grey-lighter border-teal border p-2 rounded-full"},[t._v(t._s(t.office.members.length-5)+"+")]):t._e()],2),t._v(" "),n("tab-menu",{attrs:{active:t.active},on:{activate:t.activateTab}}),t._v(" "),n("div",{staticClass:"flex flex-row flex-wrap justify-center"},[n("taskBoard",{attrs:{resourceType:"office",resource:t.office,activeTab:t.active}}),t._v(" "),n("discussionBoard",{attrs:{resourceType:"office",resource:t.office,activeTab:t.active}}),t._v(" "),n("messagesBoard",{attrs:{resourceType:"office",resource:t.office,activeTab:t.active}}),t._v(" "),n("event-board",{attrs:{resourceType:"office",resource:t.office,activeTab:t.active}}),t._v(" "),n("file-board",{attrs:{resourceType:"office",resource:t.office,activeTab:t.active}})],1),t._v(" "),n("members-list-modal",{attrs:{show:t.membersListModalShown,members:t.office.members},on:{close:t.closeMembersListModal}})],1)},staticRenderFns:[]}},Ha4T:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("RvPm"),i=n.n(r);e.default={props:{name:{required:!0,type:String},users:{required:!0,type:Array},suggestionShown:{required:!0,type:Boolean},suggestionSelected:{required:!0,type:Boolean},suggestionHighlightIndex:{required:!0,type:Number},suggestionHighlightDirection:{required:!0,type:Number},suggestionHighlightDirectionInverted:{type:Boolean}},data:function(){return{sortedUsers:[],highlightIndex:0}},watch:{name:"search",suggestionSelected:"selectUserEnter",suggestionHighlightIndex:"suggestionHighlightMove"},methods:{search:function(){this.sortedUsers=i.a.go(this.name,this.users,{keys:["name","username"],limit:5}),this.highlightIndex=0,this.suggestionHighlightDirectionInverted&&(this.sortedUsers.reverse(),this.highlightIndex=this.sortedUsers.length-1)},selectUser:function(t){this.$emit("selected",t)},selectUserEnter:function(){this.suggestionSelected&&this.selectUser(this.sortedUsers[this.highlightIndex][1].target)},getUserAvatar:function(t){return this.users.find(function(e){if(e.username===t)return e.avatar}).avatar},suggestionHighlightMove:function(){-1===this.suggestionHighlightDirection&&this.highlightIndex>0?this.highlightIndex-=1:1===this.suggestionHighlightDirection&&this.highlightIndex<this.sortedUsers.length-1&&(this.highlightIndex+=1)}}}},Hjwt:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("+1qq"),i=n.n(r),o=n("fhbW");e.default={components:{commentBox:i.a},props:{taskDetailsShown:{required:!0,type:Boolean},task:{required:!0,type:Object},index:{required:!0}},data:function(){return{dropdownMenuShown:!1,faArrowLeft:o.b,faEllipsisH:o.l}},methods:{closeTaskDetails:function(){this.dropdownMenuShown=!1,this.$emit("close")},toggleMenu:function(){this.dropdownMenuShown=!this.dropdownMenuShown},hideMenu:function(){this.dropdownMenuShown=!1},deleteTask:function(){var t=this;axios.delete("/tasks/"+this.task.id).then(function(e){t.$emit("delete",t.index),t.dropdownMenuShown=!1,EventBus.$emit("notification",e.data.message,e.data.status),t.$emit("close")}),this.dropdownMenuShown=(!1).catch(function(e){EventBus.$emit("notification",e.response.data.message,e.response.data.status),t.$emit("close")})}}}},Ht8P:function(t,e){var n={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==n.call(t)}},I8eF:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("901k"),i=n.n(r),o=n("fhbW");e.default={components:{userSuggestionBox:i.a},props:{resourceType:{required:!0,type:String},resource:{required:!0,type:Object},detailsShown:{required:!0,type:Boolean}},data:function(){return{body:"",comments:[],user:navbar.user,users:[],name:"",mentionStarted:!1,startIndex:0,suggestionHighlightDirection:1,suggestionHighlightIndex:0,suggestionSelected:!1,suggestionShown:!1,mentions:[],faTrashAlt:o.x}},created:function(){var t=this;axios.get("/comments",{params:{commentable_type:this.resourceType,commentable_id:this.resource.id}}).then(function(e){t.comments=e.data.comments}).catch(function(t){console.log(t.response.data.message)}),axios.get("/users").then(function(e){t.users=e.data.users}).catch(function(t){console.log(t)})},methods:{saveComment:function(t){var e=this;t.shiftKey?this.body=this.body+"\n":this.mentionStarted?this.suggestionSelected=!0:axios.post("/comments",{body:this.body,commentable_type:this.resourceType,commentable_id:this.resource.id,mentions:this.mentions}).then(function(t){e.body="",e.comments.push(t.data.comment),EventBus.$emit("notification",t.data.message,t.data.status)}).catch(function(t){EventBus.$emit("notification",t.response.data.message,t.response.data.status)})},deleteComment:function(t,e){var n=this;axios.delete("/comments/"+t.id).then(function(t){n.comments.splice(e,1),EventBus.$emit("notification",t.data.message,t.data.status)}).catch(function(t){EventBus.$emit("notification",t.response.data.message,t.response.data.status)})},checkForMention:function(t){"@"===t.key?(this.suggestionShown=!0,this.mentionStarted=!0,this.startIndex=document.getElementById("save-comment").selectionStart):32===t.keyCode||27===t.keyCode||8===t.keyCode&&document.getElementById("save-comment").selectionStart<this.startIndex?(this.mentionStarted=!1,this.suggestionShown=!1,this.suggestionHighlightIndex=0,this.name=""):this.mentionStarted&&(this.name=t.target.value.substring(this.startIndex))},mentionHighlightMove:function(t){!this.mentionStarted||38!==t.keyCode&&40!==t.keyCode||(38===t.keyCode?(this.suggestionHighlightIndex-=1,this.suggestionHighlightDirection=-1):40===t.keyCode&&(this.suggestionHighlightIndex+=1,this.suggestionHighlightDirection=1),t.preventDefault())},userSelected:function(t){this.body=this.body.substring(0,this.startIndex)+t,this.mentions.push(t),this.mentionStarted=!1,this.suggestionShown=!1,this.suggestionSelected=!1,this.suggestionHighlightIndex=0,this.name="",document.getElementById("save-comment").focus()}}}},IW2Z:function(t,e,n){var r=n("VU/8")(n("nkvb"),n("gcBg"),!1,null,null,null);t.exports=r.exports},K7iK:function(t,e){t.exports={render:function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"bg-white shadow-md w-64 h-64 flex flex-row flex-wrap justify-center text-center rounded m-4"},[e("header",{staticClass:"w-full relative border-b h-12 pt-4"},[e("a",{staticClass:"text-grey-darker font-medium no-underline",attrs:{href:"/"+this.resourceType+"/"+this.resource.id+"/activities"}},[this._v("\n Activities\n ")]),this._v(" "),e("span",{staticClass:"text-grey-darker absolute pin-r mr-2"},[e("font-awesome-icon",{attrs:{icon:this.faEllipsisH}})],1)]),this._v(" "),this._m(0)])},staticRenderFns:[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"w-full h-48 self-start text-left"},[n("a",{staticClass:"flex flex-row p-4 no-underline text-grey-darker",attrs:{href:"#"}},[n("img",{staticClass:"rounded-full w-8 h-8 mr-2",attrs:{src:"http://placehold.it/34x34"}}),t._v(" "),n("div",{staticClass:"text-sm"},[n("p",[n("span",{staticClass:"text-pink"},[t._v("John")]),n("span",[t._v(" added a new task")])]),t._v(" "),n("p",{staticClass:"text-xs"},[t._v("15 min ago")])])]),t._v(" "),n("a",{staticClass:"flex flex-row p-4 no-underline text-grey-darker",attrs:{href:"#"}},[n("img",{staticClass:"rounded-full w-8 h-8 mr-2",attrs:{src:"http://placehold.it/34x34"}}),t._v(" "),n("div",{staticClass:"text-sm"},[n("p",[n("span",{staticClass:"text-pink"},[t._v("John")]),n("span",[t._v(" commented in ")]),n("span",{staticClass:"text-pink"},[t._v("Review Meeting")])]),t._v(" "),n("p",{staticClass:"text-xs"},[t._v("20 min ago")])])]),t._v(" "),n("a",{staticClass:"flex flex-row p-4 no-underline text-grey-darker",attrs:{href:"#"}},[n("img",{staticClass:"rounded-full w-8 h-8 mr-2",attrs:{src:"http://placehold.it/34x34"}}),t._v(" "),n("div",{staticClass:"text-sm"},[n("p",[n("span",{staticClass:"text-pink"},[t._v("James")]),n("span",[t._v(" archived a discussion")])]),t._v(" "),n("p",{staticClass:"text-xs"},[t._v("1 hr ago")])])])])}]}},L8IH:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",[n("div",{staticClass:"absolute container mx-auto w-1/3 bg-white rounded shadow-lg z-10",staticStyle:{top:"10vh",left:"0",right:"0"}},[n("div",{staticClass:"p-4"},[n("div",{staticClass:"p-4"},[n("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold text-center text-lg mb-4",attrs:{for:"user"}},[t._v("\n Add Member\n ")]),t._v(" "),n("div",{staticClass:"flex flex-row items-center"},[n("select",{directives:[{name:"model",rawName:"v-model",value:t.newMember,expression:"newMember"}],staticClass:"w-5/6 block appearance-none w-full bg-grey-lighter border border-grey-lighter text-grey-darker py-3 px-4 pr-8 rounded",attrs:{id:"user"},on:{change:function(e){var n=Array.prototype.filter.call(e.target.options,function(t){return t.selected}).map(function(t){return"_value"in t?t._value:t.value});t.newMember=e.target.multiple?n:n[0]}}},[n("option",{attrs:{selected:"",disabled:"",hidden:""}},[t._v("Select User to Add")]),t._v(" "),t._l(t.users,function(e){return[n("option",{staticClass:"my-2 text-lg",domProps:{value:e.id}},[t._v(t._s(e.name))])]})],2),t._v(" "),n("font-awesome-icon",{staticClass:"w-1/6 pointer-events-none flex items-center text-grey-darker -ml-8",attrs:{icon:t.faChevronDown}})],1)])]),t._v(" "),n("div",{staticClass:"flex flex-row justify-between py-4 px-8 bg-grey-lighter rounded"},[n("button",{staticClass:"text-red-lighter hover:font-bold hover:text-red-light",on:{click:t.closeAddMemberForm}},[t._v("Cancel")]),t._v(" "),n("button",{staticClass:"bg-teal-light text-white font-medium hover:bg-teal-dark py-4 px-8 rounded",on:{click:t.addMember}},[t.loading?[n("font-awesome-icon",{attrs:{icon:t.faSpinner,spin:""}})]:t._e(),t._v("\n Add\n ")],2)])]),t._v(" "),n("div",{staticClass:"h-screen w-screen fixed pin bg-grey-darkest opacity-25"})])},staticRenderFns:[]}},"M+J2":function(t,e,n){
"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={props:{entityType:{required:!0,type:String},entityId:{required:!0,type:Number}},data:function(){return{repositories:[]}},created:function(){var t=this;axios.get("/services/github/repos").then(function(e){t.repositories=e.data.repos.data.viewer.repositories.nodes}).catch(function(t){console.error(t.response.data.message())})},methods:{closeModal:function(){this.$emit("close-github-repo-modal")},connectGithubRepo:function(t,e){axios.post("/services/github/connected-repos",{github_repo_id:t,repo_name:e,entity_type:this.entityType,entity_id:this.entityId}).then(function(t){EventBus.$emit("notification",t.data.message,t.data.status)}).catch(function(t){EventBus.$emit("notification",t.response.data.message,t.response.data.status)})}}}},Ms4a:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW");e.default={props:["resource","resourceType"],data:function(){return{users:[],newMember:null,loading:!1,faChevronDown:r.f,faSpinner:r.u}},created:function(){var t=this;axios.get("/users").then(function(e){t.users=e.data.users}).catch(function(t){console.log(t)})},methods:{addMember:function(){var t=this;this.loading=!0,axios.post("/members",{user_id:this.newMember,resource_type:this.resourceType,resource_id:this.resource.id}).then(function(e){"success"===e.data.status&&(t.loading=!1,EventBus.$emit("notification",e.data.message,e.data.status),t.$emit("addMember",e.data),t.$emit("close"))}).catch(function(e){t.loading=!1,EventBus.$emit("notification",e.response.data.message,e.response.data.status),t.$emit("addMember",e.response.data),t.$emit("close")})},closeAddMemberForm:function(){this.$emit("close")}}}},Nabe:function(t,e,n){"use strict";function r(t){return function(){var e=t.apply(this,arguments);return new Promise(function(t,n){return function r(i,o){try{var a=e[i](o),s=a.value}catch(t){return void n(t)}if(!a.done)return Promise.resolve(s).then(function(t){r("next",t)},function(t){r("throw",t)});t(s)}("next")})}}Object.defineProperty(e,"__esModule",{value:!0});var i=n("Xxa5"),o=n.n(i),a=n("9/p9"),s=n.n(a),l=n("CgeB"),c=n.n(l);e.default={components:{createTaskForm:s.a,taskDetails:c.a},props:{resource:{required:!0,type:Object},resourceType:{required:!0,type:String},activeTab:{required:!0,type:String}},data:function(){return{createTaskFormShown:!1,taskDetailsShown:!1,tasks:[],task:{},index:null}},created:function(){var t=r(o.a.mark(function t(){var e;return o.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.getAllTasks();case 2:e=new URL(location.href).searchParams.get("id"),this.task=this.tasks.find(function(t){return t.id===parseInt(e)}),e&&(this.taskDetailsShown=!0);case 5:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}(),methods:{showCreateTaskForm:function(){var t=this;this.createTaskFormShown=!0,this.$nextTick(function(){t.$refs.taskform.$refs.focusInput.focus()})},closeCreateTaskForm:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;t&&this.tasks.push(t),this.createTaskFormShown=!1},getAllTasks:function(){var t=r(o.a.mark(function t(){var e,n;return o.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,!("tasks"===this.activeTab&&this.tasks.length<1)){t.next=8;break}return t.next=4,axios({url:"/tasks",params:{resource_type:this.resourceType,resource_id:this.resource.id}});case 4:return e=t.sent,n=e.data,this.tasks=n.tasks,t.abrupt("return",this.tasks);case 8:t.next=13;break;case 10:t.prev=10,t.t0=t.catch(0),console.error(t.t0);case 13:case"end":return t.stop()}},t,this,[[0,10]])}));return function(){return t.apply(this,arguments)}}(),showTaskDetails:function(t){var e=this;this.index=t,this.task=this.tasks[t],void 0===this.task.user.username?axios.get("/users").then(function(t){for(var n=0;n<t.data.users.length;n++)t.data.users[n].id===e.task.user.id&&(e.task.user.username=t.data.users[n].username,e.task.user.name=t.data.users[n].name);e.taskDetailsShown=!0}).catch(function(t){console.log(t.response.data.message)}):this.taskDetailsShown=!0},closeTaskDetails:function(){this.taskDetailsShown=!1,this.task={}},deleteTask:function(t){this.tasks.splice(t,1)}},watch:{activeTab:"getAllTasks"}}},Op1H:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW");e.default={data:function(){return{user:navbar.user,token:Laravel.csrfToken,url:navbar.navUrl,notificationShown:!1,unreadMessage:!1,faEnvelope:r.m,faCircle:r.g}},created:function(){EventBus.$on("new-direct-message",this.showIndicator)},beforeDestroy:function(){EventBus.$off("new-direct-message",this.showIndicator)},methods:{showMessageBox:function(){this.unreadMessage=!1,EventBus.$emit("show-message-box")},showIndicator:function(){this.unreadMessage=!0}}}},RPMJ:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={props:{show:{type:Boolean,default:!1},members:{type:Array,required:!0}},methods:{closeModal:function(){this.$emit("close")}}}},RrJr:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW"),i=null;e.default={props:{message:{required:!0,type:Object},user:{required:!0,type:Object},index:{required:!0,type:Number}},data:function(){return{dropdownMenuShown:!1,faEllipsisH:r.l}},computed:{displayDate:function(){return!this.message.system&&this.showDate(this.message.created_at)}},methods:{deleteMessage:function(){var t=this;axios.delete("/messages/"+this.message.id).then(function(e){t.$emit("deleted",t.index),t.dropdownMenuShown=!1,EventBus.$emit("notification",e.data.message,e.data.status)}).catch(function(e){t.dropdownMenuShown=!1,EventBus.$emit("notification",e.response.data.message,e.response.data.status)})},toggleMessageMenu:function(){this.dropdownMenuShown=!this.dropdownMenuShown},hideMessageMenu:function(){this.dropdownMenuShown=!1},showDate:function(t){var e=luxon.DateTime.fromSQL(t).toLocaleString(luxon.DateTime.DATE_MED);return(null===i||i!==e)&&(i=e,!0)},getDate:function(t){return luxon.DateTime.fromSQL(t).toLocaleString(luxon.DateTime.DATE_MED)},getTime:function(t){return this.user.timezone?luxon.DateTime.fromSQL(t,{zone:"UTC"}).setZone(this.user.timezone).toLocaleString(luxon.DateTime.TIME_SIMPLE):luxon.DateTime.fromSQL(t,{zone:"UTC"}).setZone("local").toLocaleString(luxon.DateTime.TIME_SIMPLE)}}}},RvPm:function(t,e,n){(function(n){var r,i,o;i=[],void 0===(o="function"==typeof(r=function(){function t(){a.clear(),s.clear(),c=[],u=[]}function e(t){for(var e=-9007199254740991,n=t.length-1;n>=0;--n){var r=t[n];if(null!==r){var i=r.score;i>e&&(e=i)}}return-9007199254740991===e?null:e}function r(t,e){var n=t[e];if(void 0!==n)return n;var r=e;Array.isArray(e)||(r=e.split("."));for(var i=r.length,o=-1;t&&++o<i;)t=t[r[o]];return t}function i(t){return"object"==typeof t}var o="undefined"==typeof window,a=new Map,s=new Map,l=[];l.total=0;var c=[],u=[],f=function(){function t(){for(var t=0,r=e[t],i=1;i<n;){var o=i+1;t=i,o<n&&e[o].score<e[i].score&&(t=o),e[t-1>>1]=e[t],i=1+(t<<1)}for(var a=t-1>>1;t>0&&r.score<e[a].score;a=(t=a)-1>>1)e[t]=e[a];e[t]=r}var e=[],n=0,r={};return r.add=function(t){var r=n;e[n++]=t;for(var i=r-1>>1;r>0&&t.score<e[i].score;i=(r=i)-1>>1)e[r]=e[i];e[r]=t},r.poll=function(){if(0!==n){var r=e[0];return e[0]=e[--n],t(),r}},r.peek=function(t){if(0!==n)return e[0]},r.replaceTop=function(n){e[0]=n,t()},r},d=f();return function h(p){var v={single:function(t,e,n){return t?(i(t)||(t=v.getPreparedSearch(t)),e?(i(e)||(e=v.getPrepared(e)),((n&&void 0!==n.allowTypo?n.allowTypo:!p||void 0===p.allowTypo||p.allowTypo)?v.algorithm:v.algorithmNoTypo)(t,e,t[0])):null):null},go:function(t,n,o){if(!t)return l;var a=(t=v.prepareSearch(t))[0],s=o&&o.threshold||p&&p.threshold||-9007199254740991,c=o&&o.limit||p&&p.limit||9007199254740991,u=(o&&void 0!==o.allowTypo?o.allowTypo:!p||void 0===p.allowTypo||p.allowTypo)?v.algorithm:v.algorithmNoTypo,f=0,h=0,g=n.length;if(o&&o.keys)for(var m=o.scoreFn||e,y=o.keys,b=y.length,w=g-1;w>=0;--w){for(var _=n[w],x=new Array(b),k=b-1;k>=0;--k)(A=r(_,O=y[k]))?(i(A)||(A=v.getPrepared(A)),x[k]=u(t,A,a)):x[k]=null;x.obj=_;var q=m(x);null!==q&&(q<s||(x.score=q,f<c?(d.add(x),++f):(++h,q>d.peek().score&&d.replaceTop(x))))}else if(o&&o.key){var O=o.key;for(w=g-1;w>=0;--w)(A=r(_=n[w],O))&&(i(A)||(A=v.getPrepared(A)),null!==(C=u(t,A,a))&&(C.score<s||(C={target:C.target,_targetLowerCodes:null,_nextBeginningIndexes:null,score:C.score,indexes:C.indexes,obj:_},f<c?(d.add(C),++f):(++h,C.score>d.peek().score&&d.replaceTop(C)))))}else for(w=g-1;w>=0;--w){var A,C;(A=n[w])&&(i(A)||(A=v.getPrepared(A)),null!==(C=u(t,A,a))&&(C.score<s||(f<c?(d.add(C),++f):(++h,C.score>d.peek().score&&d.replaceTop(C)))))}if(0===f)return l;var E=new Array(f);for(w=f-1;w>=0;--w)E[w]=d.poll();return E.total=f+h,E},goAsync:function(t,a,s){var c=!1,u=new Promise(function(u,d){function h(){if(c)return d("canceled");var f=Date.now();if(s&&s.keys)for(var p=s.scoreFn||e,q=s.keys,O=q.length;y>=0;--y){for(var A=a[y],C=new Array(O),E=O-1;E>=0;--E)(N=r(A,T=q[E]))?(i(N)||(N=v.getPrepared(N)),C[E]=_(t,N,g)):C[E]=null;C.obj=A;var S=p(C);if(null!==S&&!(S<b)&&(C.score=S,x<w?(m.add(C),++x):(++k,S>m.peek().score&&m.replaceTop(C)),y%1e3==0&&Date.now()-f>=10))return void(o?n(h):setTimeout(h))}else if(s&&s.key){for(var T=s.key;y>=0;--y)if((N=r(A=a[y],T))&&(i(N)||(N=v.getPrepared(N)),null!==(j=_(t,N,g))&&!(j.score<b)&&(j={target:j.target,_targetLowerCodes:null,_nextBeginningIndexes:null,score:j.score,indexes:j.indexes,obj:A},x<w?(m.add(j),++x):(++k,j.score>m.peek().score&&m.replaceTop(j)),y%1e3==0&&Date.now()-f>=10)))return void(o?n(h):setTimeout(h))}else for(;y>=0;--y){var N,j;if((N=a[y])&&(i(N)||(N=v.getPrepared(N)),null!==(j=_(t,N,g))&&!(j.score<b)&&(x<w?(m.add(j),++x):(++k,j.score>m.peek().score&&m.replaceTop(j)),y%1e3==0&&Date.now()-f>=10)))return void(o?n(h):setTimeout(h))}if(0===x)return u(l);for(var M=new Array(x),P=x-1;P>=0;--P)M[P]=m.poll();M.total=x+k,u(M)}if(!t)return u(l);var g=(t=v.prepareSearch(t))[0],m=f(),y=a.length-1,b=s&&s.threshold||p&&p.threshold||-9007199254740991,w=s&&s.limit||p&&p.limit||9007199254740991,_=(s&&void 0!==s.allowTypo?s.allowTypo:!p||void 0===p.allowTypo||p.allowTypo)?v.algorithm:v.algorithmNoTypo,x=0,k=0;o?n(h):h()});return u.cancel=function(){c=!0},u},highlight:function(t,e,n){if(null===t)return null;void 0===e&&(e="<b>"),void 0===n&&(n="</b>");for(var r="",i=0,o=!1,a=t.target,s=a.length,l=t.indexes,c=0;c<s;++c){var u=a[c];if(l[i]===c){if(++i,o||(o=!0,r+=e),i===l.length){r+=u+n+a.substr(c+1);break}}else o&&(o=!1,r+=n);r+=u}return r},prepare:function(t){if(t)return{target:t,_targetLowerCodes:v.prepareLowerCodes(t),_nextBeginningIndexes:null,score:null,indexes:null,obj:null}},prepareSlow:function(t){if(t)return{target:t,_targetLowerCodes:v.prepareLowerCodes(t),_nextBeginningIndexes:v.prepareNextBeginningIndexes(t),score:null,indexes:null,obj:null}},prepareSearch:function(t){if(t)return v.prepareLowerCodes(t)},getPrepared:function(t){if(t.length>999)return v.prepare(t);var e=a.get(t);return void 0!==e?e:(e=v.prepare(t),a.set(t,e),e)},getPreparedSearch:function(t){if(t.length>999)return v.prepareSearch(t);var e=s.get(t);return void 0!==e?e:(e=v.prepareSearch(t),s.set(t,e),e)},algorithm:function(t,e,n){for(var r=e._targetLowerCodes,i=t.length,o=r.length,a=0,s=0,l=0,f=0;;){if(n===r[s]){if(c[f++]=s,++a===i)break;n=t[0===l?a:l===a?a+1:l===a-1?a-1:a]}if(++s>=o)for(;;){if(a<=1)return null;if(0===l){if(n===t[--a])continue;l=a}else{if(1===l)return null;if((n=t[1+(a=--l)])===t[a])continue}s=c[(f=a)-1]+1;break}}a=0;var d=0,h=!1,p=0,g=e._nextBeginningIndexes;null===g&&(g=e._nextBeginningIndexes=v.prepareNextBeginningIndexes(e.target));var m=s=0===c[0]?0:g[c[0]-1];if(s!==o)for(;;)if(s>=o){if(a<=0){if(++d>i-2)break;if(t[d]===t[d+1])continue;s=m;continue}--a,s=g[u[--p]]}else if(t[0===d?a:d===a?a+1:d===a-1?a-1:a]===r[s]){if(u[p++]=s,++a===i){h=!0;break}++s}else s=g[s];if(h)var y=u,b=p;else y=c,b=f;for(var w=0,_=-1,x=0;x<i;++x)_!==(s=y[x])-1&&(w-=s),_=s;for(h?0!==d&&(w+=-20):(w*=1e3,0!==l&&(w+=-20)),w-=o-i,e.score=w,e.indexes=new Array(b),x=b-1;x>=0;--x)e.indexes[x]=y[x];return e},algorithmNoTypo:function(t,e,n){for(var r=e._targetLowerCodes,i=t.length,o=r.length,a=0,s=0,l=0;;){if(n===r[s]){if(c[l++]=s,++a===i)break;n=t[a]}if(++s>=o)return null}a=0;var f=!1,d=0,h=e._nextBeginningIndexes;if(null===h&&(h=e._nextBeginningIndexes=v.prepareNextBeginningIndexes(e.target)),(s=0===c[0]?0:h[c[0]-1])!==o)for(;;)if(s>=o){if(a<=0)break;--a,s=h[u[--d]]}else if(t[a]===r[s]){if(u[d++]=s,++a===i){f=!0;break}++s}else s=h[s];if(f)var p=u,g=d;else p=c,g=l;for(var m=0,y=-1,b=0;b<i;++b)y!==(s=p[b])-1&&(m-=s),y=s;for(f||(m*=1e3),m-=o-i,e.score=m,e.indexes=new Array(g),b=g-1;b>=0;--b)e.indexes[b]=p[b];return e},prepareLowerCodes:function(t){for(var e=t.length,n=[],r=t.toLowerCase(),i=0;i<e;++i)n[i]=r.charCodeAt(i);return n},prepareBeginningIndexes:function(t){for(var e=t.length,n=[],r=0,i=!1,o=!1,a=0;a<e;++a){var s=t.charCodeAt(a),l=s>=65&&s<=90,c=l||s>=97&&s<=122||s>=48&&s<=57,u=l&&!i||!o||!c;i=l,o=c,u&&(n[r++]=a)}return n},prepareNextBeginningIndexes:function(t){for(var e=t.length,n=v.prepareBeginningIndexes(t),r=[],i=n[0],o=0,a=0;a<e;++a)i>a?r[a]=i:(i=n[++o],r[a]=void 0===i?e:i);return r},cleanup:t,new:h};return v}()})?r.apply(e,i):r)||(t.exports=o)}).call(e,n("162o").setImmediate)},SldL:function(t,e){!function(e){"use strict";function n(t,e,n,o){var a=e&&e.prototype instanceof i?e:i,s=Object.create(a.prototype),l=new d(o||[]);return s._invoke=function(t,e,n){var i=q;return function(o,a){if(i===A)throw new Error("Generator is already running");if(i===C){if("throw"===o)throw a;return p()}for(n.method=o,n.arg=a;;){var s=n.delegate;if(s){var l=c(s,n);if(l){if(l===E)continue;return l}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if(i===q)throw i=C,n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);i=A;var u=r(t,e,n);if("normal"===u.type){if(i=n.done?C:O,u.arg===E)continue;return{value:u.arg,done:n.done}}"throw"===u.type&&(i=C,n.method="throw",n.arg=u.arg)}}}(t,n,l),s}function r(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}function i(){}function o(){}function a(){}function s(t){["next","throw","return"].forEach(function(e){t[e]=function(t){return this._invoke(e,t)}})}function l(t){var e;this._invoke=function(n,i){function o(){return new Promise(function(e,o){!function e(n,i,o,a){var s=r(t[n],t,i);if("throw"!==s.type){var l=s.arg,c=l.value;return c&&"object"==typeof c&&m.call(c,"__await")?Promise.resolve(c.__await).then(function(t){e("next",t,o,a)},function(t){e("throw",t,o,a)}):Promise.resolve(c).then(function(t){l.value=t,o(l)},a)}a(s.arg)}(n,i,e,o)})}return e=e?e.then(o,o):o()}}function c(t,e){var n=t.iterator[e.method];if(n===v){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=v,c(t,e),"throw"===e.method))return E;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return E}var i=r(n,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,E;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=v),e.delegate=null,E):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,E)}function u(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function f(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function d(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(u,this),this.reset(!0)}function h(t){if(t){var e=t[b];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var n=-1,r=function e(){for(;++n<t.length;)if(m.call(t,n))return e.value=t[n],e.done=!1,e;return e.value=v,e.done=!0,e};return r.next=r}}return{next:p}}function p(){return{value:v,done:!0}}var v,g=Object.prototype,m=g.hasOwnProperty,y="function"==typeof Symbol?Symbol:{},b=y.iterator||"@@iterator",w=y.asyncIterator||"@@asyncIterator",_=y.toStringTag||"@@toStringTag",x="object"==typeof t,k=e.regeneratorRuntime;if(k)x&&(t.exports=k);else{(k=e.regeneratorRuntime=x?t.exports:{}).wrap=n;var q="suspendedStart",O="suspendedYield",A="executing",C="completed",E={},S={};S[b]=function(){return this};var T=Object.getPrototypeOf,N=T&&T(T(h([])));N&&N!==g&&m.call(N,b)&&(S=N);var j=a.prototype=i.prototype=Object.create(S);o.prototype=j.constructor=a,a.constructor=o,a[_]=o.displayName="GeneratorFunction",k.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===o||"GeneratorFunction"===(e.displayName||e.name))},k.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,a):(t.__proto__=a,_ in t||(t[_]="GeneratorFunction")),t.prototype=Object.create(j),t},k.awrap=function(t){return{__await:t}},s(l.prototype),l.prototype[w]=function(){return this},k.AsyncIterator=l,k.async=function(t,e,r,i){var o=new l(n(t,e,r,i));return k.isGeneratorFunction(e)?o:o.next().then(function(t){return t.done?t.value:o.next()})},s(j),j[_]="Generator",j[b]=function(){return this},j.toString=function(){return"[object Generator]"},k.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},k.values=h,d.prototype={constructor:d,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=v,this.done=!1,this.delegate=null,this.method="next",this.arg=v,this.tryEntries.forEach(f),!t)for(var e in this)"t"===e.charAt(0)&&m.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=v)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){function e(e,r){return o.type="throw",o.arg=t,n.next=e,r&&(n.method="next",n.arg=v),!!r}if(this.done)throw t;for(var n=this,r=this.tryEntries.length-1;r>=0;--r){var i=this.tryEntries[r],o=i.completion;if("root"===i.tryLoc)return e("end");if(i.tryLoc<=this.prev){var a=m.call(i,"catchLoc"),s=m.call(i,"finallyLoc");if(a&&s){if(this.prev<i.catchLoc)return e(i.catchLoc,!0);if(this.prev<i.finallyLoc)return e(i.finallyLoc)}else if(a){if(this.prev<i.catchLoc)return e(i.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return e(i.finallyLoc)}}}},abrupt:function(t,e){for(var n=this.tryEntries.length-1;n>=0;--n){var r=this.tryEntries[n];if(r.tryLoc<=this.prev&&m.call(r,"finallyLoc")&&this.prev<r.finallyLoc){var i=r;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var o=i?i.completion:{};return o.type=t,o.arg=e,i?(this.method="next",this.next=i.finallyLoc,E):this.complete(o)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),E},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),f(n),E}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var i=r.arg;f(n)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:h(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=v),E}}}}(function(){return this}()||Function("return this")())},U0v6:function(t,e,n){(function(t){!function(e,n){"use strict";function r(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=(e.children||[]).map(r.bind(null,t)),a=Object.keys(e.attributes||{}).reduce(function(t,n){var r=e.attributes[n];switch(n){case"class":t.class=r.split(/\s+/).reduce(function(t,e){return t[e]=!0,t},{});break;case"style":t.style=r.split(";").map(function(t){return t.trim()}).filter(function(t){return t}).reduce(function(t,e){var n=e.indexOf(":"),r=l.camelize(e.slice(0,n)),i=e.slice(n+1).trim();return t[r]=i,t},{});break;default:t.attrs[n]=r}return t},{class:{},style:{},attrs:{}}),s=i.class,c=void 0===s?{}:s,u=i.style,h=void 0===u?{}:u,p=i.attrs,v=void 0===p?{}:p,g=d(i,["class","style","attrs"]);return"string"==typeof e?e:t(e.tag,f({class:function(){for(var t=arguments.length,e=Array(t),n=0;n<t;n++)e[n]=arguments[n];return e.reduce(function(t,e){return Array.isArray(e)?t=t.concat(e):t.push(e),t},[])}(a.class,c),style:f({},a.style,h),attrs:f({},a.attrs,v)},g,{props:n}),o)}function i(t,e){return Array.isArray(e)&&e.length>0||!Array.isArray(e)&&e?u({},t,e):{}}function o(t){return null===t?null:"object"===(void 0===t?"undefined":c(t))&&t.prefix&&t.iconName?t:Array.isArray(t)&&2===t.length?{prefix:t[0],iconName:t[1]}:"string"==typeof t?{prefix:"fas",iconName:t}:void 0}var a,s="undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{},l=(function(t){var e,n,r,i,o,a,l,c,u,f,d,h,p,v,g;e=s,n=function(t,e,r){if(!c(e)||f(e)||d(e)||h(e)||l(e))return e;var i,o=0,a=0;if(u(e))for(i=[],a=e.length;o<a;o++)i.push(n(t,e[o],r));else for(var s in i={},e)Object.prototype.hasOwnProperty.call(e,s)&&(i[t(s,r)]=n(t,e[s],r));return i},r=function(t){return p(t)?t:(t=t.replace(/[\-_\s]+(.)?/g,function(t,e){return e?e.toUpperCase():""})).substr(0,1).toLowerCase()+t.substr(1)},i=function(t){var e=r(t);return e.substr(0,1).toUpperCase()+e.substr(1)},o=function(t,e){return function(t,e){var n=(e=e||{}).separator||"_",r=e.split||/(?=[A-Z])/;return t.split(r).join(n)}(t,e).toLowerCase()},a=Object.prototype.toString,l=function(t){return"function"==typeof t},c=function(t){return t===Object(t)},u=function(t){return"[object Array]"==a.call(t)},f=function(t){return"[object Date]"==a.call(t)},d=function(t){return"[object RegExp]"==a.call(t)},h=function(t){return"[object Boolean]"==a.call(t)},p=function(t){return(t-=0)==t},v=function(t,e){var n=e&&"process"in e?e.process:e;return"function"!=typeof n?t:function(e,r){return n(e,t,r)}},g={camelize:r,decamelize:o,pascalize:i,depascalize:o,camelizeKeys:function(t,e){return n(v(r,e),t)},decamelizeKeys:function(t,e){return n(v(o,e),t,e)},pascalizeKeys:function(t,e){return n(v(i,e),t)},depascalizeKeys:function(){return this.decamelizeKeys.apply(this,arguments)}},t.exports?t.exports=g:e.humps=g}(a={exports:{}},a.exports),a.exports),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=function(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t},f=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},d=function(t,e){var n={};for(var r in t)e.indexOf(r)>=0||Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n},h=!1;try{h=!0}catch(t){}var p={name:"FontAwesomeIcon",functional:!0,props:{border:{type:Boolean,default:!1},fixedWidth:{type:Boolean,default:!1},flip:{type:String,default:null,validator:function(t){return["horizontal","vertical","both"].indexOf(t)>-1}},icon:{type:[Object,Array,String],required:!0},mask:{type:[Object,Array,String],default:null},listItem:{type:Boolean,default:!1},pull:{type:String,default:null,validator:function(t){return["right","left"].indexOf(t)>-1}},pulse:{type:Boolean,default:!1},rotation:{type:Number,default:null,validator:function(t){return[90,180,270].indexOf(t)>-1}},size:{type:String,default:null,validator:function(t){return["lg","xs","sm","1x","2x","3x","4x","5x","6x","7x","8x","9x","10x"].indexOf(t)>-1}},spin:{type:Boolean,default:!1},transform:{type:[String,Object],default:null},symbol:{type:[Boolean,String],default:!1}},render:function(t,e){var a=e.props,s=a.icon,l=a.mask,c=a.symbol,d=o(s),p=i("classes",function(t){var e,n=(e={"fa-spin":t.spin,"fa-pulse":t.pulse,"fa-fw":t.fixedWidth,"fa-border":t.border,"fa-li":t.listItem,"fa-flip-horizontal":"horizontal"===t.flip||"both"===t.flip,"fa-flip-vertical":"vertical"===t.flip||"both"===t.flip},u(e,"fa-"+t.size,null!==t.size),u(e,"fa-rotate-"+t.rotation,null!==t.rotation),u(e,"fa-pull-"+t.pull,null!==t.pull),e);return Object.keys(n).map(function(t){return n[t]?t:null}).filter(function(t){return t})}(a)),v=i("transform","string"==typeof a.transform?n.parse.transform(a.transform):a.transform),g=i("mask",o(l)),m=n.icon(d,f({},p,v,g,{symbol:c}));if(!m)return function(){var t;!h&&console&&"function"==typeof console.error&&(t=console).error.apply(t,arguments)}("Could not find one or more icon(s)",d,g);var y=m.abstract;return r.bind(null,t)(y[0],{},e.data)}},v={name:"FontAwesomeLayers",functional:!0,props:{fixedWidth:{type:Boolean,default:!1}},render:function(t,e){var r,i,o=n.config.familyPrefix,a=e.data.staticClass,s=[o+"-layers"].concat(function(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)}(e.props.fixedWidth?[o+"-fw"]:[]));return t("div",f({},e.data,{staticClass:(r=a,i=s,(0===(r||"").length?[]:[r]).concat(i).join(" "))}),e.children)}},g={name:"FontAwesomeLayersText",functional:!0,props:{value:{type:[String,Number],default:""},transform:{type:[String,Object],default:null}},render:function(t,e){var o=e.props,a=i("transform","string"==typeof o.transform?n.parse.transform(o.transform):o.transform),s=n.text(o.value.toString(),f({},a)).abstract;return r.bind(null,t)(s[0],{},e.data)}};e.FontAwesomeIcon=p,e.FontAwesomeLayers=v,e.FontAwesomeLayersText=g,Object.defineProperty(e,"__esModule",{value:!0})}(e,n("C/JF"))}).call(e,n("DuR2"))},UJh6:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"w-full",class:{hidden:"messages"!=t.activeTab}},[n("div",{staticClass:"flex flex-col bg-white mx-auto my-8 max-w-md shadow rounded"},[n("div",{staticClass:"text-grey-dark bg-white shadow p-4 text-xl flex flex-row items-center"},[n("div",[t._v("\n "+t._s(t._f("localize")("Currently in room"))+":\n ")]),t._v(" "),t._l(t.users,function(e){return[n("img",{staticClass:"w-8 h-8 rounded-full mr-2 ml-4",attrs:{src:t.generateUrl(e.avatar),alt:""}})]})],2),t._v(" "),n("div",{staticClass:"h-50-vh overflow-y-auto",attrs:{id:"message-box"}},[n("div",{staticClass:"mb-6"},t._l(t.messages,function(e,r){return n("message",{key:r,attrs:{message:e,user:t.user,index:r},on:{deleted:t.deleteMessage}})}))]),t._v(" "),n("div",{staticClass:"relative bg-grey-light"},[n("div",{staticClass:"static text-center p-8"},[n("div",{staticClass:"relative"},[n("user-suggestion-box",{staticClass:"absolute mb-2 w-full pin-b",attrs:{users:t.members,name:t.name,suggestionShown:t.suggestionShown,suggestionSelected:t.suggestionSelected,suggestionHighlightIndex:t.suggestionHighlightIndex,suggestionHighlightDirection:t.suggestionHighlightDirection,suggestionHighlightDirectionInverted:!0},on:{selected:t.userSelected}})],1),t._v(" "),n("textarea",{directives:[{name:"model",rawName:"v-model",value:t.message,expression:"message"}],ref:"messageTextarea",staticClass:"static textarea resize-none rounded w-full p-4 text-grey-darker",style:{height:t.messageTextareaHeight},attrs:{id:"send-message",placeholder:t._f("localize")("write your message here"),rows:"1"},domProps:{value:t.message},on:{keyup:function(e){t.checkForMention(e)},keydown:[function(e){t.mentionHighlightMove(e)},function(e){if(!("button"in e)&&t._k(e.keyCode,"enter",13,e.key))return null;e.preventDefault(),t.sendMessage(e)}],focus:function(e){t.clearTitleNotification()},input:function(e){e.target.composing||(t.message=e.target.value)}}})])])])])},staticRenderFns:[]}},"VU/8":function(t,e){t.exports=function(t,e,n,r,i,o){var a,s=t=t||{},l=typeof t.default;"object"!==l&&"function"!==l||(a=t,s=t.default);var c,u="function"==typeof s?s.options:s;if(e&&(u.render=e.render,u.staticRenderFns=e.staticRenderFns,u._compiled=!0),n&&(u.functional=!0),i&&(u._scopeId=i),o?(c=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(o)},u._ssrRegister=c):r&&(c=r),c){var f=u.functional,d=f?u.render:u.beforeCreate;f?(u._injectStyles=c,u.render=function(t,e){return c.call(e),d(t,e)}):u.beforeCreate=d?[].concat(d,c):[c]}return{esModule:a,exports:s,options:u}}},WRGp:function(t,e,n){"use strict";var r=n("iuzX"),i=n.n(r),o=n("U0v6"),a=(n.n(o),n("dDoS")),s=n.n(a);window.Vue=n("I3G/"),window.axios=n("mtWM"),window.luxon=n("H9QG"),window.axios.defaults.headers.common={"X-CSRF-TOKEN":window.Laravel.csrfToken,"X-Requested-With":"XMLHttpRequest"},"undefined"!=typeof io&&(window.Echo=new i.a({broadcaster:"socket.io",host:window.location.hostname+":6001"})),window.Vue.mixin({methods:{generateUrl:function(t){return t?(t=t.toString(),window.location.protocol+"//"+window.location.host+"/"+t):"http://"+window.location.host+"/image/avatar.jpg"}}}),window.Vue.filter("localize",function(t){return t?(t=t.toString(),window.lang[t]?window.lang[t]:t):""}),window.Vue.directive("click-outside",s.a),window.Vue.component("font-awesome-icon",o.FontAwesomeIcon),window.EventBus=new Vue},Wfqs:function(t,e,n){var r=n("VU/8")(n("aWzK"),n("xwHu"),!1,null,null,null);t.exports=r.exports},WgZf:function(t,e,n){"use strict";function r(t){return function(){var e=t.apply(this,arguments);return new Promise(function(t,n){return function r(i,o){try{var a=e[i](o),s=a.value}catch(t){return void n(t)}if(!a.done)return Promise.resolve(s).then(function(t){r("next",t)},function(t){r("throw",t)});t(s)}("next")})}}Object.defineProperty(e,"__esModule",{value:!0});var i=n("Xxa5"),o=n.n(i),a=n("icw/"),s=n.n(a),l=n("2eDP"),c=n.n(l);e.default={components:{createDiscussionForm:s.a,discussionDetails:c.a},props:{resource:{required:!0,type:Object},resourceType:{required:!0,type:String},activeTab:{required:!0,type:String}},data:function(){return{createDiscussionFormShown:!1,discussions:[],discussion:{},discussionDetailsShown:!1,index:null}},created:function(){var t=r(o.a.mark(function t(){var e;return o.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:return t.next=2,this.getAllDiscussions();case 2:e=new URL(location.href).searchParams.get("id"),this.discussion=this.discussions.find(function(t){return t.id===parseInt(e)}),e&&(this.discussionDetailsShown=!0);case 5:case"end":return t.stop()}},t,this)}));return function(){return t.apply(this,arguments)}}(),methods:{showCreateDiscussionForm:function(){var t=this;this.createDiscussionFormShown=!0,this.$nextTick(function(){t.$refs.discussionForm.$refs.inputFocus.focus()})},closeCreateDiscussionForm:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;t&&this.discussions.push(t),this.createDiscussionFormShown=!1},getAllDiscussions:function(){var t=r(o.a.mark(function t(){var e,n;return o.a.wrap(function(t){for(;;)switch(t.prev=t.next){case 0:if(t.prev=0,!("discussions"===this.activeTab&&this.discussions.length<1)){t.next=8;break}return t.next=4,axios({url:"/discussions",params:{resource_type:this.resourceType,resource_id:this.resource.id}});case 4:return e=t.sent,n=e.data,this.discussions=n.discussions,t.abrupt("return",this.discussions);case 8:t.next=13;break;case 10:t.prev=10,t.t0=t.catch(0),console.error(t.t0.response.data.message);case 13:case"end":return t.stop()}},t,this,[[0,10]])}));return function(){return t.apply(this,arguments)}}(),showDiscussionDetails:function(t){this.index=t,this.discussion=this.discussions[t],this.discussionDetailsShown=!0},closeDiscussionDetails:function(){this.discussionDetailsShown=!1,this.discussion={}},deleteDiscussion:function(t){this.discussions.splice(t,1)}},watch:{
activeTab:"getAllDiscussions"}}},XILU:function(t,e){t.exports=function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="/",e(e.s=76)}([function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e,n){var r=n(53),i=n(14);t.exports=function(t){return r(i(t))}},function(t,e,n){t.exports=!n(8)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e,n){var r=n(5),i=n(11);t.exports=n(3)?function(t,e,n){return r.f(t,e,i(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){var r=n(7),i=n(30),o=n(23),a=Object.defineProperty;e.f=n(3)?Object.defineProperty:function(t,e,n){if(r(t),e=o(e,!0),r(n),i)try{return a(t,e,n)}catch(t){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var r=n(21)("wks"),i=n(12),o=n(0).Symbol,a="function"==typeof o;(t.exports=function(t){return r[t]||(r[t]=a&&o[t]||(a?o:i)("Symbol."+t))}).store=r},function(t,e,n){var r=n(9);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){var r=n(35),i=n(15);t.exports=Object.keys||function(t){return r(t,i)}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e){var n=t.exports={version:"2.4.0"};"number"==typeof __e&&(__e=n)},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e){t.exports={}},function(t,e){t.exports=!0},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,n){var r=n(5).f,i=n(1),o=n(6)("toStringTag");t.exports=function(t,e,n){t&&!i(t=n?t:t.prototype,o)&&r(t,o,{configurable:!0,value:e})}},function(t,e,n){var r=n(21)("keys"),i=n(12);t.exports=function(t){return r[t]||(r[t]=i(t))}},function(t,e,n){var r=n(0),i=r["__core-js_shared__"]||(r["__core-js_shared__"]={});t.exports=function(t){return i[t]||(i[t]={})}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e,n){var r=n(9);t.exports=function(t,e){if(!r(t))return t;var n,i;if(e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;if("function"==typeof(n=t.valueOf)&&!r(i=n.call(t)))return i;if(!e&&"function"==typeof(n=t.toString)&&!r(i=n.call(t)))return i;throw TypeError("Can't convert object to primitive value")}},function(t,e,n){var r=n(0),i=n(13),o=n(17),a=n(25),s=n(5).f;t.exports=function(t){var e=i.Symbol||(i.Symbol=o?{}:r.Symbol||{});"_"==t.charAt(0)||t in e||s(e,t,{value:a.f(t)})}},function(t,e,n){e.f=n(6)},function(t,e,n){"use strict";e.a={translations:{af:{language:"Afrikaans",months:{original:["Januarie","Februarie","Maart","April","Mei","Junie","Julie","Augustus","September","Oktober","November","Desember"],abbr:["Jan","Feb","Mrt","Apr","Mei","Jun","Jul","Aug","Sep","Okt","Nov","Des"]},days:["So.","Ma.","Di.","Wo.","Do.","Vr.","Sa."]},ar:{language:"Arabic",rtl:!0,months:{original:["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوڤمبر","ديسمبر"],abbr:["يناير","فبراير","مارس","أبريل","مايو","يونيو","يوليو","أغسطس","سبتمبر","أكتوبر","نوڤمبر","ديسمبر"]},days:["أحد","إثنين","ثلاثاء","أربعاء","خميس","جمعة","سبت"]},bg:{language:"Bulgarian",months:{original:["Януари","Февруари","Март","Април","Май","Юни","Юли","Август","Септември","Октомври","Ноември","Декември"],abbr:["Ян","Фев","Мар","Апр","Май","Юни","Юли","Авг","Сеп","Окт","Ное","Дек"]},days:["Нд","Пн","Вт","Ср","Чт","Пт","Сб"]},bs:{language:"Bosnian",months:{original:["Januar","Februar","Mart","April","Maj","Juni","Juli","Avgust","Septembar","Oktobar","Novembar","Decembar"],abbr:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"]},days:["Ned","Pon","Uto","Sri","Čet","Pet","Sub"]},cs:{language:"Czech",months:{original:["leden","únor","březen","duben","květen","červen","červenec","srpen","září","říjen","listopad","prosinec"],abbr:["led","úno","bře","dub","kvě","čer","čec","srp","zář","říj","lis","pro"]},days:["ne","po","út","st","čt","pá","so"]},da:{language:"Danish",months:{original:["Januar","Februar","Marts","April","Maj","Juni","Juli","August","September","Oktober","November","December"],abbr:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"]},days:["Sø","Ma","Ti","On","To","Fr","Lø"]},de:{language:"German",months:{original:["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember"],abbr:["Jan","Feb","Mär","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez"]},days:["So.","Mo.","Di.","Mi.","Do.","Fr.","Sa."]},ee:{language:"Estonian",months:{original:["Jaanuar","Veebruar","Märts","Aprill","Mai","Juuni","Juuli","August","September","Oktoober","November","Detsember"],abbr:["Jaan","Veebr","Märts","Apr","Mai","Juuni","Juuli","Aug","Sept","Okt","Nov","Dets"]},days:["P","E","T","K","N","R","L"]},el:{language:"Greek",months:{original:["Ιανουάριος","Φεβρουάριος","Μάρτιος","Απρίλιος","Μάϊος","Ιούνιος","Ιούλιος","Αύγουστος","Σεπτέμβριος","Οκτώβριος","Νοέμβριος","Δεκέμβριος"],abbr:["Ιαν","Φεβ","Μαρ","Απρ","Μαι","Ιουν","Ιουλ","Αυγ","Σεπ","Οκτ","Νοε","Δεκ"]},days:["Κυρ","Δευ","Τρι","Τετ","Πεμ","Παρ","Σατ"]},en:{language:"English",months:{original:["January","February","March","April","May","June","July","August","September","October","November","December"],abbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},days:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},es:{language:"Spanish",months:{original:["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],abbr:["Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic"]},days:["Dom","Lun","Mar","Mié","Jue","Vie","Sab"]},ca:{language:"Catalan",months:{original:["Gener","Febrer","Març","Abril","Maig","Juny","Juliol","Agost","Setembre","Octubre","Novembre","Desembre"],abbr:["Gen","Feb","Mar","Abr","Mai","Jun","Jul","Ago","Set","Oct","Nov","Des"]},days:["Diu","Dil","Dmr","Dmc","Dij","Div","Dis"]},fi:{language:"Finish",months:{original:["tammikuu","helmikuu","maaliskuu","huhtikuu","toukokuu","kesäkuu","heinäkuu","elokuu","syyskuu","lokakuu","marraskuu","joulukuu"],abbr:["tammi","helmi","maalis","huhti","touko","kesä","heinä","elo","syys","loka","marras","joulu"]},days:["su","ma","ti","ke","to","pe","la"]},fr:{language:"French",months:{original:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"],abbr:["Jan","Fév","Mar","Avr","Mai","Juin","Juil","Août","Sep","Oct","Nov","Déc"]},days:["Dim","Lun","Mar","Mer","Jeu","Ven","Sam"]},ge:{language:"Georgia",months:{original:["იანვარი","თებერვალი","მარტი","აპრილი","მაისი","ივნისი","ივლისი","აგვისტო","სექტემბერი","ოქტომბერი","ნოემბერი","დეკემბერი"],abbr:["იან","თებ","მარ","აპრ","მაი","ივნ","ივლ","აგვ","სექ","ოქტ","ნოე","დეკ"]},days:["კვი","ორშ","სამ","ოთხ","ხუთ","პარ","შაბ"]},ja:{language:"Japanese",ymd:!0,months:{original:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],abbr:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"]},days:["日","月","火","水","木","金","土"]},he:{language:"Hebrew",rtl:!0,months:{original:["ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","נובמבר","דצמבר"],abbr:["ינו","פבר","מרץ","אפר","מאי","יונ","יול","אוג","ספט","אוק","נוב","דצמ"]},days:["א","ב","ג","ד","ה","ו","ש"]},hu:{language:"Hungarian",ymd:!0,months:{original:["Január","Február","Március","Április","Május","Június","Július","Augusztus","Szeptember","Október","November","December"],abbr:["Jan","Febr","Márc","Ápr","Máj","Jún","Júl","Aug","Szept","Okt","Nov","Dec"]},days:["Vas","Hét","Ke","Sze","Csü","Pén","Szo"]},hr:{language:"Croatian",months:{original:["Siječanj","Veljača","Ožujak","Travanj","Svibanj","Lipanj","Srpanj","Kolovoz","Rujan","Listopad","Studeni","Prosinac"],abbr:["Sij","Velj","Ožu","Tra","Svi","Lip","Srp","Kol","Ruj","Lis","Stu","Pro"]},days:["Ned","Pon","Uto","Sri","Čet","Pet","Sub"]},id:{language:"Indonesian",months:{original:["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","November","Desember"],abbr:["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agu","Sep","Okt","Nov","Des"]},days:["Min","Sen","Sel","Rab","Kam","Jum","Sab"]},it:{language:"Italian",months:{original:["Gennaio","Febbraio","Marzo","Aprile","Maggio","Giugno","Luglio","Agosto","Settembre","Ottobre","Novembre","Dicembre"],abbr:["Gen","Feb","Mar","Apr","Mag","Giu","Lug","Ago","Set","Ott","Nov","Dic"]},days:["Dom","Lun","Mar","Mer","Gio","Ven","Sab"]},is:{language:"Icelandic",months:{original:["Janúar","Febrúar","Mars","Apríl","Maí","Júní","Júlí","Ágúst","September","Október","Nóvember","Desember"],abbr:["Jan","Feb","Mars","Apr","Maí","Jún","Júl","Ágú","Sep","Okt","Nóv","Des"]},days:["Sun","Mán","Þri","Mið","Fim","Fös","Lau"]},fa:{language:"Persian",months:{original:["فروردین","اردیبهشت","خرداد","تیر","مرداد","شهریور","مهر","آبان","آذر","دی","بهمن","اسفند"],abbr:["فرو","ارد","خرد","تیر","مرد","شهر","مهر","آبا","آذر","دی","بهم","اسف"]},days:["یکشنبه","دوشنبه","سهشنبه","چهارشنبه","پنجشنبه","جمعه","شنبه"]},ko:{language:"Korean",ymd:!0,months:{original:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"],abbr:["1월","2월","3월","4월","5월","6월","7월","8월","9월","10월","11월","12월"]},days:["일","월","화","수","목","금","토"]},lt:{language:"Lithuanian",ymd:!0,months:{original:["Sausis","Vasaris","Kovas","Balandis","Gegužė","Birželis","Liepa","Rugpjūtis","Rugsėjis","Spalis","Lapkritis","Gruodis"],abbr:["Sau","Vas","Kov","Bal","Geg","Bir","Lie","Rugp","Rugs","Spa","Lap","Gru"]},days:["Sek","Pir","Ant","Tre","Ket","Pen","Šeš"]},lv:{language:"Latvian",months:{original:["Janvāris","Februāris","Marts","Aprīlis","Maijs","Jūnijs","Jūlijs","Augusts","Septembris","Oktobris","Novembris","Decembris"],abbr:["Jan","Feb","Mar","Apr","Mai","Jūn","Jūl","Aug","Sep","Okt","Nov","Dec"]},days:["Sv","Pr","Ot","Tr","Ce","Pk","Se"]},mn:{language:"Mongolia",ymd:!0,months:{original:["1 дүгээр сар","2 дугаар сар","3 дугаар сар","4 дүгээр сар","5 дугаар сар","6 дугаар сар","7 дугаар сар","8 дугаар сар","9 дүгээр сар","10 дугаар сар","11 дүгээр сар","12 дугаар сар"],abbr:["1-р сар","2-р сар","3-р сар","4-р сар","5-р сар","6-р сар","7-р сар","8-р сар","9-р сар","10-р сар","11-р сар","12-р сар"]},days:["Ня","Да","Мя","Лх","Пү","Ба","Бя"]},nl:{language:"Dutch",months:{original:["januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december"],abbr:["jan","feb","maa","apr","mei","jun","jul","aug","sep","okt","nov","dec"]},days:["zo","ma","di","wo","do","vr","za"]},"nb-no":{language:"Norwegian Bokmål",months:{original:["Januar","Februar","Mars","April","Mai","Juni","Juli","August","September","Oktober","November","Desember"],abbr:["Jan","Feb","Mar","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Des"]},days:["Sø","Ma","Ti","On","To","Fr","Lø"]},pl:{language:"Polish",months:{original:["Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień"],abbr:["Sty","Lut","Mar","Kwi","Maj","Cze","Lip","Sie","Wrz","Paź","Lis","Gru"]},days:["Nd","Pn","Wt","Śr","Czw","Pt","Sob"]},"pt-br":{language:"Brazilian",months:{original:["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"],abbr:["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"]},days:["Dom","Seg","Ter","Qua","Qui","Sex","Sab"]},ro:{language:"Romanian",months:{original:["Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","Noiembrie","Decembrie"],abbr:["Ian","Feb","Mar","Apr","Mai","Iun","Iul","Aug","Sep","Oct","Noi","Dec"]},days:["D","L","Ma","Mi","J","V","S"]},ru:{language:"Russian",months:{original:["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"],abbr:["Янв","Февр","Март","Апр","Май","Июнь","Июль","Авг","Сент","Окт","Нояб","Дек"]},days:["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]},sv:{language:"Swedish",months:{original:["Januari","Februari","Mars","April","Maj","Juni","Juli","Augusti","September","Oktober","November","December"],abbr:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Aug","Sep","Okt","Nov","Dec"]},days:["Sön","Mån","Tis","Ons","Tor","Fre","Lör"]},sk:{language:"Slovakian",months:{original:["január","február","marec","apríl","máj","jún","júl","august","september","október","november","december"],abbr:["jan","feb","mar","apr","máj","jún","júl","aug","sep","okt","nov","dec"]},days:["ne","po","ut","st","št","pi","so"]},"sl-si":{language:"Sloveian",months:{original:["Januar","Februar","Marec","April","Maj","Junij","Julij","Avgust","September","Oktober","November","December"],abbr:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"]},days:["Ned","Pon","Tor","Sre","Čet","Pet","Sob"]},sr:{language:"Serbian",months:{original:["Januar","Februar","Mart","April","Maj","Jun","Jul","Avgust","Septembar","Oktobar","Novembar","Decembar"],abbr:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"]},days:["Ned","Pon","Uto","Sre","Čet","Pet","Sub"]},"sr-Cyrl":{language:"Serbian in Cyrillic script",months:{original:["Јануар","Фебруар","Март","Април","Мај","Јун","Јул","Август","Септембар","Октобар","Новембар","Децембар"],abbr:["Јан","Феб","Мар","Апр","Мај","Јун","Јул","Авг","Сеп","Окт","Нов","Дец"]},days:["Нед","Пон","Уто","Сре","Чет","Пет","Суб"]},th:{language:"Thai",months:{original:["มกราคม","กุมภาพันธ์","มีนาคม","เมษายน","พฤษภาคม","มิถุนายน","กรกฎาคม","สิงหาคม","กันยายน","ตุลาคม","พฤศจิกายน","ธันวาคม"],abbr:["ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค."]},days:["อา","จ","อ","พ","พฤ","ศ","ส"]},tr:{language:"Turkish",months:{original:["Ocak","Şubat","Mart","Nisan","Mayıs","Haziran","Temmuz","Ağustos","Eylül","Ekim","Kasım","Aralık"],abbr:["Oca","Şub","Mar","Nis","May","Haz","Tem","Ağu","Eyl","Eki","Kas","Ara"]},days:["Paz","Pzt","Sal","Çar","Per","Cum","Cmt"]},uk:{language:"Ukraine",months:{original:["Січень","Лютий","Березень","Квітень","Травень","Червень","Липень","Серпень","Вересень","Жовтень","Листопад","Грудень"],abbr:["Січ","Лют","Бер","Квіт","Трав","Чер","Лип","Серп","Вер","Жовт","Лист","Груд"]},days:["Нд","Пн","Вт","Ср","Чт","Пт","Сб"]},ur:{language:"Urdu",rtl:!0,months:{original:["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","سپتمبر","اکتوبر","نومبر","دسمبر"],abbr:["جنوری","فروری","مارچ","اپریل","مئی","جون","جولائی","اگست","سپتمبر","اکتوبر","نومبر","دسمبر"]},days:["اتوار","پیر","منگل","بدھ","جمعرات","جمعہ","ہفتہ"]},vi:{language:"Vientnamese",months:{original:["Tháng 1","Tháng 2","Tháng 3","Tháng 4","Tháng 5","Tháng 6","Tháng 7","Tháng 8","Tháng 9","Tháng 10","Tháng 11","Tháng 12"],abbr:["T 01","T 02","T 03","T 04","T 05","T 06","T 07","T 08","T 09","T 10","T 11","T 12"]},days:["CN","Thứ 2","Thứ 3","Thứ 4","Thứ 5","Thứ 6","Thứ 7"]},zh:{language:"Chinese",ymd:!0,months:{original:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],abbr:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]},days:["日","一","二","三","四","五","六"]}}}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(9),i=n(0).document,o=r(i)&&r(i.createElement);t.exports=function(t){return o?i.createElement(t):{}}},function(t,e,n){var r=n(0),i=n(13),o=n(50),a=n(4),s=function(t,e,n){var l,c,u,f=t&s.F,d=t&s.G,h=t&s.S,p=t&s.P,v=t&s.B,g=t&s.W,m=d?i:i[e]||(i[e]={}),y=m.prototype,b=d?r:h?r[e]:(r[e]||{}).prototype;for(l in d&&(n=e),n)(c=!f&&b&&void 0!==b[l])&&l in m||(u=c?b[l]:n[l],m[l]=d&&"function"!=typeof b[l]?n[l]:v&&c?o(u,r):g&&b[l]==u?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e.prototype=t.prototype,e}(u):p&&"function"==typeof u?o(Function.call,u):u,p&&((m.virtual||(m.virtual={}))[l]=u,t&s.R&&y&&!y[l]&&a(y,l,u)))};s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,t.exports=s},function(t,e,n){t.exports=!n(3)&&!n(8)(function(){return 7!=Object.defineProperty(n(28)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){"use strict";var r=n(17),i=n(29),o=n(36),a=n(4),s=n(1),l=n(16),c=n(55),u=n(19),f=n(62),d=n(6)("iterator"),h=!([].keys&&"next"in[].keys()),p=function(){return this};t.exports=function(t,e,n,v,g,m,y){c(n,e,v);var b,w,_,x=function(t){if(!h&&t in A)return A[t];switch(t){case"keys":case"values":return function(){return new n(this,t)}}return function(){return new n(this,t)}},k=e+" Iterator",q="values"==g,O=!1,A=t.prototype,C=A[d]||A["@@iterator"]||g&&A[g],E=C||x(g),S=g?q?x("entries"):E:void 0,T="Array"==e&&A.entries||C;if(T&&(_=f(T.call(new t)))!==Object.prototype&&(u(_,k,!0),r||s(_,d)||a(_,d,p)),q&&C&&"values"!==C.name&&(O=!0,E=function(){return C.call(this)}),r&&!y||!h&&!O&&A[d]||a(A,d,E),l[e]=E,l[k]=p,g)if(b={values:q?E:x("values"),keys:m?E:x("keys"),entries:S},y)for(w in b)w in A||o(A,w,b[w]);else i(i.P+i.F*(h||O),e,b);return b}},function(t,e,n){var r=n(7),i=n(59),o=n(15),a=n(20)("IE_PROTO"),s=function(){},l=function(){var t,e=n(28)("iframe"),r=o.length;for(e.style.display="none",n(52).appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("<script>document.F=Object<\/script>"),t.close(),l=t.F;r--;)delete l.prototype[o[r]];return l()};t.exports=Object.create||function(t,e){var n;return null!==t?(s.prototype=r(t),n=new s,s.prototype=null,n[a]=t):n=l(),void 0===e?n:i(n,e)}},function(t,e,n){var r=n(35),i=n(15).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,i)}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e,n){var r=n(1),i=n(2),o=n(49)(!1),a=n(20)("IE_PROTO");t.exports=function(t,e){var n,s=i(t),l=0,c=[];for(n in s)n!=a&&r(s,n)&&c.push(n);for(;e.length>l;)r(s,n=e[l++])&&(~o(c,n)||c.push(n));return c}},function(t,e,n){t.exports=n(4)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(41),i=n(26);e.default={props:{value:{validator:function(t){return null===t||t instanceof Date||"string"==typeof t||"number"==typeof t}},name:String,refName:String,id:String,format:{type:[String,Function],default:"dd MMM yyyy"},language:{type:String,default:"en"},openDate:{validator:function(t){return null===t||t instanceof Date||"string"==typeof t}},fullMonthName:Boolean,disabled:Object,highlighted:Object,placeholder:String,inline:Boolean,calendarClass:[String,Object],inputClass:[String,Object],wrapperClass:[String,Object],mondayFirst:Boolean,clearButton:Boolean,clearButtonIcon:String,calendarButton:Boolean,calendarButtonIcon:String,calendarButtonIconContent:String,bootstrapStyling:Boolean,initialView:String,disabledPicker:Boolean,required:Boolean,minimumView:{type:String,default:"day"},maximumView:{type:String,default:"year"}},data:function(){return{pageTimestamp:(this.openDate?new Date(this.openDate):new Date).setDate(1),selectedDate:null,showDayView:!1,showMonthView:!1,showYearView:!1,calendarHeight:0}},watch:{value:function(t){this.setValue(t)},openDate:function(){this.setPageDate()},initialView:function(){this.setInitialView()}},computed:{computedInitialView:function(){return this.initialView?this.initialView:this.minimumView},pageDate:function(){return new Date(this.pageTimestamp)},formattedValue:function(){return this.selectedDate?"function"==typeof this.format?this.format(this.selectedDate):r.a.formatDate(new Date(this.selectedDate),this.format,this.translation):null},translation:function(){return i.a.translations[this.language]},currMonthName:function(){var t=this.fullMonthName?this.translation.months.original:this.translation.months.abbr;return r.a.getMonthNameAbbr(this.pageDate.getMonth(),t)},currYear:function(){return this.pageDate.getFullYear()},blankDays:function(){var t=this.pageDate,e=new Date(t.getFullYear(),t.getMonth(),1,t.getHours(),t.getMinutes());return this.mondayFirst?e.getDay()>0?e.getDay()-1:6:e.getDay()},daysOfWeek:function(){if(this.mondayFirst){var t=this.translation.days.slice();return t.push(t.shift()),t}return this.translation.days},days:function(){for(var t=this.pageDate,e=[],n=new Date(t.getFullYear(),t.getMonth(),1,t.getHours(),t.getMinutes()),i=r.a.daysInMonth(n.getFullYear(),n.getMonth()),o=0;o<i;o++)e.push({date:n.getDate(),timestamp:n.getTime(),isSelected:this.isSelectedDate(n),isDisabled:this.isDisabledDate(n),isHighlighted:this.isHighlightedDate(n),isHighlightStart:this.isHighlightStart(n),isHighlightEnd:this.isHighlightEnd(n),isToday:n.toDateString()===(new Date).toDateString(),isWeekend:0===n.getDay()||6===n.getDay(),isSaturday:6===n.getDay(),isSunday:0===n.getDay()}),n.setDate(n.getDate()+1);return e},months:function(){for(var t=this.pageDate,e=[],n=new Date(t.getFullYear(),0,t.getDate(),t.getHours(),t.getMinutes()),i=0;i<12;i++)e.push({month:r.a.getMonthName(i,this.translation.months.original),timestamp:n.getTime(),isSelected:this.isSelectedMonth(n),isDisabled:this.isDisabledMonth(n)}),n.setMonth(n.getMonth()+1);return e},years:function(){for(var t=this.pageDate,e=[],n=new Date(10*Math.floor(t.getFullYear()/10),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes()),r=0;r<10;r++)e.push({year:n.getFullYear(),timestamp:n.getTime(),isSelected:this.isSelectedYear(n),isDisabled:this.isDisabledYear(n)}),n.setFullYear(n.getFullYear()+1);return e},calendarStyle:function(){return{position:this.isInline?"static":void 0}},isOpen:function(){return this.showDayView||this.showMonthView||this.showYearView},isInline:function(){return!!this.inline},isRtl:function(){return!0===this.translation.rtl},isYmd:function(){return!0===this.translation.ymd}},methods:{close:function(t){this.showDayView=this.showMonthView=this.showYearView=!1,this.isInline||(t&&this.$emit("closed"),document.removeEventListener("click",this.clickOutside,!1))},resetDefaultDate:function(){null!==this.selectedDate?this.setPageDate(this.selectedDate):this.setPageDate()},showCalendar:function(){return!this.disabledPicker&&!this.isInline&&(this.isOpen?this.close(!0):(this.setInitialView(),void(this.isInline||this.$emit("opened"))))},setInitialView:function(){var t=this.computedInitialView;if(!this.allowedToShowView(t))throw new Error("initialView '"+this.initialView+"' cannot be rendered based on minimum '"+this.minimumView+"' and maximum '"+this.maximumView+"'");switch(t){case"year":this.showYearCalendar();break;case"month":this.showMonthCalendar();break;default:this.showDayCalendar()}},allowedToShowView:function(t){var e=["day","month","year"],n=e.indexOf(this.minimumView),r=e.indexOf(this.maximumView),i=e.indexOf(t);return i>=n&&i<=r},showDayCalendar:function(){if(!this.allowedToShowView("day"))return!1;this.close(),this.showDayView=!0,this.addOutsideClickListener()},showMonthCalendar:function(){if(!this.allowedToShowView("month"))return!1;this.close(),this.showMonthView=!0,this.addOutsideClickListener()},showYearCalendar:function(){if(!this.allowedToShowView("year"))return!1;this.close(),this.showYearView=!0,this.addOutsideClickListener()},addOutsideClickListener:function(){var t=this;this.isInline||setTimeout(function(){document.addEventListener("click",t.clickOutside,!1)},100)},setDate:function(t){var e=new Date(t);this.selectedDate=new Date(e),this.setPageDate(e),this.$emit("selected",new Date(e)),this.$emit("input",new Date(e))},clearDate:function(){this.selectedDate=null,this.$emit("selected",null),this.$emit("input",null),this.$emit("cleared")},selectDate:function(t){if(t.isDisabled)return this.$emit("selectedDisabled",t),!1;this.setDate(t.timestamp),this.isInline?this.showDayCalendar():this.close(!0)},selectMonth:function(t){if(t.isDisabled)return!1;var e=new Date(t.timestamp);this.allowedToShowView("day")?(this.setPageDate(e),this.$emit("changedMonth",t),this.showDayCalendar()):(this.setDate(e),this.close(!0))},selectYear:function(t){if(t.isDisabled)return!1;var e=new Date(t.timestamp);this.allowedToShowView("month")?(this.setPageDate(e),this.$emit("changedYear",t),this.showMonthCalendar()):(this.setDate(e),this.close(!0))},getPageDate:function(){return this.pageDate.getDate()},getPageMonth:function(){return this.pageDate.getMonth()},getPageYear:function(){return this.pageDate.getFullYear()},getPageDecade:function(){return 10*Math.floor(this.pageDate.getFullYear()/10)+"'s"},changeMonth:function(t){var e=this.pageDate;e.setMonth(e.getMonth()+t),this.setPageDate(e),this.$emit("changedMonth",e)},previousMonth:function(){this.previousMonthDisabled()||this.changeMonth(-1)},previousMonthDisabled:function(){if(!this.disabled||!this.disabled.to)return!1;var t=this.pageDate;return this.disabled.to.getMonth()>=t.getMonth()&&this.disabled.to.getFullYear()>=t.getFullYear()},nextMonth:function(){this.nextMonthDisabled()||this.changeMonth(1)},nextMonthDisabled:function(){if(!this.disabled||!this.disabled.from)return!1;var t=this.pageDate;return this.disabled.from.getMonth()<=t.getMonth()&&this.disabled.from.getFullYear()<=t.getFullYear()},changeYear:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"changedYear",n=this.pageDate;n.setYear(n.getFullYear()+t),this.setPageDate(n),this.$emit(e,n)},previousYear:function(){this.previousYearDisabled()||this.changeYear(-1)},previousYearDisabled:function(){return!(!this.disabled||!this.disabled.to)&&this.disabled.to.getFullYear()>=this.pageDate.getFullYear()},nextYear:function(){this.nextYearDisabled()||this.changeYear(1)},nextYearDisabled:function(){return!(!this.disabled||!this.disabled.from)&&this.disabled.from.getFullYear()<=this.pageDate.getFullYear()},previousDecade:function(){this.previousDecadeDisabled()||this.changeYear(-10,"changeDecade")},previousDecadeDisabled:function(){return!(!this.disabled||!this.disabled.to)&&10*Math.floor(this.disabled.to.getFullYear()/10)>=10*Math.floor(this.pageDate.getFullYear()/10)},nextDecade:function(){this.nextDecadeDisabled()||this.changeYear(10,"changeDecade")},nextDecadeDisabled:function(){return!(!this.disabled||!this.disabled.from)&&10*Math.ceil(this.disabled.from.getFullYear()/10)<=10*Math.ceil(this.pageDate.getFullYear()/10)},isSelectedDate:function(t){return this.selectedDate&&this.selectedDate.toDateString()===t.toDateString()},isDisabledDate:function(t){var e=!1;return void 0!==this.disabled&&(void 0!==this.disabled.dates&&this.disabled.dates.forEach(function(n){if(t.toDateString()===n.toDateString())return e=!0,!0}),void 0!==this.disabled.to&&this.disabled.to&&t<this.disabled.to&&(e=!0),void 0!==this.disabled.from&&this.disabled.from&&t>this.disabled.from&&(e=!0),void 0!==this.disabled.ranges&&this.disabled.ranges.forEach(function(n){if(void 0!==n.from&&n.from&&void 0!==n.to&&n.to&&t<n.to&&t>n.from)return e=!0,!0}),void 0!==this.disabled.days&&-1!==this.disabled.days.indexOf(t.getDay())&&(e=!0),void 0!==this.disabled.daysOfMonth&&-1!==this.disabled.daysOfMonth.indexOf(t.getDate())&&(e=!0),"function"==typeof this.disabled.customPredictor&&this.disabled.customPredictor(t)&&(e=!0),e)},isHighlightedDate:function(t){if(this.isDisabledDate(t))return!1;var e=!1;return void 0!==this.highlighted&&(void 0!==this.highlighted.dates&&this.highlighted.dates.forEach(function(n){if(t.toDateString()===n.toDateString())return e=!0,!0}),this.isDefined(this.highlighted.from)&&this.isDefined(this.highlighted.to)&&(e=t>=this.highlighted.from&&t<=this.highlighted.to),void 0!==this.highlighted.days&&-1!==this.highlighted.days.indexOf(t.getDay())&&(e=!0),void 0!==this.highlighted.daysOfMonth&&-1!==this.highlighted.daysOfMonth.indexOf(t.getDate())&&(e=!0),"function"==typeof this.highlighted.customPredictor&&this.highlighted.customPredictor(t)&&(e=!0),e)},isHighlightStart:function(t){return this.isHighlightedDate(t)&&this.highlighted.from instanceof Date&&this.highlighted.from.getFullYear()===t.getFullYear()&&this.highlighted.from.getMonth()===t.getMonth()&&this.highlighted.from.getDate()===t.getDate()},isHighlightEnd:function(t){return this.isHighlightedDate(t)&&this.highlighted.to instanceof Date&&this.highlighted.to.getFullYear()===t.getFullYear()&&this.highlighted.to.getMonth()===t.getMonth()&&this.highlighted.to.getDate()===t.getDate()},isDefined:function(t){return void 0!==t&&t},isSelectedMonth:function(t){return this.selectedDate&&this.selectedDate.getFullYear()===t.getFullYear()&&this.selectedDate.getMonth()===t.getMonth()},isDisabledMonth:function(t){var e=!1;return void 0!==this.disabled&&(void 0!==this.disabled.to&&this.disabled.to&&(t.getMonth()<this.disabled.to.getMonth()&&t.getFullYear()<=this.disabled.to.getFullYear()||t.getFullYear()<this.disabled.to.getFullYear())&&(e=!0),void 0!==this.disabled.from&&this.disabled.from&&(this.disabled.from&&t.getMonth()>this.disabled.from.getMonth()&&t.getFullYear()>=this.disabled.from.getFullYear()||t.getFullYear()>this.disabled.from.getFullYear())&&(e=!0),e)},isSelectedYear:function(t){return this.selectedDate&&this.selectedDate.getFullYear()===t.getFullYear()},isDisabledYear:function(t){var e=!1;return!(void 0===this.disabled||!this.disabled)&&(void 0!==this.disabled.to&&this.disabled.to&&t.getFullYear()<this.disabled.to.getFullYear()&&(e=!0),void 0!==this.disabled.from&&this.disabled.from&&t.getFullYear()>this.disabled.from.getFullYear()&&(e=!0),e)},setValue:function(t){if("string"==typeof t||"number"==typeof t){var e=new Date(t);t=isNaN(e.valueOf())?null:e}if(!t)return this.setPageDate(),void(this.selectedDate=null);this.selectedDate=t,this.setPageDate(t)},setPageDate:function(t){t||(t=this.openDate?new Date(this.openDate):new Date),this.pageTimestamp=new Date(t).setDate(1)},clickOutside:function(t){if(this.$el&&!this.$el.contains(t.target)){if(this.isInline)return this.showDayCalendar();this.resetDefaultDate(),this.close(!0),document.removeEventListener("click",this.clickOutside,!1)}},dayClasses:function(t){return{selected:t.isSelected,disabled:t.isDisabled,highlighted:t.isHighlighted,today:t.isToday,weekend:t.isWeekend,sat:t.isSaturday,sun:t.isSunday,"highlight-start":t.isHighlightStart,"highlight-end":t.isHighlightEnd}},init:function(){this.value&&this.setValue(this.value),this.isInline&&this.setInitialView()}},mounted:function(){this.init()}}},function(t,e){t.exports=function(t,e,n,r,i){var o,a=t=t||{},s=typeof t.default;"object"!==s&&"function"!==s||(o=t,a=t.default);var l,c="function"==typeof a?a.options:a;if(e&&(c.render=e.render,c.staticRenderFns=e.staticRenderFns),r&&(c._scopeId=r),i?(l=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),n&&n.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(i)},c._ssrRegister=l):n&&(l=n),l){var u=c.functional,f=u?c.render:c.beforeCreate;u?c.render=function(t,e){return l.call(e),f(t,e)}:c.beforeCreate=f?[].concat(f,l):[l]}return{esModule:o,exports:a,options:c}}},function(t,e){t.exports={render:function(){
var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"vdp-datepicker",class:[t.wrapperClass,t.isRtl?"rtl":""]},[n("div",{class:{"input-group":t.bootstrapStyling}},[t.calendarButton?n("span",{staticClass:"vdp-datepicker__calendar-button",class:{"input-group-addon":t.bootstrapStyling},style:{"cursor:not-allowed;":t.disabledPicker},on:{click:t.showCalendar}},[n("i",{class:t.calendarButtonIcon},[t._v("\n "+t._s(t.calendarButtonIconContent)+"\n "),t.calendarButtonIcon?t._e():n("span",[t._v("…")])])]):t._e(),t._v(" "),n("input",{ref:t.refName,class:[t.inputClass,{"form-control":t.bootstrapStyling}],attrs:{type:t.inline?"hidden":"text",name:t.name,id:t.id,"open-date":t.openDate,placeholder:t.placeholder,"clear-button":t.clearButton,disabled:t.disabledPicker,required:t.required,readonly:""},domProps:{value:t.formattedValue},on:{click:t.showCalendar}}),t._v(" "),t.clearButton&&t.selectedDate?n("span",{staticClass:"vdp-datepicker__clear-button",class:{"input-group-addon":t.bootstrapStyling},on:{click:function(e){t.clearDate()}}},[n("i",{class:t.clearButtonIcon},[t.clearButtonIcon?t._e():n("span",[t._v("×")])])]):t._e()]),t._v(" "),t.allowedToShowView("day")?[n("div",{directives:[{name:"show",rawName:"v-show",value:t.showDayView,expression:"showDayView"}],class:[t.calendarClass,"vdp-datepicker__calendar"],style:t.calendarStyle},[n("header",[n("span",{staticClass:"prev",class:{disabled:t.isRtl?t.nextMonthDisabled(t.pageTimestamp):t.previousMonthDisabled(t.pageTimestamp)},on:{click:function(e){t.isRtl?t.nextMonth():t.previousMonth()}}},[t._v("<")]),t._v(" "),n("span",{class:t.allowedToShowView("month")?"up":"",on:{click:t.showMonthCalendar}},[t._v(t._s(t.isYmd?t.currYear:t.currMonthName)+" "+t._s(t.isYmd?t.currMonthName:t.currYear))]),t._v(" "),n("span",{staticClass:"next",class:{disabled:t.isRtl?t.previousMonthDisabled(t.pageTimestamp):t.nextMonthDisabled(t.pageTimestamp)},on:{click:function(e){t.isRtl?t.previousMonth():t.nextMonth()}}},[t._v(">")])]),t._v(" "),n("div",{class:t.isRtl?"flex-rtl":""},[t._l(t.daysOfWeek,function(e){return n("span",{key:e.timestamp,staticClass:"cell day-header"},[t._v(t._s(e))])}),t._v(" "),t.blankDays>0?t._l(t.blankDays,function(t){return n("span",{key:t.timestamp,staticClass:"cell day blank"})}):t._e(),t._l(t.days,function(e){return n("span",{key:e.timestamp,staticClass:"cell day",class:t.dayClasses(e),attrs:{"track-by":"timestamp"},on:{click:function(n){t.selectDate(e)}}},[t._v(t._s(e.date))])})],2)])]:t._e(),t._v(" "),t.allowedToShowView("month")?[n("div",{directives:[{name:"show",rawName:"v-show",value:t.showMonthView,expression:"showMonthView"}],class:[t.calendarClass,"vdp-datepicker__calendar"],style:t.calendarStyle},[n("header",[n("span",{staticClass:"prev",class:{disabled:t.previousYearDisabled(t.pageTimestamp)},on:{click:t.previousYear}},[t._v("<")]),t._v(" "),n("span",{class:t.allowedToShowView("year")?"up":"",on:{click:t.showYearCalendar}},[t._v(t._s(t.getPageYear()))]),t._v(" "),n("span",{staticClass:"next",class:{disabled:t.nextYearDisabled(t.pageTimestamp)},on:{click:t.nextYear}},[t._v(">")])]),t._v(" "),t._l(t.months,function(e){return n("span",{key:e.timestamp,staticClass:"cell month",class:{selected:e.isSelected,disabled:e.isDisabled},attrs:{"track-by":"timestamp"},on:{click:function(n){n.stopPropagation(),t.selectMonth(e)}}},[t._v(t._s(e.month))])})],2)]:t._e(),t._v(" "),t.allowedToShowView("year")?[n("div",{directives:[{name:"show",rawName:"v-show",value:t.showYearView,expression:"showYearView"}],class:[t.calendarClass,"vdp-datepicker__calendar"],style:t.calendarStyle},[n("header",[n("span",{staticClass:"prev",class:{disabled:t.previousDecadeDisabled(t.pageTimestamp)},on:{click:t.previousDecade}},[t._v("<")]),t._v(" "),n("span",[t._v(t._s(t.getPageDecade()))]),t._v(" "),n("span",{staticClass:"next",class:{disabled:t.nextMonthDisabled(t.pageTimestamp)},on:{click:t.nextDecade}},[t._v(">")])]),t._v(" "),t._l(t.years,function(e){return n("span",{key:e.timestamp,staticClass:"cell year",class:{selected:e.isSelected,disabled:e.isDisabled},attrs:{"track-by":"timestamp"},on:{click:function(n){n.stopPropagation(),t.selectYear(e)}}},[t._v(t._s(e.year))])})],2)]:t._e()],2)},staticRenderFns:[]}},function(t,e,n){var r=n(74);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals),n(77)("cc2c5bfc",r,!0)},function(t,e,n){"use strict";var r=n(44),i=n.n(r),o=n(26);e.a={isValidDate:function(t){return"[object Date]"===Object.prototype.toString.call(t)&&!isNaN(t.getTime())},getDayNameAbbr:function(t,e){if("object"!==(void 0===t?"undefined":i()(t)))throw TypeError("Invalid Type");return e[t.getDay()]},getMonthName:function(t,e){if(!e)throw Error("missing 2nd parameter Months array");if("object"===(void 0===t?"undefined":i()(t)))return e[t.getMonth()];if("number"==typeof t)return e[t];throw TypeError("Invalid type")},getMonthNameAbbr:function(t,e){if(!e)throw Error("missing 2nd paramter Months array");if("object"===(void 0===t?"undefined":i()(t)))return e[t.getMonth()];if("number"==typeof t)return e[t];throw TypeError("Invalid type")},daysInMonth:function(t,e){return/8|3|5|10/.test(e)?30:1===e?(t%4||!(t%100))&&t%400?28:29:31},getNthSuffix:function(t){switch(t){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th"}},formatDate:function(t,e,n){n=n||o.a.translations.en;var r=t.getFullYear(),i=t.getMonth()+1,a=t.getDate();return e.replace(/dd/,("0"+a).slice(-2)).replace(/d/,a).replace(/yyyy/,r).replace(/yy/,String(r).slice(2)).replace(/MMMM/,this.getMonthName(t.getMonth(),n.months.original)).replace(/MMM/,this.getMonthNameAbbr(t.getMonth(),n.months.abbr)).replace(/MM/,("0"+i).slice(-2)).replace(/M(?!a|ä)/,i).replace(/su/,this.getNthSuffix(t.getDate())).replace(/D(?!e|é|i)/,this.getDayNameAbbr(t,n.days))},createDateArray:function(t,e){for(var n=[];t<=e;)n.push(new Date(t)),t=new Date(t).setDate(new Date(t).getDate()+1);return n}}},function(t,e,n){t.exports={default:n(45),__esModule:!0}},function(t,e,n){t.exports={default:n(46),__esModule:!0}},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}e.__esModule=!0;var i=r(n(43)),o=r(n(42)),a="function"==typeof o.default&&"symbol"==typeof i.default?function(t){return typeof t}:function(t){return t&&"function"==typeof o.default&&t.constructor===o.default&&t!==o.default.prototype?"symbol":typeof t};e.default="function"==typeof o.default&&"symbol"===a(i.default)?function(t){return void 0===t?"undefined":a(t)}:function(t){return t&&"function"==typeof o.default&&t.constructor===o.default&&t!==o.default.prototype?"symbol":void 0===t?"undefined":a(t)}},function(t,e,n){n(70),n(68),n(71),n(72),t.exports=n(13).Symbol},function(t,e,n){n(69),n(73),t.exports=n(25).f("iterator")},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e){t.exports=function(){}},function(t,e,n){var r=n(2),i=n(65),o=n(64);t.exports=function(t){return function(e,n,a){var s,l=r(e),c=i(l.length),u=o(a,c);if(t&&n!=n){for(;c>u;)if((s=l[u++])!=s)return!0}else for(;c>u;u++)if((t||u in l)&&l[u]===n)return t||u||0;return!t&&-1}}},function(t,e,n){var r=n(47);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,i){return t.call(e,n,r,i)}}return function(){return t.apply(e,arguments)}}},function(t,e,n){var r=n(10),i=n(34),o=n(18);t.exports=function(t){var e=r(t),n=i.f;if(n)for(var a,s=n(t),l=o.f,c=0;s.length>c;)l.call(t,a=s[c++])&&e.push(a);return e}},function(t,e,n){t.exports=n(0).document&&document.documentElement},function(t,e,n){var r=n(27);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e,n){var r=n(27);t.exports=Array.isArray||function(t){return"Array"==r(t)}},function(t,e,n){"use strict";var r=n(32),i=n(11),o=n(19),a={};n(4)(a,n(6)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(a,{next:i(1,n)}),o(t,e+" Iterator")}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){var r=n(10),i=n(2);t.exports=function(t,e){for(var n,o=i(t),a=r(o),s=a.length,l=0;s>l;)if(o[n=a[l++]]===e)return n}},function(t,e,n){var r=n(12)("meta"),i=n(9),o=n(1),a=n(5).f,s=0,l=Object.isExtensible||function(){return!0},c=!n(8)(function(){return l(Object.preventExtensions({}))}),u=function(t){a(t,r,{value:{i:"O"+ ++s,w:{}}})},f=t.exports={KEY:r,NEED:!1,fastKey:function(t,e){if(!i(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!o(t,r)){if(!l(t))return"F";if(!e)return"E";u(t)}return t[r].i},getWeak:function(t,e){if(!o(t,r)){if(!l(t))return!0;if(!e)return!1;u(t)}return t[r].w},onFreeze:function(t){return c&&f.NEED&&l(t)&&!o(t,r)&&u(t),t}}},function(t,e,n){var r=n(5),i=n(7),o=n(10);t.exports=n(3)?Object.defineProperties:function(t,e){i(t);for(var n,a=o(e),s=a.length,l=0;s>l;)r.f(t,n=a[l++],e[n]);return t}},function(t,e,n){var r=n(18),i=n(11),o=n(2),a=n(23),s=n(1),l=n(30),c=Object.getOwnPropertyDescriptor;e.f=n(3)?c:function(t,e){if(t=o(t),e=a(e,!0),l)try{return c(t,e)}catch(t){}if(s(t,e))return i(!r.f.call(t,e),t[e])}},function(t,e,n){var r=n(2),i=n(33).f,o={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return a&&"[object Window]"==o.call(t)?function(t){try{return i(t)}catch(t){return a.slice()}}(t):i(r(t))}},function(t,e,n){var r=n(1),i=n(66),o=n(20)("IE_PROTO"),a=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=i(t),r(t,o)?t[o]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?a:null}},function(t,e,n){var r=n(22),i=n(14);t.exports=function(t){return function(e,n){var o,a,s=String(i(e)),l=r(n),c=s.length;return l<0||l>=c?t?"":void 0:(o=s.charCodeAt(l))<55296||o>56319||l+1===c||(a=s.charCodeAt(l+1))<56320||a>57343?t?s.charAt(l):o:t?s.slice(l,l+2):a-56320+(o-55296<<10)+65536}}},function(t,e,n){var r=n(22),i=Math.max,o=Math.min;t.exports=function(t,e){return(t=r(t))<0?i(t+e,0):o(t,e)}},function(t,e,n){var r=n(22),i=Math.min;t.exports=function(t){return t>0?i(r(t),9007199254740991):0}},function(t,e,n){var r=n(14);t.exports=function(t){return Object(r(t))}},function(t,e,n){"use strict";var r=n(48),i=n(56),o=n(16),a=n(2);t.exports=n(31)(Array,"Array",function(t,e){this._t=a(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,i(1)):i(0,"keys"==e?n:"values"==e?t[n]:[n,t[n]])},"values"),o.Arguments=o.Array,r("keys"),r("values"),r("entries")},function(t,e){},function(t,e,n){"use strict";var r=n(63)(!0);n(31)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){"use strict";var r=n(0),i=n(1),o=n(3),a=n(29),s=n(36),l=n(58).KEY,c=n(8),u=n(21),f=n(19),d=n(12),h=n(6),p=n(25),v=n(24),g=n(57),m=n(51),y=n(54),b=n(7),w=n(2),_=n(23),x=n(11),k=n(32),q=n(61),O=n(60),A=n(5),C=n(10),E=O.f,S=A.f,T=q.f,N=r.Symbol,j=r.JSON,M=j&&j.stringify,P=h("_hidden"),D=h("toPrimitive"),L={}.propertyIsEnumerable,B=u("symbol-registry"),I=u("symbols"),R=u("op-symbols"),F=Object.prototype,z="function"==typeof N,U=r.QObject,H=!U||!U.prototype||!U.prototype.findChild,V=o&&c(function(){return 7!=k(S({},"a",{get:function(){return S(this,"a",{value:7}).a}})).a})?function(t,e,n){var r=E(F,e);r&&delete F[e],S(t,e,n),r&&t!==F&&S(F,e,r)}:S,Y=function(t){var e=I[t]=k(N.prototype);return e._k=t,e},$=z&&"symbol"==typeof N.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof N},J=function(t,e,n){return t===F&&J(R,e,n),b(t),e=_(e,!0),b(n),i(I,e)?(n.enumerable?(i(t,P)&&t[P][e]&&(t[P][e]=!1),n=k(n,{enumerable:x(0,!1)})):(i(t,P)||S(t,P,x(1,{})),t[P][e]=!0),V(t,e,n)):S(t,e,n)},K=function(t,e){b(t);for(var n,r=m(e=w(e)),i=0,o=r.length;o>i;)J(t,n=r[i++],e[n]);return t},W=function(t){var e=L.call(this,t=_(t,!0));return!(this===F&&i(I,t)&&!i(R,t))&&(!(e||!i(this,t)||!i(I,t)||i(this,P)&&this[P][t])||e)},G=function(t,e){if(t=w(t),e=_(e,!0),t!==F||!i(I,e)||i(R,e)){var n=E(t,e);return!n||!i(I,e)||i(t,P)&&t[P][e]||(n.enumerable=!0),n}},Z=function(t){for(var e,n=T(w(t)),r=[],o=0;n.length>o;)i(I,e=n[o++])||e==P||e==l||r.push(e);return r},X=function(t){for(var e,n=t===F,r=T(n?R:w(t)),o=[],a=0;r.length>a;)!i(I,e=r[a++])||n&&!i(F,e)||o.push(I[e]);return o};z||(s((N=function(){if(this instanceof N)throw TypeError("Symbol is not a constructor!");var t=d(arguments.length>0?arguments[0]:void 0),e=function(n){this===F&&e.call(R,n),i(this,P)&&i(this[P],t)&&(this[P][t]=!1),V(this,t,x(1,n))};return o&&H&&V(F,t,{configurable:!0,set:e}),Y(t)}).prototype,"toString",function(){return this._k}),O.f=G,A.f=J,n(33).f=q.f=Z,n(18).f=W,n(34).f=X,o&&!n(17)&&s(F,"propertyIsEnumerable",W,!0),p.f=function(t){return Y(h(t))}),a(a.G+a.W+a.F*!z,{Symbol:N});for(var Q="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),tt=0;Q.length>tt;)h(Q[tt++]);for(Q=C(h.store),tt=0;Q.length>tt;)v(Q[tt++]);a(a.S+a.F*!z,"Symbol",{for:function(t){return i(B,t+="")?B[t]:B[t]=N(t)},keyFor:function(t){if($(t))return g(B,t);throw TypeError(t+" is not a symbol!")},useSetter:function(){H=!0},useSimple:function(){H=!1}}),a(a.S+a.F*!z,"Object",{create:function(t,e){return void 0===e?k(t):K(k(t),e)},defineProperty:J,defineProperties:K,getOwnPropertyDescriptor:G,getOwnPropertyNames:Z,getOwnPropertySymbols:X}),j&&a(a.S+a.F*(!z||c(function(){var t=N();return"[null]"!=M([t])||"{}"!=M({a:t})||"{}"!=M(Object(t))})),"JSON",{stringify:function(t){if(void 0!==t&&!$(t)){for(var e,n,r=[t],i=1;arguments.length>i;)r.push(arguments[i++]);return"function"==typeof(e=r[1])&&(n=e),!n&&y(e)||(e=function(t,e){if(n&&(e=n.call(this,t,e)),!$(e))return e}),r[1]=e,M.apply(j,r)}}}),N.prototype[D]||n(4)(N.prototype,D,N.prototype.valueOf),f(N,"Symbol"),f(Math,"Math",!0),f(r.JSON,"JSON",!0)},function(t,e,n){n(24)("asyncIterator")},function(t,e,n){n(24)("observable")},function(t,e,n){n(67);for(var r=n(0),i=n(4),o=n(16),a=n(6)("toStringTag"),s=["NodeList","DOMTokenList","MediaList","StyleSheetList","CSSRuleList"],l=0;l<5;l++){var c=s[l],u=r[c],f=u&&u.prototype;f&&!f[a]&&i(f,a,c),o[c]=o.Array}},function(t,e,n){(t.exports=n(75)(!0)).push([t.i,'.rtl{direction:rtl}.vdp-datepicker{position:relative;text-align:left}.vdp-datepicker *{box-sizing:border-box}.vdp-datepicker__calendar{position:absolute;z-index:100;background:#fff;width:300px;border:1px solid #ccc}.vdp-datepicker__calendar header{display:block;line-height:40px}.vdp-datepicker__calendar header span{display:inline-block;text-align:center;width:71.42857142857143%;float:left}.vdp-datepicker__calendar header .next,.vdp-datepicker__calendar header .prev{width:14.285714285714286%;float:left;text-indent:-10000px;position:relative}.vdp-datepicker__calendar header .next:after,.vdp-datepicker__calendar header .prev:after{content:"";position:absolute;left:50%;top:50%;-webkit-transform:translateX(-50%) translateY(-50%);transform:translateX(-50%) translateY(-50%);border:6px solid transparent}.vdp-datepicker__calendar header .prev:after{border-right:10px solid #000;margin-left:-5px}.vdp-datepicker__calendar header .prev.disabled:after{border-right:10px solid #ddd}.vdp-datepicker__calendar header .next:after{border-left:10px solid #000;margin-left:5px}.vdp-datepicker__calendar header .next.disabled:after{border-left:10px solid #ddd}.vdp-datepicker__calendar header .next:not(.disabled),.vdp-datepicker__calendar header .prev:not(.disabled),.vdp-datepicker__calendar header .up:not(.disabled){cursor:pointer}.vdp-datepicker__calendar header .next:not(.disabled):hover,.vdp-datepicker__calendar header .prev:not(.disabled):hover,.vdp-datepicker__calendar header .up:not(.disabled):hover{background:#eee}.vdp-datepicker__calendar .disabled{color:#ddd;cursor:default}.vdp-datepicker__calendar .flex-rtl{display:-webkit-box;display:-ms-flexbox;display:flex;width:inherit;-ms-flex-wrap:wrap;flex-wrap:wrap}.vdp-datepicker__calendar .cell{display:inline-block;padding:0 5px;width:14.285714285714286%;height:40px;line-height:40px;text-align:center;vertical-align:middle;border:1px solid transparent}.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).day,.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).month,.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).year{cursor:pointer}.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).day:hover,.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).month:hover,.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).year:hover{border:1px solid #4bd}.vdp-datepicker__calendar .cell.selected,.vdp-datepicker__calendar .cell.selected.highlighted,.vdp-datepicker__calendar .cell.selected:hover{background:#4bd}.vdp-datepicker__calendar .cell.highlighted{background:#cae5ed}.vdp-datepicker__calendar .cell.grey{color:#888}.vdp-datepicker__calendar .cell.grey:hover{background:inherit}.vdp-datepicker__calendar .cell.day-header{font-size:75%;white-space:no-wrap;cursor:inherit}.vdp-datepicker__calendar .cell.day-header:hover{background:inherit}.vdp-datepicker__calendar .month,.vdp-datepicker__calendar .year{width:33.333%}.vdp-datepicker__calendar-button,.vdp-datepicker__clear-button{cursor:pointer;font-style:normal}.vdp-datepicker__calendar-button.disabled,.vdp-datepicker__clear-button.disabled{color:#999;cursor:default}',"",{version:3,sources:["/Users/charlie.kassel/Server/sites/vuejs-datepicker/src/components/Datepicker.vue"],names:[],mappings:"AACA,KACE,aAAe,CAChB,AACD,gBACE,kBAAmB,AACnB,eAAiB,CAClB,AACD,kBACE,qBAAuB,CACxB,AACD,0BACE,kBAAmB,AACnB,YAAa,AACb,gBAAiB,AACjB,YAAa,AACb,qBAAuB,CACxB,AACD,iCACE,cAAe,AACf,gBAAkB,CACnB,AACD,sCACE,qBAAsB,AACtB,kBAAmB,AACnB,yBAA0B,AAC1B,UAAY,CACb,AACD,8EAEE,0BAA2B,AAC3B,WAAY,AACZ,qBAAsB,AACtB,iBAAmB,CACpB,AACD,0FAEE,WAAY,AACZ,kBAAmB,AACnB,SAAU,AACV,QAAS,AACT,oDAAqD,AAC7C,4CAA6C,AACrD,4BAA8B,CAC/B,AACD,6CACE,6BAA8B,AAC9B,gBAAkB,CACnB,AACD,sDACE,4BAA8B,CAC/B,AACD,6CACE,4BAA6B,AAC7B,eAAiB,CAClB,AACD,sDACE,2BAA6B,CAC9B,AACD,gKAGE,cAAgB,CACjB,AACD,kLAGE,eAAiB,CAClB,AACD,oCACE,WAAY,AACZ,cAAgB,CACjB,AACD,oCACE,oBAAqB,AACrB,oBAAqB,AACrB,aAAc,AACd,cAAe,AACf,mBAAoB,AAChB,cAAgB,CACrB,AACD,gCACE,qBAAsB,AACtB,cAAe,AACf,0BAA2B,AAC3B,YAAa,AACb,iBAAkB,AAClB,kBAAmB,AACnB,sBAAuB,AACvB,4BAA8B,CAC/B,AACD,gMAGE,cAAgB,CACjB,AACD,kNAGE,qBAAuB,CACxB,AAOD,6IACE,eAAiB,CAClB,AACD,4CACE,kBAAoB,CACrB,AACD,qCACE,UAAY,CACb,AACD,2CACE,kBAAoB,CACrB,AACD,2CACE,cAAe,AACf,oBAAqB,AACrB,cAAgB,CACjB,AACD,iDACE,kBAAoB,CACrB,AACD,iEAEE,aAAe,CAChB,AACD,+DAEE,eAAgB,AAChB,iBAAmB,CACpB,AACD,iFAEE,WAAY,AACZ,cAAgB,CACjB",file:"Datepicker.vue",sourcesContent:["\n.rtl {\n direction: rtl;\n}\n.vdp-datepicker {\n position: relative;\n text-align: left;\n}\n.vdp-datepicker * {\n box-sizing: border-box;\n}\n.vdp-datepicker__calendar {\n position: absolute;\n z-index: 100;\n background: #fff;\n width: 300px;\n border: 1px solid #ccc;\n}\n.vdp-datepicker__calendar header {\n display: block;\n line-height: 40px;\n}\n.vdp-datepicker__calendar header span {\n display: inline-block;\n text-align: center;\n width: 71.42857142857143%;\n float: left;\n}\n.vdp-datepicker__calendar header .prev,\n.vdp-datepicker__calendar header .next {\n width: 14.285714285714286%;\n float: left;\n text-indent: -10000px;\n position: relative;\n}\n.vdp-datepicker__calendar header .prev:after,\n.vdp-datepicker__calendar header .next:after {\n content: '';\n position: absolute;\n left: 50%;\n top: 50%;\n -webkit-transform: translateX(-50%) translateY(-50%);\n transform: translateX(-50%) translateY(-50%);\n border: 6px solid transparent;\n}\n.vdp-datepicker__calendar header .prev:after {\n border-right: 10px solid #000;\n margin-left: -5px;\n}\n.vdp-datepicker__calendar header .prev.disabled:after {\n border-right: 10px solid #ddd;\n}\n.vdp-datepicker__calendar header .next:after {\n border-left: 10px solid #000;\n margin-left: 5px;\n}\n.vdp-datepicker__calendar header .next.disabled:after {\n border-left: 10px solid #ddd;\n}\n.vdp-datepicker__calendar header .prev:not(.disabled),\n.vdp-datepicker__calendar header .next:not(.disabled),\n.vdp-datepicker__calendar header .up:not(.disabled) {\n cursor: pointer;\n}\n.vdp-datepicker__calendar header .prev:not(.disabled):hover,\n.vdp-datepicker__calendar header .next:not(.disabled):hover,\n.vdp-datepicker__calendar header .up:not(.disabled):hover {\n background: #eee;\n}\n.vdp-datepicker__calendar .disabled {\n color: #ddd;\n cursor: default;\n}\n.vdp-datepicker__calendar .flex-rtl {\n display: -webkit-box;\n display: -ms-flexbox;\n display: flex;\n width: inherit;\n -ms-flex-wrap: wrap;\n flex-wrap: wrap;\n}\n.vdp-datepicker__calendar .cell {\n display: inline-block;\n padding: 0 5px;\n width: 14.285714285714286%;\n height: 40px;\n line-height: 40px;\n text-align: center;\n vertical-align: middle;\n border: 1px solid transparent;\n}\n.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).day,\n.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).month,\n.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).year {\n cursor: pointer;\n}\n.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).day:hover,\n.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).month:hover,\n.vdp-datepicker__calendar .cell:not(.blank):not(.disabled).year:hover {\n border: 1px solid #4bd;\n}\n.vdp-datepicker__calendar .cell.selected {\n background: #4bd;\n}\n.vdp-datepicker__calendar .cell.selected:hover {\n background: #4bd;\n}\n.vdp-datepicker__calendar .cell.selected.highlighted {\n background: #4bd;\n}\n.vdp-datepicker__calendar .cell.highlighted {\n background: #cae5ed;\n}\n.vdp-datepicker__calendar .cell.grey {\n color: #888;\n}\n.vdp-datepicker__calendar .cell.grey:hover {\n background: inherit;\n}\n.vdp-datepicker__calendar .cell.day-header {\n font-size: 75%;\n white-space: no-wrap;\n cursor: inherit;\n}\n.vdp-datepicker__calendar .cell.day-header:hover {\n background: inherit;\n}\n.vdp-datepicker__calendar .month,\n.vdp-datepicker__calendar .year {\n width: 33.333%;\n}\n.vdp-datepicker__clear-button,\n.vdp-datepicker__calendar-button {\n cursor: pointer;\n font-style: normal;\n}\n.vdp-datepicker__clear-button.disabled,\n.vdp-datepicker__calendar-button.disabled {\n color: #999;\n cursor: default;\n}"],sourceRoot:""}])},function(t,e){function n(t,e){var n=t[1]||"",r=t[3];if(!r)return n;if(e&&"function"==typeof btoa){var i=function(t){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(t))))+" */"}(r);return[n].concat(r.sources.map(function(t){return"/*# sourceURL="+r.sourceRoot+t+" */"})).concat([i]).join("\n")}return[n].join("\n")}t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var r=n(e,t);return e[2]?"@media "+e[2]+"{"+r+"}":r}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},i=0;i<this.length;i++){var o=this[i][0];"number"==typeof o&&(r[o]=!0)}for(i=0;i<t.length;i++){var a=t[i];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},function(t,e,n){var r=n(38)(n(37),n(39),function(t){n(40)},null,null);t.exports=r.exports},function(t,e,n){function r(t){for(var e=0;e<t.length;e++){var n=t[e],r=c[n.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](n.parts[i]);for(;i<n.parts.length;i++)r.parts.push(o(n.parts[i]));r.parts.length>n.parts.length&&(r.parts.length=n.parts.length)}else{var a=[];for(i=0;i<n.parts.length;i++)a.push(o(n.parts[i]));c[n.id]={id:n.id,refs:1,parts:a}}}}function i(){var t=document.createElement("style");return t.type="text/css",u.appendChild(t),t}function o(t){var e,n,r=document.querySelector('style[data-vue-ssr-id~="'+t.id+'"]');if(r){if(h)return p;r.parentNode.removeChild(r)}if(v){var o=d++;r=f||(f=i()),e=a.bind(null,r,o,!1),n=a.bind(null,r,o,!0)}else r=i(),e=function(t,e){var n=e.css,r=e.media,i=e.sourceMap;if(r&&t.setAttribute("media",r),i&&(n+="\n/*# sourceURL="+i.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */"),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}.bind(null,r),n=function(){r.parentNode.removeChild(r)};return e(t),function(r){if(r){if(r.css===t.css&&r.media===t.media&&r.sourceMap===t.sourceMap)return;e(t=r)}else n()}}function a(t,e,n,r){var i=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=g(e,i);else{var o=document.createTextNode(i),a=t.childNodes;a[e]&&t.removeChild(a[e]),a.length?t.insertBefore(o,a[e]):t.appendChild(o)}}var s="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!s)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var l=n(78),c={},u=s&&(document.head||document.getElementsByTagName("head")[0]),f=null,d=0,h=!1,p=function(){},v="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());t.exports=function(t,e,n){h=n;var i=l(t,e);return r(i),function(e){for(var n=[],o=0;o<i.length;o++){var a=i[o];(s=c[a.id]).refs--,n.push(s)}for(e?r(i=l(t,e)):i=[],o=0;o<n.length;o++){var s;if(0===(s=n[o]).refs){for(var u=0;u<s.parts.length;u++)s.parts[u]();delete c[s.id]}}}};var g=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e){t.exports=function(t,e){for(var n=[],r={},i=0;i<e.length;i++){var o=e[i],a=o[0],s={id:t+":"+i,css:o[1],media:o[2],sourceMap:o[3]};r[a]?r[a].parts.push(s):n.push(r[a]={id:a,parts:[s]})}return n}}])},XgyI:function(t,e,n){var r=n("VU/8")(n("YCkH"),n("7psb"),!1,null,null,null);t.exports=r.exports},Xxa5:function(t,e,n){t.exports=n("jyFz")},YCkH:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW");e.default={props:{active:{required:!0,type:String}},data:function(){return{faBolt:r.d,faCalendarAlt:r.e,faCircle:r.g,faClipboardList:r.h,faComments:r.k,faFileAlt:r.n,faTasks:r.v,hasUnreadMessage:!1}},computed:{displayUnreadMessageBadge:function(){return this.hasUnreadMessage&&!this.isTabActive("messages")}},methods:{activateThisTab:function(t){this.$emit("activate",t)},isTabActive:function(t){return this.active===t},onMessagePushed:function(){this.setHasUnreadMessage(!this.isTabActive("messages"))},onMessagesTabClicked:function(){this.setHasUnreadMessage(!1),this.activateThisTab("messages"),EventBus.$emit("clear-title-notification")},setHasUnreadMessage:function(t){this.hasUnreadMessage=t}},mounted:function(){EventBus.$on("messagePushed",this.onMessagePushed)}}},Yl9i:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("AmgE");n.n(r),e.default={props:["resource","resourceType"],data:function(){return{faEllipsisH:r.faEllipsisH}}}},Z4Xw:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.messageBoxShown?n("div",{attrs:{id:"direct-message-box"},on:{focus:function(e){t.clearTitleNotification()}}},[n("div",{staticClass:"fixed pin-t bg-white text-lg rounded mx-auto md:w-1/2 mt-16 pt-6 shadow-lg z-50 pin-x"},[n("div",{staticClass:"bg-white text-2xl text-grey-dark text-center px-8 pb-2"},[t._v("\n Your Messages\n ")]),t._v(" "),n("div",{staticClass:"py-2 bg-grey-lighter"},[n("div",{staticClass:"text-sm text-center text-grey-dark"},[t._v("Send direct meesage")]),t._v(" "),n("div",{staticClass:"flex flex-row justify-center px-4 py-2"},t._l(t.users,function(e){return e.id!==t.authUser.id?n("div",{on:{click:function(n){t.selectUserMessage(e)}}},[n("img",{staticClass:"w-10 h-10 rounded-full md:mr-2 cursor-pointer",attrs:{title:e.name,src:t.generateUrl(e.avatar)}})]):t._e()}))]),t._v(" "),n("div",{staticClass:"h-50-vh overflow-y-auto",attrs:{id:"message-box"}},[t.selectedUser.id?n("div",t._l(t.messages,function(e,r){return n("message",{key:r,attrs:{message:e,user:t.authUser,index:r},on:{deleted:t.deleteMessage}})})):n("div",{staticClass:"text-grey-dark text-sm text-center",staticStyle:{"margin-top":"20vh"}},[t._v("\n Click on the profile pic above to see interaction with that user\n ")])]),t._v(" "),n("div",{staticClass:"relative bg-grey-light"},[n("div",{staticClass:"static text-center p-4"},[n("textarea",{directives:[{name:"model",rawName:"v-model",value:t.message,expression:"message"}],ref:"messageTextarea",staticClass:"static textarea resize-none rounded w-full p-4 text-grey-darker",style:{height:t.messageTextareaHeight},attrs:{id:"send-message",placeholder:t._f("localize")("write your message here"),rows:"1",disabled:t.isDisabled},domProps:{value:t.message},on:{keydown:function(e){if(!("button"in e)&&t._k(e.keyCode,"enter",13,e.key))return null;e.preventDefault(),t.sendMessage(e)},input:function(e){e.target.composing||(t.message=e.target.value)}}})])])]),t._v(" "),n("div",{staticClass:"h-screen w-screen fixed pin bg-grey-darkest opacity-25",on:{click:t.hideMessageBox}})]):t._e()},staticRenderFns:[]}},aWzK:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW");e.default={data:function(){return{notificationShown:!1,message:"",messageType:"",faTimes:r.w}},created:function(){EventBus.$on("notification",this.showNotification)},beforeDestroy:function(){EventBus.$off("notification",this.showNotification)},methods:{closeNotification:function(){this.notificationShown=!1},showNotification:function(t,e){var n=this;this.message=t,this.messageType=e,this.notificationShown=!0,setTimeout(function(){n.closeNotification()},3e3)}}}},bgwq:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",[n("div",{staticClass:"absolute container mx-auto mb-8 w-5/6 md:w-md lg:w-lg xl:w-xl bg-white rounded shadow-lg z-10",class:{hidden:!t.formShown},staticStyle:{top:"12vh",left:"0",right:"0"}},[n("div",{},[n("div",{staticClass:"p-4 bg-grey-lighter"},[t._m(0),t._v(" "),n("input",{directives:[{name:"model",rawName:"v-model",value:t.name,expression:"name"}],ref:"inputFocus",staticClass:"appearance-none block w-full bg-white text-grey-darker border border-grey-lighter rounded py-3 px-4",attrs:{id:"grid-last-name",type:"text",placeholder:"New Discussion Post",required:""},domProps:{value:t.name},on:{input:function(e){e.target.composing||(t.name=e.target.value)}}})]),t._v(" "),n("div",{staticClass:"p-4 bg-grey-lighter"},[t._m(1),t._v(" "),n("select",{directives:[{name:"model",rawName:"v-model",value:t.categoryId,expression:"categoryId"}],staticClass:"appearance-none block w-full bg-white text-grey-darker border border-grey-lighter rounded py-3 px-4",on:{change:function(e){var n=Array.prototype.filter.call(e.target.options,function(t){return t.selected}).map(function(t){return"_value"in t?t._value:t.value});t.categoryId=e.target.multiple?n:n[0]}}},[n("option",{attrs:{value:"",disabled:""}},[t._v("Choose one")]),t._v(" "),t._l(t.categories,function(e){return n("option",{domProps:{value:e.id}},[t._v(t._s(e.name))])})],2)]),t._v(" "),t._m(2)]),t._v(" "),n("div",{staticClass:"flex flex-row justify-between px-4 bg-white rounded-b"},[n("button",{staticClass:"no-underline px-3 py-2 my-4 bg-white text-base text-red-light rounded border-red-light border",on:{click:t.closeEditor}},[t._v("Cancel")]),t._v(" "),n("div",[n("button",{staticClass:"no-underline px-3 py-2 mr-4 my-4 text-teal-light text-base bg-white font-medium rounded border-teal-light border",on:{click:function(e){t.savePost(!0)}}},[t._v("Save as a Draft")]),t._v(" "),n("button",{staticClass:"no-underline px-3 py-2 my-4 bg-teal-light text-base text-white font-medium rounded",on:{click:function(e){t.savePost(!1)}}
},[t._v("Publish")])])])]),t._v(" "),n("div",{staticClass:"h-screen w-screen fixed pin bg-grey-darkest opacity-25",class:{hidden:!t.formShown},on:{click:t.closeEditor}})])},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[this._v("\n Title "),e("span",{staticClass:"text-grey capitalize"},[this._v("(required)")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[this._v("\n Category "),e("span",{staticClass:"text-grey capitalize"},[this._v("(required)")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"p-4 bg-grey-lighter"},[e("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[this._v("\n Body "),e("span",{staticClass:"text-grey capitalize"},[this._v("(required)")])]),this._v(" "),e("div",{staticClass:"h-80 bg-white",attrs:{id:"editor"}})])}]}},chEw:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=[],i="M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z";e.definition={prefix:"fas",iconName:"plus",icon:[448,512,r,"f067",i]},e.faPlus=e.definition,e.prefix="fas",e.iconName="plus",e.width=448,e.height=512,e.ligatures=r,e.unicode="f067",e.svgPathData=i},dBZW:function(t,e,n){var r=n("VU/8")(n("fDZG"),n("FlIk"),!1,null,null,null);t.exports=r.exports},dDoS:function(t,e){function n(t){return"function"==typeof t.value||(console.warn("[Vue-click-outside:] provided expression",t.expression,"is not a function."),!1)}function r(t){return void 0!==t.componentInstance&&t.componentInstance.$isServer}t.exports={bind:function(t,e,i){function o(e){if(i.context){var n=e.path||e.composedPath&&e.composedPath();n&&n.length>0&&n.unshift(e.target),t.contains(e.target)||function(t,e){if(!t||!e)return!1;for(var n=0,r=e.length;n<r;n++)try{if(t.contains(e[n]))return!0;if(e[n].contains(t))return!1}catch(t){return!1}return!1}(i.context.popupItem,n)||t.__vueClickOutside__.callback(e)}}n(e)&&(t.__vueClickOutside__={handler:o,callback:e.value},!r(i)&&document.addEventListener("click",o))},update:function(t,e){n(e)&&(t.__vueClickOutside__.callback=e.value)},unbind:function(t,e,n){!r(n)&&document.removeEventListener("click",t.__vueClickOutside__.handler),delete t.__vueClickOutside__}}},dcwu:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"px-4 self-center"},[n("div",{directives:[{name:"click-outside",rawName:"v-click-outside",value:t.hideNotification,expression:"hideNotification"}],staticClass:"text-teal-light text-base no-underline cursor-pointer",attrs:{id:"notification"},on:{click:t.toggleNotification}},[n("font-awesome-icon",{staticClass:"font-bold text-xl",attrs:{icon:t.faBell}}),t._v(" "),t.unreadNotification?n("font-awesome-icon",{staticClass:"text-red-light text-xs absolute pin-t mt-3 ml-3",attrs:{icon:t.faCircle,"aria-hidden":"true"}}):t._e()],1),t._v(" "),t.notificationShown?n("div",{staticClass:"absolute bg-white w-64 mt-5 mr-8 py-4 shadow-lg rounded z-50",staticStyle:{right:"5%"}},[t._l(t.notifications,function(e){return t.notifications.length>0?n("a",{staticClass:"flex flex-row items-center list-reset px-4 py-2 text-grey-dark no-underline block",attrs:{href:"#"}},[n("img",{staticClass:"w-10 h-10 rounded-full mr-2",attrs:{src:t.generateUrl(e.data.subject.avatar)}}),t._v(" "),n("div",[n("div",{staticClass:"py-1 text-sm"},[n("a",{staticClass:"no-underline text-blue-light",attrs:{href:"/users/"+e.data.subject.username}},[t._v(t._s(e.data.subject.name))]),t._v("\n "+t._s(e.data.action)+"\n "),n("a",{staticClass:"no-underline text-blue-light",attrs:{href:e.data.object_type+"/"+e.data.object_id}},[t._v(t._s(e.data.object_name))])]),t._v(" "),n("div",{staticClass:"py-1 text-xs"},[t._v("\n "+t._s(e.date)+"\n ")])])]):t._e()}),t._v(" "),0===t.notifications.length?n("div",{staticClass:"px-4 py-2 text-sm text-grey-dark block"},[t._v("No unread notifications. You're all caught up")]):t._e(),t._v(" "),n("span",{staticClass:"block border-t"}),t._v(" "),n("a",{staticClass:"list-reset px-4 pt-2 text-blue-light text-center no-underline block",attrs:{href:"/notifications"}},[t._v("\n View All\n ")])],2):t._e()])},staticRenderFns:[]}},"e/o1":function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("DnYK"),i=n.n(r),o=n("8zbO"),a=n.n(o),s=n("7K14"),l=n.n(s),c=n("xv6y"),u=n.n(c),f=n("n14q"),d=n.n(f),h=n("wmlM"),p=n.n(h),v=n("y8Kx"),g=n.n(v),m=n("/r2q"),y=n.n(m),b=n("84B/"),w=n.n(b),_=n("XgyI"),x=n.n(_),k=n("chEw"),q=(n.n(k),n("08EX"));n.n(q),e.default={components:{taskBoard:i.a,discussionBoard:a.a,messagesBoard:l.a,eventBoard:u.a,fileBoard:d.a,activity:p.a,addMemberForm:g.a,membersListModal:w.a,tabMenu:x.a,showGithubRepo:y.a},props:["office"],data:function(){return{addMemberFormShown:!1,active:"tasks",dropdownMenuShown:!1,githubRepoModalShown:!1,membersListModalShown:!1,faPlus:k.faPlus,faCog:q.faCog}},created:function(){var t=new URL(location.href).searchParams.get("tool");null!==t&&-1!==["tasks","discussions","messages","events","files","activities"].indexOf(t)&&(this.active=t)},methods:{showAddMemberForm:function(){this.addMemberFormShown=!0},closeAddMemberForm:function(){this.addMemberFormShown=!1},addMember:function(t){var e=void 0;t.user?(this.message=t.message,e="success",this.office.members.push(t.user)):(e="error",this.message=t.message),this.addMemberFormShown=!1,EventBus.$emit("notification",t.message,e)},showMembersListModal:function(){this.membersListModalShown=!0},closeMembersListModal:function(){this.membersListModalShown=!1},activateTab:function(t){t!==this.active&&(this.active=t)},toggleDropdownMenu:function(){this.dropdownMenuShown=!this.dropdownMenuShown},closeDropdownMenu:function(){this.dropdownMenuShown=!1},showGithubRepoModal:function(){this.githubRepoModalShown=!0},closeGithubRepoModal:function(){this.githubRepoModalShown=!1}}}},eSzc:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.taskDetailsShown?n("div",[n("div",{staticClass:"absolute container mx-auto md:w-3/4 lg:2/3 xl:w-1/2 xxl:w-2/5 bg-white rounded shadow-lg z-10 pt-4 pb-4 mb-16",staticStyle:{top:"12vh",left:"0",right:"0"}},[n("div",{staticClass:"flex flex-row justify-between px-8 pb-4 relative"},[n("div",{staticClass:"cursor-pointer",on:{click:t.closeTaskDetails}},[n("font-awesome-icon",{staticClass:"text-base text-grey-dark",attrs:{icon:t.faArrowLeft}})],1),t._v(" "),n("div",{directives:[{name:"click-outside",rawName:"v-click-outside",value:t.hideMenu,expression:"hideMenu"}],staticClass:"cursor-pointer",on:{click:t.toggleMenu}},[n("font-awesome-icon",{staticClass:"text-base text-grey-dark",attrs:{icon:t.faEllipsisH}})],1),t._v(" "),t.dropdownMenuShown?n("div",{staticClass:"absolute rounded shadow-lg pin-r pin-t mt-6 mr-4 p-3 text-grey-darker"},[n("div",{staticClass:"cursor-pointer",on:{click:t.deleteTask}},[t._v("\n Delete\n ")])]):t._e()]),t._v(" "),n("div",{staticClass:"text-2xl text-grey-darker text-center font-semibold px-8 py-4"},[t._v("\n "+t._s(t.task.name)+"\n ")]),t._v(" "),n("div",{staticClass:"flex flex-row flex-wrap justify-between pt-4"},[n("div",[n("div",{staticClass:"text-sm text-grey-dark px-8"},[t._v("\n Assignee\n ")]),t._v(" "),n("div",{staticClass:"px-8 py-2"},[n("a",{attrs:{href:"/users/"+t.task.user.username}},[t.task.assigned_to?n("img",{staticClass:"rounded-full w-8 h-8 mx-2 self-start",attrs:{src:t.generateUrl(t.task.user.avatar)}}):t._e()])])]),t._v(" "),n("div",{staticClass:"text-center"},[n("div",{staticClass:"text-sm text-grey-dark px-8"},[t._v("\n Due Date\n ")]),t._v(" "),n("div",{staticClass:"px-8 py-2 text-grey-darkest"},[t._v("\n "+t._s(t.task.due_on)+"\n ")])]),t._v(" "),t._m(0),t._v(" "),n("div",{staticClass:"text-center"},[n("div",{staticClass:"text-sm text-grey-dark px-8"},[t._v("\n Related To\n ")]),t._v(" "),n("div",{staticClass:"px-8 py-2",class:[t.task.related_to?"text-blue underline":"text-grey-dark"]},[t._v("\n "+t._s(t.task.related_to?t.task.related_to:"None")+"\n ")])])]),t._v(" "),n("div",{staticClass:"text-sm text-grey-dark px-8 pt-4"},[t._v("\n Details\n ")]),t._v(" "),n("div",{staticClass:"text-grey-darkest text-lg px-8 py-2"},[t._v("\n "+t._s(t.task.notes)+"\n ")]),t._v(" "),n("div",{staticClass:"text-sm text-grey-dark px-8 pt-4"},[t._v("\n Tags\n ")]),t._v(" "),t._m(1),t._v(" "),t._m(2),t._v(" "),n("div",{staticClass:"px-2 md:px-8"},[n("comment-box",{attrs:{resourceType:"task",resource:t.task,detailsShown:t.taskDetailsShown}})],1)]),t._v(" "),n("div",{staticClass:"h-screen w-screen fixed pin bg-grey-darkest opacity-25",class:{hidden:!t.taskDetailsShown},on:{click:t.closeTaskDetails}})]):t._e()},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"text-center"},[e("div",{staticClass:"text-sm text-grey-dark px-8"},[this._v("\n Status\n ")]),this._v(" "),e("div",{staticClass:"px-8 py-2 text-green-dark"},[this._v("\n In Progress\n ")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"flex flex-row justify-start px-8 py-4 -ml-2"},[e("div",{staticClass:"bg-blue-light px-2 py-1 rounded-full text-white text-sm mx-2"},[this._v("frontend")]),this._v(" "),e("div",{staticClass:"bg-blue-light px-2 py-1 rounded-full text-white text-sm mx-2"},[this._v("backend")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"flex flex-row justify-around bg-grey-lighter py-4 mt-4 text-grey-dark text-center"},[e("div",{staticClass:"w-1/2 border-teal border-b-2 pb-4 -mb-4"},[this._v("\n Comments\n ")]),this._v(" "),e("div",{staticClass:"w-1/2"},[this._v("\n Progress\n ")])])}]}},fDZG:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW");e.default={data:function(){return{user:navbar.user,token:Laravel.csrfToken,url:navbar.navUrl,avatar:"",profileUrl:navbar.navUrl.site+"/users/"+navbar.user.username,profileDropdownShown:!1,faAngleDown:r.a,faCog:r.j,faShieldAlt:r.s,faSignOutAlt:r.t,faUser:r.y,faEnvelope:r.m}},methods:{logoutUser:function(t){t.preventDefault(),document.getElementById("logout-form").submit()},toggleProfileDropdown:function(t){this.profileDropdownShown?(this.hideProfileDropdown(t),document.body.removeEventListener("keyup",this.hideProfileDropdown)):(this.showProfileDropdown(),document.body.addEventListener("keyup",this.hideProfileDropdown))},showProfileDropdown:function(t){this.notificationShown&&(this.notificationShown=!1),this.profileDropdownShown=!0},hideProfileDropdown:function(t){if("keyup"===t.type&&"Escape"!==t.key)return!1;this.profileDropdownShown=!1}}}},fhbW:function(t,e,n){"use strict";n.d(e,"a",function(){return r}),n.d(e,"b",function(){return i}),n.d(e,"c",function(){return o}),n.d(e,"d",function(){return a}),n.d(e,"e",function(){return s}),n.d(e,"f",function(){return l}),n.d(e,"g",function(){return c}),n.d(e,"h",function(){return u}),n.d(e,"i",function(){return f}),n.d(e,"j",function(){return d}),n.d(e,"k",function(){return h}),n.d(e,"l",function(){return p}),n.d(e,"m",function(){return v}),n.d(e,"n",function(){return g}),n.d(e,"o",function(){return m}),n.d(e,"p",function(){return y}),n.d(e,"q",function(){return b}),n.d(e,"r",function(){return w}),n.d(e,"s",function(){return _}),n.d(e,"t",function(){return x}),n.d(e,"u",function(){return k}),n.d(e,"v",function(){return q}),n.d(e,"w",function(){return O}),n.d(e,"x",function(){return A}),n.d(e,"y",function(){return C});var r={prefix:"fas",iconName:"angle-down",icon:[320,512,[],"f107","M143 352.3L7 216.3c-9.4-9.4-9.4-24.6 0-33.9l22.6-22.6c9.4-9.4 24.6-9.4 33.9 0l96.4 96.4 96.4-96.4c9.4-9.4 24.6-9.4 33.9 0l22.6 22.6c9.4 9.4 9.4 24.6 0 33.9l-136 136c-9.2 9.4-24.4 9.4-33.8 0z"]},i={prefix:"fas",iconName:"arrow-left",icon:[448,512,[],"f060","M257.5 445.1l-22.2 22.2c-9.4 9.4-24.6 9.4-33.9 0L7 273c-9.4-9.4-9.4-24.6 0-33.9L201.4 44.7c9.4-9.4 24.6-9.4 33.9 0l22.2 22.2c9.5 9.5 9.3 25-.4 34.3L136.6 216H424c13.3 0 24 10.7 24 24v32c0 13.3-10.7 24-24 24H136.6l120.5 114.8c9.8 9.3 10 24.8.4 34.3z"]},o={prefix:"fas",iconName:"bell",icon:[448,512,[],"f0f3","M224 512c35.32 0 63.97-28.65 63.97-64H160.03c0 35.35 28.65 64 63.97 64zm215.39-149.71c-19.32-20.76-55.47-51.99-55.47-154.29 0-77.7-54.48-139.9-127.94-155.16V32c0-17.67-14.32-32-31.98-32s-31.98 14.33-31.98 32v20.84C118.56 68.1 64.08 130.3 64.08 208c0 102.3-36.15 133.53-55.47 154.29-6 6.45-8.66 14.16-8.61 21.71.11 16.4 12.98 32 32.1 32h383.8c19.12 0 32-15.6 32.1-32 .05-7.55-2.61-15.27-8.61-21.71z"]},a={prefix:"fas",iconName:"bolt",icon:[320,512,[],"f0e7","M295.973 160H180.572L215.19 30.184C219.25 14.956 207.756 0 192 0H56C43.971 0 33.8 8.905 32.211 20.828l-31.996 240C-1.704 275.217 9.504 288 24.004 288h118.701L96.646 482.466C93.05 497.649 104.659 512 119.992 512c8.35 0 16.376-4.374 20.778-11.978l175.973-303.997c9.244-15.967-2.288-36.025-20.77-36.025z"]},s={prefix:"fas",iconName:"calendar-alt",icon:[448,512,[],"f073","M436 160H12c-6.6 0-12-5.4-12-12v-36c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48v36c0 6.6-5.4 12-12 12zM12 192h424c6.6 0 12 5.4 12 12v260c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V204c0-6.6 5.4-12 12-12zm116 204c0-6.6-5.4-12-12-12H76c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm0-128c0-6.6-5.4-12-12-12H76c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm128 128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm0-128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm128 128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40zm0-128c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-40z"]},l={prefix:"fas",iconName:"chevron-down",icon:[448,512,[],"f078","M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z"]},c={prefix:"fas",iconName:"circle",icon:[512,512,[],"f111","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8z"]},u={prefix:"fas",iconName:"clipboard-list",icon:[384,512,[],"f46d","M336 64h-80c0-35.3-28.7-64-64-64s-64 28.7-64 64H48C21.5 64 0 85.5 0 112v352c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V112c0-26.5-21.5-48-48-48zM96 424c-13.3 0-24-10.7-24-24s10.7-24 24-24 24 10.7 24 24-10.7 24-24 24zm0-96c-13.3 0-24-10.7-24-24s10.7-24 24-24 24 10.7 24 24-10.7 24-24 24zm0-96c-13.3 0-24-10.7-24-24s10.7-24 24-24 24 10.7 24 24-10.7 24-24 24zm96-192c13.3 0 24 10.7 24 24s-10.7 24-24 24-24-10.7-24-24 10.7-24 24-24zm128 368c0 4.4-3.6 8-8 8H168c-4.4 0-8-3.6-8-8v-16c0-4.4 3.6-8 8-8h144c4.4 0 8 3.6 8 8v16zm0-96c0 4.4-3.6 8-8 8H168c-4.4 0-8-3.6-8-8v-16c0-4.4 3.6-8 8-8h144c4.4 0 8 3.6 8 8v16zm0-96c0 4.4-3.6 8-8 8H168c-4.4 0-8-3.6-8-8v-16c0-4.4 3.6-8 8-8h144c4.4 0 8 3.6 8 8v16z"]},f={prefix:"fas",iconName:"clock",icon:[512,512,[],"f017","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm57.1 350.1L224.9 294c-3.1-2.3-4.9-5.9-4.9-9.7V116c0-6.6 5.4-12 12-12h48c6.6 0 12 5.4 12 12v137.7l63.5 46.2c5.4 3.9 6.5 11.4 2.6 16.8l-28.2 38.8c-3.9 5.3-11.4 6.5-16.8 2.6z"]},d={prefix:"fas",iconName:"cog",icon:[512,512,[],"f013","M444.788 291.1l42.616 24.599c4.867 2.809 7.126 8.618 5.459 13.985-11.07 35.642-29.97 67.842-54.689 94.586a12.016 12.016 0 0 1-14.832 2.254l-42.584-24.595a191.577 191.577 0 0 1-60.759 35.13v49.182a12.01 12.01 0 0 1-9.377 11.718c-34.956 7.85-72.499 8.256-109.219.007-5.49-1.233-9.403-6.096-9.403-11.723v-49.184a191.555 191.555 0 0 1-60.759-35.13l-42.584 24.595a12.016 12.016 0 0 1-14.832-2.254c-24.718-26.744-43.619-58.944-54.689-94.586-1.667-5.366.592-11.175 5.459-13.985L67.212 291.1a193.48 193.48 0 0 1 0-70.199l-42.616-24.599c-4.867-2.809-7.126-8.618-5.459-13.985 11.07-35.642 29.97-67.842 54.689-94.586a12.016 12.016 0 0 1 14.832-2.254l42.584 24.595a191.577 191.577 0 0 1 60.759-35.13V25.759a12.01 12.01 0 0 1 9.377-11.718c34.956-7.85 72.499-8.256 109.219-.007 5.49 1.233 9.403 6.096 9.403 11.723v49.184a191.555 191.555 0 0 1 60.759 35.13l42.584-24.595a12.016 12.016 0 0 1 14.832 2.254c24.718 26.744 43.619 58.944 54.689 94.586 1.667 5.366-.592 11.175-5.459 13.985L444.788 220.9a193.485 193.485 0 0 1 0 70.2zM336 256c0-44.112-35.888-80-80-80s-80 35.888-80 80 35.888 80 80 80 80-35.888 80-80z"]},h={prefix:"fas",iconName:"comments",icon:[576,512,[],"f086","M416 192c0-88.4-93.1-160-208-160S0 103.6 0 192c0 34.3 14.1 65.9 38 92-13.4 30.2-35.5 54.2-35.8 54.5-2.2 2.3-2.8 5.7-1.5 8.7S4.8 352 8 352c36.6 0 66.9-12.3 88.7-25 32.2 15.7 70.3 25 111.3 25 114.9 0 208-71.6 208-160zm122 220c23.9-26 38-57.7 38-92 0-66.9-53.5-124.2-129.3-148.1.9 6.6 1.3 13.3 1.3 20.1 0 105.9-107.7 192-240 192-10.8 0-21.3-.8-31.7-1.9C207.8 439.6 281.8 480 368 480c41 0 79.1-9.2 111.3-25 21.8 12.7 52.1 25 88.7 25 3.2 0 6.1-1.9 7.3-4.8 1.3-2.9.7-6.3-1.5-8.7-.3-.3-22.4-24.2-35.8-54.5z"]},p={prefix:"fas",iconName:"ellipsis-h",icon:[512,512,[],"f141","M328 256c0 39.8-32.2 72-72 72s-72-32.2-72-72 32.2-72 72-72 72 32.2 72 72zm104-72c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72zm-352 0c-39.8 0-72 32.2-72 72s32.2 72 72 72 72-32.2 72-72-32.2-72-72-72z"]},v={prefix:"fas",iconName:"envelope",icon:[512,512,[],"f0e0","M502.3 190.8c3.9-3.1 9.7-.2 9.7 4.7V400c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V195.6c0-5 5.7-7.8 9.7-4.7 22.4 17.4 52.1 39.5 154.1 113.6 21.1 15.4 56.7 47.8 92.2 47.6 35.7.3 72-32.8 92.3-47.6 102-74.1 131.6-96.3 154-113.7zM256 320c23.2.4 56.6-29.2 73.4-41.4 132.7-96.3 142.8-104.7 173.4-128.7 5.8-4.5 9.2-11.5 9.2-18.9v-19c0-26.5-21.5-48-48-48H48C21.5 64 0 85.5 0 112v19c0 7.4 3.4 14.3 9.2 18.9 30.6 23.9 40.7 32.4 173.4 128.7 16.8 12.2 50.2 41.8 73.4 41.4z"]},g={prefix:"fas",iconName:"file-alt",icon:[384,512,[],"f15c","M224 136V0H24C10.7 0 0 10.7 0 24v464c0 13.3 10.7 24 24 24h336c13.3 0 24-10.7 24-24V160H248c-13.2 0-24-10.8-24-24zm64 236c0 6.6-5.4 12-12 12H108c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h168c6.6 0 12 5.4 12 12v8zm0-64c0 6.6-5.4 12-12 12H108c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h168c6.6 0 12 5.4 12 12v8zm0-72v8c0 6.6-5.4 12-12 12H108c-6.6 0-12-5.4-12-12v-8c0-6.6 5.4-12 12-12h168c6.6 0 12 5.4 12 12zm96-114.1v6.1H256V0h6.1c6.4 0 12.5 2.5 17 7l97.9 98c4.5 4.5 7 10.6 7 16.9z"]},m={prefix:"fas",iconName:"file-image",icon:[384,512,[],"f1c5","M384 121.941V128H256V0h6.059a24 24 0 0 1 16.97 7.029l97.941 97.941a24.002 24.002 0 0 1 7.03 16.971zM248 160c-13.2 0-24-10.8-24-24V0H24C10.745 0 0 10.745 0 24v464c0 13.255 10.745 24 24 24h336c13.255 0 24-10.745 24-24V160H248zm-135.455 16c26.51 0 48 21.49 48 48s-21.49 48-48 48-48-21.49-48-48 21.491-48 48-48zm208 240h-256l.485-48.485L104.545 328c4.686-4.686 11.799-4.201 16.485.485L160.545 368 264.06 264.485c4.686-4.686 12.284-4.686 16.971 0L320.545 304v112z"]},y={prefix:"fas",iconName:"file-pdf",icon:[384,512,[],"f1c1","M181.9 256.1c-5-16-4.9-46.9-2-46.9 8.4 0 7.6 36.9 2 46.9zm-1.7 47.2c-7.7 20.2-17.3 43.3-28.4 62.7 18.3-7 39-17.2 62.9-21.9-12.7-9.6-24.9-23.4-34.5-40.8zM86.1 428.1c0 .8 13.2-5.4 34.9-40.2-6.7 6.3-29.1 24.5-34.9 40.2zM248 160h136v328c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V24C0 10.7 10.7 0 24 0h200v136c0 13.2 10.8 24 24 24zm-8 171.8c-20-12.2-33.3-29-42.7-53.8 4.5-18.5 11.6-46.6 6.2-64.2-4.7-29.4-42.4-26.5-47.8-6.8-5 18.3-.4 44.1 8.1 77-11.6 27.6-28.7 64.6-40.8 85.8-.1 0-.1.1-.2.1-27.1 13.9-73.6 44.5-54.5 68 5.6 6.9 16 10 21.5 10 17.9 0 35.7-18 61.1-61.8 25.8-8.5 54.1-19.1 79-23.2 21.7 11.8 47.1 19.5 64 19.5 29.2 0 31.2-32 19.7-43.4-13.9-13.6-54.3-9.7-73.6-7.2zM377 105L279 7c-4.5-4.5-10.6-7-17-7h-6v128h128v-6.1c0-6.3-2.5-12.4-7-16.9zm-74.1 255.3c4.1-2.7-2.5-11.9-42.8-9 37.1 15.8 42.8 9 42.8 9z"]},b={prefix:"fas",iconName:"map-marker",icon:[384,512,[],"f041","M172.268 501.67C26.97 291.031 0 269.413 0 192 0 85.961 85.961 0 192 0s192 85.961 192 192c0 77.413-26.97 99.031-172.268 309.67-9.535 13.774-29.93 13.773-39.464 0z"]},w={prefix:"fas",iconName:"plus",icon:[448,512,[],"f067","M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z"]},_={prefix:"fas",iconName:"shield-alt",icon:[512,512,[],"f3ed","M496 128c0 221.282-135.934 344.645-221.539 380.308a48 48 0 0 1-36.923 0C130.495 463.713 16 326.487 16 128a48 48 0 0 1 29.539-44.308l192-80a48 48 0 0 1 36.923 0l192 80A48 48 0 0 1 496 128zM256 446.313l.066.034c93.735-46.689 172.497-156.308 175.817-307.729L256 65.333v380.98z"]},x={prefix:"fas",iconName:"sign-out-alt",icon:[512,512,[],"f2f5","M497 273L329 441c-15 15-41 4.5-41-17v-96H152c-13.3 0-24-10.7-24-24v-96c0-13.3 10.7-24 24-24h136V88c0-21.4 25.9-32 41-17l168 168c9.3 9.4 9.3 24.6 0 34zM192 436v-40c0-6.6-5.4-12-12-12H96c-17.7 0-32-14.3-32-32V160c0-17.7 14.3-32 32-32h84c6.6 0 12-5.4 12-12V76c0-6.6-5.4-12-12-12H96c-53 0-96 43-96 96v192c0 53 43 96 96 96h84c6.6 0 12-5.4 12-12z"]},k={prefix:"fas",iconName:"spinner",icon:[512,512,[],"f110","M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"]},q={prefix:"fas",iconName:"tasks",icon:[512,512,[],"f0ae","M208 132h288c8.8 0 16-7.2 16-16V76c0-8.8-7.2-16-16-16H208c-8.8 0-16 7.2-16 16v40c0 8.8 7.2 16 16 16zm0 160h288c8.8 0 16-7.2 16-16v-40c0-8.8-7.2-16-16-16H208c-8.8 0-16 7.2-16 16v40c0 8.8 7.2 16 16 16zm0 160h288c8.8 0 16-7.2 16-16v-40c0-8.8-7.2-16-16-16H208c-8.8 0-16 7.2-16 16v40c0 8.8 7.2 16 16 16zM64 368c-26.5 0-48.6 21.5-48.6 48s22.1 48 48.6 48 48-21.5 48-48-21.5-48-48-48zm92.5-299l-72.2 72.2-15.6 15.6c-4.7 4.7-12.9 4.7-17.6 0L3.5 109.4c-4.7-4.7-4.7-12.3 0-17l15.7-15.7c4.7-4.7 12.3-4.7 17 0l22.7 22.1 63.7-63.3c4.7-4.7 12.3-4.7 17 0l17 16.5c4.6 4.7 4.6 12.3-.1 17zm0 159.6l-72.2 72.2-15.7 15.7c-4.7 4.7-12.9 4.7-17.6 0L3.5 269c-4.7-4.7-4.7-12.3 0-17l15.7-15.7c4.7-4.7 12.3-4.7 17 0l22.7 22.1 63.7-63.7c4.7-4.7 12.3-4.7 17 0l17 17c4.6 4.6 4.6 12.2-.1 16.9z"]},O={prefix:"fas",iconName:"times",icon:[352,512,[],"f00d","M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"]},A={prefix:"fas",iconName:"trash-alt",icon:[448,512,[],"f2ed","M0 84V56c0-13.3 10.7-24 24-24h112l9.4-18.7c4-8.2 12.3-13.3 21.4-13.3h114.3c9.1 0 17.4 5.1 21.5 13.3L312 32h112c13.3 0 24 10.7 24 24v28c0 6.6-5.4 12-12 12H12C5.4 96 0 90.6 0 84zm416 56v324c0 26.5-21.5 48-48 48H80c-26.5 0-48-21.5-48-48V140c0-6.6 5.4-12 12-12h360c6.6 0 12 5.4 12 12zm-272 68c0-8.8-7.2-16-16-16s-16 7.2-16 16v224c0 8.8 7.2 16 16 16s16-7.2 16-16V208zm96 0c0-8.8-7.2-16-16-16s-16 7.2-16 16v224c0 8.8 7.2 16 16 16s16-7.2 16-16V208zm96 0c0-8.8-7.2-16-16-16s-16 7.2-16 16v224c0 8.8 7.2 16 16 16s16-7.2 16-16V208z"]},C={prefix:"fas",iconName:"user",icon:[448,512,[],"f007","M224 256c70.7 0 128-57.3 128-128S294.7 0 224 0 96 57.3 96 128s57.3 128 128 128zm89.6 32h-16.7c-22.2 10.2-46.9 16-72.9 16s-50.6-5.8-72.9-16h-16.7C60.2 288 0 348.2 0 422.4V464c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48v-41.6c0-74.2-60.2-134.4-134.4-134.4z"]}},fxt6:function(t,e,n){
(t.exports=n("FZ+f")(!1)).push([t.i,'/*!\n * Quill Editor v1.3.6\n * https://quilljs.com/\n * Copyright (c) 2014, Jason Chen\n * Copyright (c) 2013, salesforce.com\n */.ql-container{box-sizing:border-box;font-family:Helvetica,Arial,sans-serif;font-size:13px;height:50vh;margin:0;position:relative}.ql-container.ql-disabled .ql-tooltip{visibility:hidden}.ql-container.ql-disabled .ql-editor ul[data-checked]>li:before{pointer-events:none}.ql-clipboard{left:-100000px;height:1px;overflow-y:hidden;position:absolute;top:50%}.ql-clipboard p{margin:0;padding:0}.ql-editor{box-sizing:border-box;line-height:1.42;height:100%;outline:none;overflow-y:auto;padding:12px 15px;tab-size:4;-moz-tab-size:4;text-align:left;white-space:pre-wrap;word-wrap:break-word}.ql-editor>*{cursor:text}.ql-editor blockquote,.ql-editor h1,.ql-editor h2,.ql-editor h3,.ql-editor h4,.ql-editor h5,.ql-editor h6,.ql-editor ol,.ql-editor p,.ql-editor pre,.ql-editor ul{margin:0;padding:0;counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}.ql-editor ol,.ql-editor ul{padding-left:1.5em}.ql-editor ol>li,.ql-editor ul>li{list-style-type:none}.ql-editor ul>li:before{content:"\\2022"}.ql-editor ul[data-checked=false],.ql-editor ul[data-checked=true]{pointer-events:none}.ql-editor ul[data-checked=false]>li *,.ql-editor ul[data-checked=true]>li *{pointer-events:all}.ql-editor ul[data-checked=false]>li:before,.ql-editor ul[data-checked=true]>li:before{color:#777;cursor:pointer;pointer-events:all}.ql-editor ul[data-checked=true]>li:before{content:"\\2611"}.ql-editor ul[data-checked=false]>li:before{content:"\\2610"}.ql-editor li:before{display:inline-block;white-space:nowrap;width:1.2em}.ql-editor li:not(.ql-direction-rtl):before{margin-left:-1.5em;margin-right:.3em;text-align:right}.ql-editor li.ql-direction-rtl:before{margin-left:.3em;margin-right:-1.5em}.ql-editor ol li:not(.ql-direction-rtl),.ql-editor ul li:not(.ql-direction-rtl){padding-left:1.5em}.ql-editor ol li.ql-direction-rtl,.ql-editor ul li.ql-direction-rtl{padding-right:1.5em}.ql-editor ol li{counter-reset:list-1 list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9;counter-increment:list-0}.ql-editor ol li:before{content:counter(list-0,decimal) ". "}.ql-editor ol li.ql-indent-1{counter-increment:list-1}.ql-editor ol li.ql-indent-1:before{content:counter(list-1,lower-alpha) ". "}.ql-editor ol li.ql-indent-1{counter-reset:list-2 list-3 list-4 list-5 list-6 list-7 list-8 list-9}.ql-editor ol li.ql-indent-2{counter-increment:list-2}.ql-editor ol li.ql-indent-2:before{content:counter(list-2,lower-roman) ". "}.ql-editor ol li.ql-indent-2{counter-reset:list-3 list-4 list-5 list-6 list-7 list-8 list-9}.ql-editor ol li.ql-indent-3{counter-increment:list-3}.ql-editor ol li.ql-indent-3:before{content:counter(list-3,decimal) ". "}.ql-editor ol li.ql-indent-3{counter-reset:list-4 list-5 list-6 list-7 list-8 list-9}.ql-editor ol li.ql-indent-4{counter-increment:list-4}.ql-editor ol li.ql-indent-4:before{content:counter(list-4,lower-alpha) ". "}.ql-editor ol li.ql-indent-4{counter-reset:list-5 list-6 list-7 list-8 list-9}.ql-editor ol li.ql-indent-5{counter-increment:list-5}.ql-editor ol li.ql-indent-5:before{content:counter(list-5,lower-roman) ". "}.ql-editor ol li.ql-indent-5{counter-reset:list-6 list-7 list-8 list-9}.ql-editor ol li.ql-indent-6{counter-increment:list-6}.ql-editor ol li.ql-indent-6:before{content:counter(list-6,decimal) ". "}.ql-editor ol li.ql-indent-6{counter-reset:list-7 list-8 list-9}.ql-editor ol li.ql-indent-7{counter-increment:list-7}.ql-editor ol li.ql-indent-7:before{content:counter(list-7,lower-alpha) ". "}.ql-editor ol li.ql-indent-7{counter-reset:list-8 list-9}.ql-editor ol li.ql-indent-8{counter-increment:list-8}.ql-editor ol li.ql-indent-8:before{content:counter(list-8,lower-roman) ". "}.ql-editor ol li.ql-indent-8{counter-reset:list-9}.ql-editor ol li.ql-indent-9{counter-increment:list-9}.ql-editor ol li.ql-indent-9:before{content:counter(list-9,decimal) ". "}.ql-editor .ql-indent-1:not(.ql-direction-rtl){padding-left:3em}.ql-editor li.ql-indent-1:not(.ql-direction-rtl){padding-left:4.5em}.ql-editor .ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:3em}.ql-editor li.ql-indent-1.ql-direction-rtl.ql-align-right{padding-right:4.5em}.ql-editor .ql-indent-2:not(.ql-direction-rtl){padding-left:6em}.ql-editor li.ql-indent-2:not(.ql-direction-rtl){padding-left:7.5em}.ql-editor .ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:6em}.ql-editor li.ql-indent-2.ql-direction-rtl.ql-align-right{padding-right:7.5em}.ql-editor .ql-indent-3:not(.ql-direction-rtl){padding-left:9em}.ql-editor li.ql-indent-3:not(.ql-direction-rtl){padding-left:10.5em}.ql-editor .ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:9em}.ql-editor li.ql-indent-3.ql-direction-rtl.ql-align-right{padding-right:10.5em}.ql-editor .ql-indent-4:not(.ql-direction-rtl){padding-left:12em}.ql-editor li.ql-indent-4:not(.ql-direction-rtl){padding-left:13.5em}.ql-editor .ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:12em}.ql-editor li.ql-indent-4.ql-direction-rtl.ql-align-right{padding-right:13.5em}.ql-editor .ql-indent-5:not(.ql-direction-rtl){padding-left:15em}.ql-editor li.ql-indent-5:not(.ql-direction-rtl){padding-left:16.5em}.ql-editor .ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:15em}.ql-editor li.ql-indent-5.ql-direction-rtl.ql-align-right{padding-right:16.5em}.ql-editor .ql-indent-6:not(.ql-direction-rtl){padding-left:18em}.ql-editor li.ql-indent-6:not(.ql-direction-rtl){padding-left:19.5em}.ql-editor .ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:18em}.ql-editor li.ql-indent-6.ql-direction-rtl.ql-align-right{padding-right:19.5em}.ql-editor .ql-indent-7:not(.ql-direction-rtl){padding-left:21em}.ql-editor li.ql-indent-7:not(.ql-direction-rtl){padding-left:22.5em}.ql-editor .ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:21em}.ql-editor li.ql-indent-7.ql-direction-rtl.ql-align-right{padding-right:22.5em}.ql-editor .ql-indent-8:not(.ql-direction-rtl){padding-left:24em}.ql-editor li.ql-indent-8:not(.ql-direction-rtl){padding-left:25.5em}.ql-editor .ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:24em}.ql-editor li.ql-indent-8.ql-direction-rtl.ql-align-right{padding-right:25.5em}.ql-editor .ql-indent-9:not(.ql-direction-rtl){padding-left:27em}.ql-editor li.ql-indent-9:not(.ql-direction-rtl){padding-left:28.5em}.ql-editor .ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:27em}.ql-editor li.ql-indent-9.ql-direction-rtl.ql-align-right{padding-right:28.5em}.ql-editor .ql-video{display:block;max-width:100%}.ql-editor .ql-video.ql-align-center{margin:0 auto}.ql-editor .ql-video.ql-align-right{margin:0 0 0 auto}.ql-editor .ql-bg-black{background-color:#000}.ql-editor .ql-bg-red{background-color:#e60000}.ql-editor .ql-bg-orange{background-color:#f90}.ql-editor .ql-bg-yellow{background-color:#ff0}.ql-editor .ql-bg-green{background-color:#008a00}.ql-editor .ql-bg-blue{background-color:#06c}.ql-editor .ql-bg-purple{background-color:#93f}.ql-editor .ql-color-white{color:#fff}.ql-editor .ql-color-red{color:#e60000}.ql-editor .ql-color-orange{color:#f90}.ql-editor .ql-color-yellow{color:#ff0}.ql-editor .ql-color-green{color:#008a00}.ql-editor .ql-color-blue{color:#06c}.ql-editor .ql-color-purple{color:#93f}.ql-editor .ql-font-serif{font-family:Georgia,Times New Roman,serif}.ql-editor .ql-font-monospace{font-family:Monaco,Courier New,monospace}.ql-editor .ql-size-small{font-size:.75em}.ql-editor .ql-size-large{font-size:1.5em}.ql-editor .ql-size-huge{font-size:2.5em}.ql-editor .ql-direction-rtl{direction:rtl;text-align:inherit}.ql-editor .ql-align-center{text-align:center}.ql-editor .ql-align-justify{text-align:justify}.ql-editor .ql-align-right{text-align:right}.ql-editor.ql-blank:before{color:rgba(0,0,0,.6);content:attr(data-placeholder);font-style:italic;left:15px;pointer-events:none;position:absolute;right:15px}.ql-snow.ql-toolbar:after,.ql-snow .ql-toolbar:after{clear:both;content:"";display:table}.ql-snow.ql-toolbar button,.ql-snow .ql-toolbar button{background:none;border:none;cursor:pointer;display:inline-block;float:left;height:24px;padding:3px 5px;width:28px}.ql-snow.ql-toolbar button svg,.ql-snow .ql-toolbar button svg{float:left;height:100%}.ql-snow.ql-toolbar button:active:hover,.ql-snow .ql-toolbar button:active:hover{outline:none}.ql-snow.ql-toolbar input.ql-image[type=file],.ql-snow .ql-toolbar input.ql-image[type=file]{display:none}.ql-snow.ql-toolbar .ql-picker-item.ql-selected,.ql-snow .ql-toolbar .ql-picker-item.ql-selected,.ql-snow.ql-toolbar .ql-picker-item:hover,.ql-snow .ql-toolbar .ql-picker-item:hover,.ql-snow.ql-toolbar .ql-picker-label.ql-active,.ql-snow .ql-toolbar .ql-picker-label.ql-active,.ql-snow.ql-toolbar .ql-picker-label:hover,.ql-snow .ql-toolbar .ql-picker-label:hover,.ql-snow.ql-toolbar button.ql-active,.ql-snow .ql-toolbar button.ql-active,.ql-snow.ql-toolbar button:focus,.ql-snow .ql-toolbar button:focus,.ql-snow.ql-toolbar button:hover,.ql-snow .ql-toolbar button:hover{color:#06c}.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-fill,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-fill,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-fill,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-fill,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke.ql-fill,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-fill,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-fill,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke.ql-fill,.ql-snow.ql-toolbar button.ql-active .ql-fill,.ql-snow .ql-toolbar button.ql-active .ql-fill,.ql-snow.ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-snow .ql-toolbar button.ql-active .ql-stroke.ql-fill,.ql-snow.ql-toolbar button:focus .ql-fill,.ql-snow .ql-toolbar button:focus .ql-fill,.ql-snow.ql-toolbar button:focus .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:focus .ql-stroke.ql-fill,.ql-snow.ql-toolbar button:hover .ql-fill,.ql-snow .ql-toolbar button:hover .ql-fill,.ql-snow.ql-toolbar button:hover .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:hover .ql-stroke.ql-fill{fill:#06c}.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke,.ql-snow.ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-item.ql-selected .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke,.ql-snow.ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-item:hover .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke,.ql-snow.ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-label.ql-active .ql-stroke-miter,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke,.ql-snow.ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-snow .ql-toolbar .ql-picker-label:hover .ql-stroke-miter,.ql-snow.ql-toolbar button.ql-active .ql-stroke,.ql-snow .ql-toolbar button.ql-active .ql-stroke,.ql-snow.ql-toolbar button.ql-active .ql-stroke-miter,.ql-snow .ql-toolbar button.ql-active .ql-stroke-miter,.ql-snow.ql-toolbar button:focus .ql-stroke,.ql-snow .ql-toolbar button:focus .ql-stroke,.ql-snow.ql-toolbar button:focus .ql-stroke-miter,.ql-snow .ql-toolbar button:focus .ql-stroke-miter,.ql-snow.ql-toolbar button:hover .ql-stroke,.ql-snow .ql-toolbar button:hover .ql-stroke,.ql-snow.ql-toolbar button:hover .ql-stroke-miter,.ql-snow .ql-toolbar button:hover .ql-stroke-miter{stroke:#06c}@media (pointer:coarse){.ql-snow.ql-toolbar button:hover:not(.ql-active),.ql-snow .ql-toolbar button:hover:not(.ql-active){color:#444}.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-fill,.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke.ql-fill{fill:#444}.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke,.ql-snow.ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter,.ql-snow .ql-toolbar button:hover:not(.ql-active) .ql-stroke-miter{stroke:#444}}.ql-snow,.ql-snow *{box-sizing:border-box}.ql-snow .ql-hidden{display:none}.ql-snow .ql-out-bottom,.ql-snow .ql-out-top{visibility:hidden}.ql-snow .ql-tooltip{position:absolute;transform:translateY(10px)}.ql-snow .ql-tooltip a{cursor:pointer;text-decoration:none}.ql-snow .ql-tooltip.ql-flip{transform:translateY(-10px)}.ql-snow .ql-formats{display:inline-block;vertical-align:middle}.ql-snow .ql-formats:after{clear:both;content:"";display:table}.ql-snow .ql-stroke{fill:none;stroke:#444;stroke-linecap:round;stroke-linejoin:round;stroke-width:2}.ql-snow .ql-stroke-miter{fill:none;stroke:#444;stroke-miterlimit:10;stroke-width:2}.ql-snow .ql-fill,.ql-snow .ql-stroke.ql-fill{fill:#444}.ql-snow .ql-empty{fill:none}.ql-snow .ql-even{fill-rule:evenodd}.ql-snow .ql-stroke.ql-thin,.ql-snow .ql-thin{stroke-width:1}.ql-snow .ql-transparent{opacity:.4}.ql-snow .ql-direction svg:last-child{display:none}.ql-snow .ql-direction.ql-active svg:last-child{display:inline}.ql-snow .ql-direction.ql-active svg:first-child{display:none}.ql-snow .ql-editor h1{font-size:2em}.ql-snow .ql-editor h2{font-size:1.5em}.ql-snow .ql-editor h3{font-size:1.17em}.ql-snow .ql-editor h4{font-size:1em}.ql-snow .ql-editor h5{font-size:.83em}.ql-snow .ql-editor h6{font-size:.67em}.ql-snow .ql-editor a{text-decoration:underline}.ql-snow .ql-editor blockquote{border-left:4px solid #ccc;margin-bottom:5px;margin-top:5px;padding-left:16px}.ql-snow .ql-editor code,.ql-snow .ql-editor pre{background-color:#f0f0f0;border-radius:3px}.ql-snow .ql-editor pre{white-space:pre-wrap;margin-bottom:5px;margin-top:5px;padding:5px 10px}.ql-snow .ql-editor code{font-size:85%;padding:2px 4px}.ql-snow .ql-editor pre.ql-syntax{background-color:#23241f;color:#f8f8f2;overflow:visible}.ql-snow .ql-editor img{max-width:100%}.ql-snow .ql-picker{color:#444;display:inline-block;float:left;font-size:14px;font-weight:500;height:24px;position:relative;vertical-align:middle}.ql-snow .ql-picker-label{cursor:pointer;display:inline-block;height:100%;padding-left:8px;padding-right:2px;position:relative;width:100%}.ql-snow .ql-picker-label:before{display:inline-block;line-height:22px}.ql-snow .ql-picker-options{background-color:#fff;display:none;min-width:100%;padding:4px 8px;position:absolute;white-space:nowrap}.ql-snow .ql-picker-options .ql-picker-item{cursor:pointer;display:block;padding-bottom:5px;padding-top:5px}.ql-snow .ql-picker.ql-expanded .ql-picker-label{color:#ccc;z-index:2}.ql-snow .ql-picker.ql-expanded .ql-picker-label .ql-fill{fill:#ccc}.ql-snow .ql-picker.ql-expanded .ql-picker-label .ql-stroke{stroke:#ccc}.ql-snow .ql-picker.ql-expanded .ql-picker-options{display:block;margin-top:-1px;top:100%;z-index:1}.ql-snow .ql-color-picker,.ql-snow .ql-icon-picker{width:28px}.ql-snow .ql-color-picker .ql-picker-label,.ql-snow .ql-icon-picker .ql-picker-label{padding:2px 4px}.ql-snow .ql-color-picker .ql-picker-label svg,.ql-snow .ql-icon-picker .ql-picker-label svg{right:4px}.ql-snow .ql-icon-picker .ql-picker-options{padding:4px 0}.ql-snow .ql-icon-picker .ql-picker-item{height:24px;width:24px;padding:2px 4px}.ql-snow .ql-color-picker .ql-picker-options{padding:3px 5px;width:152px}.ql-snow .ql-color-picker .ql-picker-item{border:1px solid transparent;float:left;height:16px;margin:2px;padding:0;width:16px}.ql-snow .ql-picker:not(.ql-color-picker):not(.ql-icon-picker) svg{position:absolute;margin-top:-9px;right:0;top:50%;width:18px}.ql-snow .ql-picker.ql-font .ql-picker-item[data-label]:not([data-label=""]):before,.ql-snow .ql-picker.ql-font .ql-picker-label[data-label]:not([data-label=""]):before,.ql-snow .ql-picker.ql-header .ql-picker-item[data-label]:not([data-label=""]):before,.ql-snow .ql-picker.ql-header .ql-picker-label[data-label]:not([data-label=""]):before,.ql-snow .ql-picker.ql-size .ql-picker-item[data-label]:not([data-label=""]):before,.ql-snow .ql-picker.ql-size .ql-picker-label[data-label]:not([data-label=""]):before{content:attr(data-label)}.ql-snow .ql-picker.ql-header{width:98px}.ql-snow .ql-picker.ql-header .ql-picker-item:before,.ql-snow .ql-picker.ql-header .ql-picker-label:before{content:"Normal"}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]:before,.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]:before{content:"Heading 1"}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]:before,.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]:before{content:"Heading 2"}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]:before,.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]:before{content:"Heading 3"}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]:before,.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]:before{content:"Heading 4"}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]:before,.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]:before{content:"Heading 5"}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]:before,.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]:before{content:"Heading 6"}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]:before{font-size:2em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]:before{font-size:1.5em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]:before{font-size:1.17em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]:before{font-size:1em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]:before{font-size:.83em}.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]:before{font-size:.67em}.ql-snow .ql-picker.ql-font{width:108px}.ql-snow .ql-picker.ql-font .ql-picker-item:before,.ql-snow .ql-picker.ql-font .ql-picker-label:before{content:"Sans Serif"}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]:before,.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=serif]:before{content:"Serif"}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]:before,.ql-snow .ql-picker.ql-font .ql-picker-label[data-value=monospace]:before{content:"Monospace"}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=serif]:before{font-family:Georgia,Times New Roman,serif}.ql-snow .ql-picker.ql-font .ql-picker-item[data-value=monospace]:before{font-family:Monaco,Courier New,monospace}.ql-snow .ql-picker.ql-size{width:98px}.ql-snow .ql-picker.ql-size .ql-picker-item:before,.ql-snow .ql-picker.ql-size .ql-picker-label:before{content:"Normal"}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]:before,.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]:before{content:"Small"}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]:before,.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]:before{content:"Large"}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]:before,.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]:before{content:"Huge"}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]:before{font-size:10px}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]:before{font-size:18px}.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]:before{font-size:32px}.ql-snow .ql-color-picker.ql-background .ql-picker-item{background-color:#fff}.ql-snow .ql-color-picker.ql-color .ql-picker-item{background-color:#000}.ql-toolbar.ql-snow{border:0 solid #ccc;box-sizing:border-box;font-family:Helvetica Neue,Helvetica,Arial,sans-serif;padding:8px;background-color:#bcdefa}.ql-toolbar.ql-snow .ql-formats{margin-right:15px}.ql-toolbar.ql-snow .ql-picker-label{border:1px solid transparent}.ql-toolbar.ql-snow .ql-picker-options{border:1px solid transparent;box-shadow:0 2px 8px rgba(0,0,0,.2)}.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-label,.ql-toolbar.ql-snow .ql-picker.ql-expanded .ql-picker-options{border-color:#ccc}.ql-toolbar.ql-snow .ql-color-picker .ql-picker-item.ql-selected,.ql-toolbar.ql-snow .ql-color-picker .ql-picker-item:hover{border-color:#000}.ql-toolbar.ql-snow+.ql-container.ql-snow{border-top:0}.ql-snow .ql-tooltip{background-color:#fff;border:1px solid #ccc;box-shadow:0 0 5px #ddd;color:#444;padding:5px 12px;white-space:nowrap}.ql-snow .ql-tooltip:before{content:"Visit URL:";line-height:26px;margin-right:8px}.ql-snow .ql-tooltip input[type=text]{display:none;border:1px solid #ccc;font-size:13px;height:26px;margin:0;padding:3px 5px;width:170px}.ql-snow .ql-tooltip a.ql-preview{display:inline-block;max-width:200px;overflow-x:hidden;text-overflow:ellipsis;vertical-align:top}.ql-snow .ql-tooltip a.ql-action:after{border-right:1px solid #ccc;content:"Edit";margin-left:16px;padding-right:8px}.ql-snow .ql-tooltip a.ql-remove:before{content:"Remove";margin-left:8px}.ql-snow .ql-tooltip a{line-height:26px}.ql-snow .ql-tooltip.ql-editing a.ql-preview,.ql-snow .ql-tooltip.ql-editing a.ql-remove{display:none}.ql-snow .ql-tooltip.ql-editing input[type=text]{display:inline-block}.ql-snow .ql-tooltip.ql-editing a.ql-action:after{border-right:0;content:"Save";padding-right:0}.ql-snow .ql-tooltip[data-mode=link]:before{content:"Enter link:"}.ql-snow .ql-tooltip[data-mode=formula]:before{content:"Enter formula:"}.ql-snow .ql-tooltip[data-mode=video]:before{content:"Enter video:"}.ql-snow a{color:#06c}',""])},fyOk:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW");e.default={props:{resourceType:{required:!0,type:String},resource:{required:!0,type:Object},activeTab:{required:!0,type:String}},data:function(){return{events:[],faClock:r.i,faCalendarAlt:r.e,faMapMarker:r.q}}}},"g7/Z":function(t,e,n){var r=n("VU/8")(n("RrJr"),n("7/jY"),!1,null,null,null);t.exports=r.exports},gcBg:function(t,e){t.exports={render:function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"py-4"},[e("div",[e("label",{attrs:{for:"file-upload"}}),this._v(" "),e("input",{ref:"files",staticClass:"hidden",attrs:{type:"file",name:"file-upload",multiple:""},on:{change:this.filesSelected}}),this._v(" "),e("button",{staticClass:"bg-teal-light text-white p-3 rounded shadow-md",on:{click:this.selectFiles}},[this._v("Upload Files")])])])},staticRenderFns:[]}},gpS8:function(t,e,n){var r=n("VU/8")(n("e/o1"),n("HYRr"),!1,null,null,null);t.exports=r.exports},"icw/":function(t,e,n){var r=n("VU/8")(n("xQsn"),n("bgwq"),!1,function(t){n("9Oya")},null,null);t.exports=r.exports},iuzX:function(t,e){!function(){function t(t){this.value=t}function e(e){function n(i,o){try{var a=e[i](o),s=a.value;s instanceof t?Promise.resolve(s.value).then(function(t){n("next",t)},function(t){n("throw",t)}):r(a.done?"return":"normal",a.value)}catch(t){r("throw",t)}}function r(t,e){switch(t){case"return":i.resolve({value:e,done:!0});break;case"throw":i.reject(e);break;default:i.resolve({value:e,done:!1})}(i=i.next)?n(i.key,i.arg):o=null}var i,o;this._invoke=function(t,e){return new Promise(function(r,a){var s={key:t,arg:e,resolve:r,reject:a,next:null};o?o=o.next=s:(i=o=s,n(t,e))})},"function"!=typeof e.return&&(this.return=void 0)}"function"==typeof Symbol&&Symbol.asyncIterator&&(e.prototype[Symbol.asyncIterator]=function(){return this}),e.prototype.next=function(t){return this._invoke("next",t)},e.prototype.throw=function(t){return this._invoke("throw",t)},e.prototype.return=function(t){return this._invoke("return",t)}}();var n=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},o=function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)},a=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e},s=function(){function t(e){n(this,t),this._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",broadcaster:"pusher",csrfToken:null,host:null,key:null,namespace:"App.Events"},this.setOptions(e),this.connect()}return r(t,[{key:"setOptions",value:function(t){return this.options=i(this._defaultOptions,t),this.csrfToken()&&(this.options.auth.headers["X-CSRF-TOKEN"]=this.csrfToken()),t}},{key:"csrfToken",value:function(){var t=void 0;return"undefined"!=typeof window&&window.Laravel&&window.Laravel.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:"undefined"!=typeof document&&(t=document.querySelector('meta[name="csrf-token"]'))?t.getAttribute("content"):null}}]),t}(),l=function(){function t(){n(this,t)}return r(t,[{key:"notification",value:function(t){return this.listen(".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated",t)}},{key:"listenForWhisper",value:function(t,e){return this.listen(".client-"+t,e)}}]),t}(),c=function(){function t(e){n(this,t),this.setNamespace(e)}return r(t,[{key:"format",value:function(t){return"."===t.charAt(0)||"\\"===t.charAt(0)?t.substr(1):(this.namespace&&(t=this.namespace+"."+t),t.replace(/\./g,"\\"))}},{key:"setNamespace",value:function(t){this.namespace=t}}]),t}(),u=function(t){function e(t,r,i){n(this,e);var o=a(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return o.name=r,o.pusher=t,o.options=i,o.eventFormatter=new c(o.options.namespace),o.subscribe(),o}return o(e,l),r(e,[{key:"subscribe",value:function(){this.subscription=this.pusher.subscribe(this.name)}},{key:"unsubscribe",value:function(){this.pusher.unsubscribe(this.name)}},{key:"listen",value:function(t,e){return this.on(this.eventFormatter.format(t),e),this}},{key:"stopListening",value:function(t){return this.subscription.unbind(this.eventFormatter.format(t)),this}},{key:"on",value:function(t,e){return this.subscription.bind(t,e),this}}]),e}(),f=function(t){function e(){return n(this,e),a(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return o(e,u),r(e,[{key:"whisper",value:function(t,e){return this.pusher.channels.channels[this.name].trigger("client-"+t,e),this}}]),e}(),d=function(t){function e(){return n(this,e),a(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return o(e,u),r(e,[{key:"here",value:function(t){return this.on("pusher:subscription_succeeded",function(e){t(Object.keys(e.members).map(function(t){return e.members[t]}))}),this}},{key:"joining",value:function(t){return this.on("pusher:member_added",function(e){t(e.info)}),this}},{key:"leaving",value:function(t){return this.on("pusher:member_removed",function(e){t(e.info)}),this}},{key:"whisper",value:function(t,e){return this.pusher.channels.channels[this.name].trigger("client-"+t,e),this}}]),e}(),h=function(t){function e(t,r,i){n(this,e);var o=a(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return o.events={},o.name=r,o.socket=t,o.options=i,o.eventFormatter=new c(o.options.namespace),o.subscribe(),o.configureReconnector(),o}return o(e,l),r(e,[{key:"subscribe",value:function(){this.socket.emit("subscribe",{channel:this.name,auth:this.options.auth||{}})}},{key:"unsubscribe",value:function(){this.unbind(),this.socket.emit("unsubscribe",{channel:this.name,auth:this.options.auth||{}})}},{key:"listen",value:function(t,e){return this.on(this.eventFormatter.format(t),e),this}},{key:"on",value:function(t,e){var n=this,r=function(t,r){n.name==t&&e(r)};this.socket.on(t,r),this.bind(t,r)}},{key:"configureReconnector",value:function(){var t=this,e=function(){t.subscribe()};this.socket.on("reconnect",e),this.bind("reconnect",e)}},{key:"bind",value:function(t,e){this.events[t]=this.events[t]||[],this.events[t].push(e)}},{key:"unbind",value:function(){var t=this;Object.keys(this.events).forEach(function(e){t.events[e].forEach(function(n){t.socket.removeListener(e,n)}),delete t.events[e]})}}]),e}(),p=function(t){function e(){return n(this,e),a(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return o(e,h),r(e,[{key:"whisper",value:function(t,e){return this.socket.emit("client event",{channel:this.name,event:"client-"+t,data:e}),this}}]),e}(),v=function(t){function e(){return n(this,e),a(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return o(e,p),r(e,[{key:"here",value:function(t){return this.on("presence:subscribed",function(e){t(e.map(function(t){return t.user_info}))}),this}},{key:"joining",value:function(t){return this.on("presence:joining",function(e){return t(e.user_info)}),this}},{key:"leaving",value:function(t){return this.on("presence:leaving",function(e){return t(e.user_info)}),this}}]),e}(),g=function(t){function e(){var t;n(this,e);for(var r=arguments.length,i=Array(r),o=0;o<r;o++)i[o]=arguments[o];var s=a(this,(t=e.__proto__||Object.getPrototypeOf(e)).call.apply(t,[this].concat(i)));return s.channels={},s}return o(e,s),r(e,[{key:"connect",value:function(){this.pusher=new Pusher(this.options.key,this.options)}},{key:"listen",value:function(t,e,n){return this.channel(t).listen(e,n)}},{key:"channel",value:function(t){return this.channels[t]||(this.channels[t]=new u(this.pusher,t,this.options)),this.channels[t]}},{key:"privateChannel",value:function(t){return this.channels["private-"+t]||(this.channels["private-"+t]=new f(this.pusher,"private-"+t,this.options)),this.channels["private-"+t]}},{key:"presenceChannel",value:function(t){return this.channels["presence-"+t]||(this.channels["presence-"+t]=new d(this.pusher,"presence-"+t,this.options)),this.channels["presence-"+t]}},{key:"leave",value:function(t){var e=this;[t,"private-"+t,"presence-"+t].forEach(function(t,n){e.channels[t]&&(e.channels[t].unsubscribe(),delete e.channels[t])})}},{key:"socketId",value:function(){return this.pusher.connection.socket_id}},{key:"disconnect",value:function(){this.pusher.disconnect()}}]),e}(),m=function(t){function e(){var t;n(this,e);for(var r=arguments.length,i=Array(r),o=0;o<r;o++)i[o]=arguments[o];var s=a(this,(t=e.__proto__||Object.getPrototypeOf(e)).call.apply(t,[this].concat(i)));return s.channels={},s}return o(e,s),r(e,[{key:"connect",value:function(){var t=this.getSocketIO();return this.socket=t(this.options.host,this.options),this.socket}},{key:"getSocketIO",value:function(){if("undefined"!=typeof io)return io;if("undefined"!==this.options.client)return this.options.client;throw new Error("Socket.io client not found. Should be globally available or passed via options.client")}},{key:"listen",value:function(t,e,n){return this.channel(t).listen(e,n)}},{key:"channel",value:function(t){return this.channels[t]||(this.channels[t]=new h(this.socket,t,this.options)),this.channels[t]}},{key:"privateChannel",value:function(t){return this.channels["private-"+t]||(this.channels["private-"+t]=new p(this.socket,"private-"+t,this.options)),this.channels["private-"+t]}
},{key:"presenceChannel",value:function(t){return this.channels["presence-"+t]||(this.channels["presence-"+t]=new v(this.socket,"presence-"+t,this.options)),this.channels["presence-"+t]}},{key:"leave",value:function(t){var e=this;[t,"private-"+t,"presence-"+t].forEach(function(t){e.channels[t]&&(e.channels[t].unsubscribe(),delete e.channels[t])})}},{key:"socketId",value:function(){return this.socket.id}},{key:"disconnect",value:function(){this.socket.disconnect()}}]),e}(),y=function(){function t(e){n(this,t),this.options=e,"function"==typeof Vue&&Vue.http&&this.registerVueRequestInterceptor(),"function"==typeof axios&&this.registerAxiosRequestInterceptor(),"function"==typeof jQuery&&this.registerjQueryAjaxSetup(),"pusher"==this.options.broadcaster?this.connector=new g(this.options):"socket.io"==this.options.broadcaster&&(this.connector=new m(this.options))}return r(t,[{key:"registerVueRequestInterceptor",value:function(){var t=this;Vue.http.interceptors.push(function(e,n){t.socketId()&&e.headers.set("X-Socket-ID",t.socketId()),n()})}},{key:"registerAxiosRequestInterceptor",value:function(){var t=this;axios.interceptors.request.use(function(e){return t.socketId()&&(e.headers["X-Socket-Id"]=t.socketId()),e})}},{key:"registerjQueryAjaxSetup",value:function(){var t=this;void 0!==jQuery.ajax&&jQuery.ajaxSetup({beforeSend:function(e){t.socketId()&&e.setRequestHeader("X-Socket-Id",t.socketId())}})}},{key:"listen",value:function(t,e,n){return this.connector.listen(t,e,n)}},{key:"channel",value:function(t){return this.connector.channel(t)}},{key:"private",value:function(t){return this.connector.privateChannel(t)}},{key:"join",value:function(t){return this.connector.presenceChannel(t)}},{key:"leave",value:function(t){this.connector.leave(t)}},{key:"socketId",value:function(){return this.connector.socketId()}},{key:"disconnect",value:function(){this.connector.disconnect()}}]),t}();t.exports=y},jyFz:function(t,e,n){var r=function(){return this}()||Function("return this")(),i=r.regeneratorRuntime&&Object.getOwnPropertyNames(r).indexOf("regeneratorRuntime")>=0,o=i&&r.regeneratorRuntime;if(r.regeneratorRuntime=void 0,t.exports=n("SldL"),i)r.regeneratorRuntime=o;else try{delete r.regeneratorRuntime}catch(t){r.regeneratorRuntime=void 0}},"lHi+":function(t,e,n){var r=n("VU/8")(n("Op1H"),n("GaUX"),!1,null,null,null);t.exports=r.exports},lgjm:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{},[n("div",{staticClass:"absolute container mx-auto w-5/6 md:w-3/5 lg:w-2/5 bg-white rounded shadow-lg z-10",class:{hidden:!t.formShown},staticStyle:{top:"12vh",left:"0",right:"0"}},[n("div",{staticClass:"p-4"},[n("div",{staticClass:"p-4"},[t._m(0),t._v(" "),n("input",{directives:[{name:"model",rawName:"v-model",value:t.name,expression:"name"}],ref:"focusInput",staticClass:"appearance-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4",attrs:{type:"text",placeholder:"New Task",required:""},domProps:{value:t.name},on:{input:function(e){e.target.composing||(t.name=e.target.value)}}})]),t._v(" "),n("div",{staticClass:"p-4"},[n("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[t._v("\n Notes\n ")]),t._v(" "),n("input",{directives:[{name:"model",rawName:"v-model",value:t.notes,expression:"notes"}],staticClass:"appearance-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4",attrs:{type:"text",placeholder:"Description"},domProps:{value:t.notes},on:{input:function(e){e.target.composing||(t.notes=e.target.value)}}})]),t._v(" "),n("div",{staticClass:"p-4"},[t._m(1),t._v(" "),n("div",{staticClass:"flex flex-row items-center"},[n("select",{directives:[{name:"model",rawName:"v-model",value:t.assigned_to,expression:"assigned_to"}],staticClass:"w-5/6 block appearance-none w-full bg-grey-lighter border border-grey-lighter text-grey-darker py-3 px-4 pr-8 rounded",attrs:{id:"user"},on:{change:function(e){var n=Array.prototype.filter.call(e.target.options,function(t){return t.selected}).map(function(t){return"_value"in t?t._value:t.value});t.assigned_to=e.target.multiple?n:n[0]}}},[n("option",{attrs:{selected:"",disabled:"",hidden:""}},[t._v("Select User to Add")]),t._v(" "),t._l(t.resource.members,function(e){return[n("option",{staticClass:"my-2 text-lg",domProps:{value:e.id}},[t._v(t._s(e.name))])]})],2),t._v(" "),n("font-awesome-icon",{staticClass:"w-1/6 pointer-events-none flex items-center text-grey-darker -ml-8",attrs:{icon:t.faChevronDown}})],1)]),t._v(" "),n("div",{staticClass:"p-4"},[t._m(2),t._v(" "),n("datepicker",{ref:"dueOnDate",attrs:{placeholder:"Select Date",format:"yyyy-MM-dd","input-class":"appearance-none bg-grey-lighter text-grey-darker","wrapper-class":"appearance-none block w-full bg-grey-lighter text-grey-darker border border-grey-lighter rounded py-3 px-4"}})],1),t._v(" "),n("div",{staticClass:"p-4"},[n("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[t._v("\n Related To\n ")]),t._v(" "),n("div",{staticClass:"flex flex-row items-center"},[n("select",{directives:[{name:"model",rawName:"v-model",value:t.related_to,expression:"related_to"}],staticClass:"w-5/6 block appearance-none w-full bg-grey-lighter border border-grey-lighter text-grey-darker py-3 px-4 pr-8 rounded",attrs:{id:"user"},on:{change:function(e){var n=Array.prototype.filter.call(e.target.options,function(t){return t.selected}).map(function(t){return"_value"in t?t._value:t.value});t.related_to=e.target.multiple?n:n[0]}}},[n("option",{attrs:{selected:"",value:""}}),t._v(" "),t._l(t.tasks,function(e){return[n("option",{staticClass:"my-2 text-lg",domProps:{value:e.id}},[t._v(t._s(e.name))])]})],2),t._v(" "),n("font-awesome-icon",{staticClass:"w-1/6 pointer-events-none flex items-center text-grey-darker -ml-8",attrs:{icon:t.faChevronDown}})],1)])]),t._v(" "),n("div",{staticClass:"flex flex-row justify-between py-4 px-8 bg-grey-lighter rounded"},[n("button",{staticClass:"text-red-lighter hover:font-bold hover:text-red-light",on:{click:t.closeCreateTaskForm}},[t._v("Cancel")]),t._v(" "),n("button",{staticClass:"bg-teal-light text-white font-medium hover:bg-teal-dark py-4 px-8 rounded",on:{click:t.createTask}},[t._v("Create")])])]),t._v(" "),n("div",{staticClass:"h-screen w-screen fixed pin bg-grey-darkest opacity-25",class:{hidden:!t.formShown},on:{click:t.closeCreateTaskForm}})])},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[this._v("\n Title "),e("span",{staticClass:"text-grey capitalize"},[this._v("(required)")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[this._v("\n Assigned To "),e("span",{staticClass:"text-grey capitalize"},[this._v("(required)")])])},function(){var t=this.$createElement,e=this._self._c||t;return e("label",{staticClass:"block uppercase tracking-wide text-grey-darker text-xs font-bold mb-2",attrs:{for:"grid-first-name"}},[this._v("\n Due On "),e("span",{staticClass:"text-grey capitalize"},[this._v("(required)")])])}]}},mnZz:function(t,e,n){(t.exports=n("FZ+f")(!1)).push([t.i,"#members-list-modal{top:25%;bottom:25%;max-height:300px}",""])},myy1:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),n("WRGp");var r=n("ncgk"),i=n("gpS8"),o=n.n(i);new Vue({el:"#app",mixins:[r.a],components:{single:o.a}})},n14q:function(t,e,n){var r=n("VU/8")(n("z9ch"),n("xlX9"),!1,null,null,null);t.exports=r.exports},ncgk:function(t,e,n){"use strict";var r=n("pQE+"),i=n.n(r),o=n("Wfqs"),a=n.n(o),s=n("AGK/"),l=n.n(s),c={components:{navbar:i.a,notificationPopup:a.a,messageBox:l.a}};e.a=c},nkvb:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={props:{resourceType:{required:!0,type:String},resourceId:{required:!0,type:Number}},data:function(){return{files:[]}},methods:{selectFiles:function(){this.$refs.files.click()},filesSelected:function(){this.files=this.$refs.files.files;for(var t=new FormData,e=0;e<this.files.length;e++){var n=this.files[e];t.append("files["+e+"]",n)}t.append("fileable_type",this.resourceType),t.append("fileable_id",this.resourceId),this.submitFiles(t)},submitFiles:function(t){axios.post("/files",t,{headers:{"Content-Type":"multipart/form-data"}}).then(function(t){EventBus.$emit("notification",t.data.message,t.data.status)}).catch(function(t){EventBus.$emit("notification",t.response.data.message,t.response.data.status)})}}}},"pQE+":function(t,e,n){var r=n("VU/8")(n("qjuG"),n("qmjA"),!1,null,null,null);t.exports=r.exports},qiXB:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.discussionDetailsShown?n("div",[n("div",{staticClass:"absolute container mx-auto md:w-5/6 lg:4/5 xl:w-3/4 xxl:w-2/3 bg-white rounded shadow-lg z-10 py-8 mb-16",staticStyle:{top:"12vh",left:"0",right:"0"}},[n("div",{staticClass:"flex flex-row justify-between relative px-8"},[n("div",{staticClass:"cursor-pointer",on:{click:t.closeDiscussionDetails}},[n("font-awesome-icon",{staticClass:"text-base text-grey-dark",attrs:{icon:t.faArrowLeft}})],1),t._v(" "),n("div",{directives:[{name:"click-outside",rawName:"v-click-outside",value:t.hideMenu,expression:"hideMenu"}],staticClass:"cursor-pointer",on:{click:t.toggleMenu}},[n("font-awesome-icon",{staticClass:"text-base text-grey-dark",attrs:{icon:t.faEllipsisH}})],1),t._v(" "),t.dropdownMenuShown?n("div",{staticClass:"absolute rounded shadow-lg pin-r pin-t mt-6 p-3 text-grey-darker hover:bg-grey-light"},[n("div",{staticClass:"cursor-pointer",on:{click:t.deleteDiscussion}},[t._v("\n Delete\n ")])]):t._e()]),t._v(" "),n("div",{staticClass:"text-grey-darkest text-left text-3xl font-medium py-4 px-16",attrs:{"data-discussion-id":t.discussion.id}},[t._v("\n "+t._s(t.discussion.name)+"\n ")]),t._v(" "),n("div",{staticClass:"flex flex-row justify-start items-center pb-4 border-b px-16"},[n("img",{staticClass:"rounded-full w-10 h-10",attrs:{src:t.generateUrl(t.discussion.creator.avatar)}}),t._v(" "),n("div",{staticClass:"text-grey-darker text-sm ml-4"},[n("div",{staticClass:"pb-1"},[t._v("\n "+t._s(t.discussion.creator.name)+"\n ")]),t._v(" "),n("div",[t._v("\n "+t._s(t.discussion.date)+"\n ")])])]),t._v(" "),n("div",{staticClass:"py-8 px-16 text-grey-darkest",domProps:{innerHTML:t._s(t.discussion.content)}}),t._v(" "),n("comment-box",{staticClass:"px-16",attrs:{resourceType:"discussion",resource:t.discussion,detailsShown:t.discussionDetailsShown}})],1),t._v(" "),n("div",{staticClass:"h-screen w-screen fixed pin bg-grey-darkest opacity-25",on:{click:t.closeDiscussionDetails}})]):t._e()},staticRenderFns:[]}},qjuG:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("8tCw"),i=n.n(r),o=n("lHi+"),a=n.n(o),s=n("dBZW"),l=n.n(s);e.default={components:{notificationDropdown:i.a,messageDropdown:a.a,profileDropdown:l.a},data:function(){return{user:navbar.user,token:Laravel.csrfToken,url:navbar.navUrl}}}},qmjA:function(t,e){t.exports={render:function(){var t=this.$createElement,e=this._self._c||t;return e("nav",{staticClass:"bg-white flex flex-row justify-between h-12 md:px-4 shadow"},[e("a",{staticClass:"text-teal text-2xl font-bold md:font-normal no-underline h-12 w-32",attrs:{href:this.url.site}},[e("img",{staticClass:"w-full h-full hidden md:block",attrs:{src:this.generateUrl("logos/logo.svg"),alt:""}}),this._v(" "),e("img",{staticClass:"w-full h-full block md:hidden pr-16",attrs:{src:this.generateUrl("logos/logo_square.svg"),alt:""}})]),this._v(" "),e("div",{staticClass:"md:flex"},[e("div",{staticClass:"flex flex-row border-l h-full"},[e("notification-dropdown"),this._v(" "),e("message-dropdown"),this._v(" "),e("profile-dropdown")],1)])])},staticRenderFns:[]}},rjj0:function(t,e,n){function r(t){for(var e=0;e<t.length;e++){var n=t[e],r=c[n.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](n.parts[i]);for(;i<n.parts.length;i++)r.parts.push(o(n.parts[i]));r.parts.length>n.parts.length&&(r.parts.length=n.parts.length)}else{var a=[];for(i=0;i<n.parts.length;i++)a.push(o(n.parts[i]));c[n.id]={id:n.id,refs:1,parts:a}}}}function i(){var t=document.createElement("style");return t.type="text/css",u.appendChild(t),t}function o(t){var e,n,r=document.querySelector("style["+g+'~="'+t.id+'"]');if(r){if(h)return p;r.parentNode.removeChild(r)}if(m){var o=d++;r=f||(f=i()),e=a.bind(null,r,o,!1),n=a.bind(null,r,o,!0)}else r=i(),e=function(t,e){var n=e.css,r=e.media,i=e.sourceMap;if(r&&t.setAttribute("media",r),v.ssrId&&t.setAttribute(g,e.id),i&&(n+="\n/*# sourceURL="+i.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */"),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}.bind(null,r),n=function(){r.parentNode.removeChild(r)};return e(t),function(r){if(r){if(r.css===t.css&&r.media===t.media&&r.sourceMap===t.sourceMap)return;e(t=r)}else n()}}function a(t,e,n,r){var i=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=b(e,i);else{var o=document.createTextNode(i),a=t.childNodes;a[e]&&t.removeChild(a[e]),a.length?t.insertBefore(o,a[e]):t.appendChild(o)}}var s="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!s)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var l=n("tTVk"),c={},u=s&&(document.head||document.getElementsByTagName("head")[0]),f=null,d=0,h=!1,p=function(){},v=null,g="data-vue-ssr-id",m="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());t.exports=function(t,e,n,i){h=n,v=i||{};var o=l(t,e);return r(o),function(e){for(var n=[],i=0;i<o.length;i++){var a=o[i];(s=c[a.id]).refs--,n.push(s)}for(e?r(o=l(t,e)):o=[],i=0;i<n.length;i++){var s;if(0===(s=n[i]).refs){for(var u=0;u<s.parts.length;u++)s.parts[u]();delete c[s.id]}}}};var y,b=(y=[],function(t,e){return y[t]=e,y.filter(Boolean).join("\n")})},sklR:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",[n("div",{staticClass:"border-b pt-8 pb-2 text-grey-dark font-medium"},[t._v("\n Comments "),n("span",{staticClass:"rounded-full py-1 px-2 bg-teal-lighter"},[t._v(t._s(t.comments.length))])]),t._v(" "),n("div",{staticClass:"py-6"},[n("textarea",{directives:[{name:"model",rawName:"v-model",value:t.body,expression:"body"}],staticClass:"static bg-grey-lighter textarea resize-none rounded w-full p-4 text-grey-darker",attrs:{id:"save-comment",placeholder:"write your comment here",rows:"1"},domProps:{value:t.body},on:{keyup:function(e){t.checkForMention(e)},keydown:[function(e){t.mentionHighlightMove(e)},function(e){if(!("button"in e)&&t._k(e.keyCode,"enter",13,e.key))return null;e.preventDefault(),t.saveComment(e)}],input:function(e){e.target.composing||(t.body=e.target.value)}}}),t._v(" "),n("user-suggestion-box",{attrs:{users:t.users,name:t.name,suggestionShown:t.suggestionShown,suggestionSelected:t.suggestionSelected,suggestionHighlightIndex:t.suggestionHighlightIndex,suggestionHighlightDirection:t.suggestionHighlightDirection},on:{selected:t.userSelected}}),t._v(" "),t.name.length<1?n("div",{staticClass:"absolute text-xs text-grey-dark pt-2"},[t._v("Press enter "),n("span",{staticClass:"bg-grey p-1 rounded text-white font-bold"},[t._v("↵")]),t._v(" to save")]):t._e()],1),t._v(" "),n("div",t._l(t.comments,function(e,r){return n("div",{staticClass:"my-6"},[n("div",{staticClass:"text-xs text-grey-dark pb-2 ml-10"},[t._v("\n "+t._s(e.user.name)+" on "+t._s(e.date)+"\n ")]),t._v(" "),n("div",{staticClass:"flex flex-row items-center"},[n("div",{staticClass:"z-10"},[n("img",{staticClass:"rounded-full w-8 h-8",attrs:{src:t.generateUrl(e.user.avatar)}})]),t._v(" "),n("div",{staticClass:"flex-1 bg-grey-lighter text-grey-darker rounded ml-2 p-4 flex flex-row justify-between"},[n("div",[t._v("\n "+t._s(e.body)+"\n ")]),t._v(" "),t.user.id===e.user_id?n("div",{staticClass:"text-xs text-red pb-2 ml-10 cursor-pointer",on:{click:function(n){t.deleteComment(e,r)}}},[n("font-awesome-icon",{attrs:{icon:t.faTrashAlt}})],1):t._e()])])])}))])},staticRenderFns:[]}},tTVk:function(t,e){t.exports=function(t,e){for(var n=[],r={},i=0;i<e.length;i++){var o=e[i],a=o[0],s={id:t+":"+i,css:o[1],media:o[2],sourceMap:o[3]};r[a]?r[a].parts.push(s):n.push(r[a]={id:a,parts:[s]})}return n}},ujcs:function(t,e){e.read=function(t,e,n,r,i){var o,a,s=8*i-r-1,l=(1<<s)-1,c=l>>1,u=-7,f=n?i-1:0,d=n?-1:1,h=t[e+f];for(f+=d,o=h&(1<<-u)-1,h>>=-u,u+=s;u>0;o=256*o+t[e+f],f+=d,u-=8);for(a=o&(1<<-u)-1,o>>=-u,u+=r;u>0;a=256*a+t[e+f],f+=d,u-=8);if(0===o)o=1-c;else{if(o===l)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,r),o-=c}return(h?-1:1)*a*Math.pow(2,o-r)},e.write=function(t,e,n,r,i,o){var a,s,l,c=8*o-i-1,u=(1<<c)-1,f=u>>1,d=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:o-1,p=r?1:-1,v=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=u):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),(e+=a+f>=1?d/l:d*Math.pow(2,1-f))*l>=2&&(a++,l/=2),a+f>=u?(s=0,a=u):a+f>=1?(s=(e*l-1)*Math.pow(2,i),a+=f):(s=e*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;t[n+h]=255&s,h+=p,s/=256,i-=8);for(a=a<<i|s,c+=i;c>0;t[n+h]=255&a,h+=p,a/=256,c-=8);t[n+h-p]|=128*v}},v4BQ:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("XILU"),i=n.n(r),o=n("fhbW");e.default={components:{Datepicker:i.a},props:["resource","resourceType","formShown","tasks"],data:function(){return{name:"",notes:"",assigned_to:null,related_to:"",faChevronDown:o.f}},methods:{createTask:function(){var t=this;axios.post("/tasks",{name:this.name,notes:this.notes,assigned_to:this.assigned_to,related_to:this.related_to,due_on:this.$refs.dueOnDate.formattedValue,taskable_id:this.resource.id,taskable_type:this.resourceType}).then(function(e){"success"===e.data.status&&(t.name="",t.notes="",t.assigned_to=null,t.related_to="",EventBus.$emit("notification",e.data.message,e.data.status),t.$emit("close",e.data.task))}).catch(function(e){EventBus.$emit("notification",e.response.data.message,e.response.data.status),t.$emit("close")})},closeCreateTaskForm:function(){this.$emit("close")},closeNotification:function(){this.showNotification=!1},suggestMember:function(t){}},computed:{taskCompleted:function(){return this.tasks.filter(function(t){return t.completed}).length}}}},wmlM:function(t,e,n){var r=n("VU/8")(n("Yl9i"),n("K7iK"),!1,null,null,null);t.exports=r.exports},x3ax:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"w-full",class:{hidden:"discussions"!=t.activeTab}},[n("create-discussion-form",{ref:"discussionForm",attrs:{resourceId:t.resource.id,resourceType:t.resourceType,"form-shown":t.createDiscussionFormShown},on:{close:t.closeCreateDiscussionForm}}),t._v(" "),t.discussion?n("discussion-details",{attrs:{discussionDetailsShown:t.discussionDetailsShown,discussion:t.discussion,index:t.index},on:{close:t.closeDiscussionDetails,deleted:t.deleteDiscussion}}):t._e(),t._v(" "),n("div",{staticClass:"text-center"},[n("button",{staticClass:"no-underline p-3 my-4 bg-white text-base text-teal rounded shadow",on:{click:t.showCreateDiscussionForm}},[t._v(t._s(t._f("localize")("Create New Post")))])]),t._v(" "),n("div",{staticClass:"flex flex-row flex-wrap justify-center items-start"},t._l(t.discussions,function(e,r){return n("div",{key:r,staticClass:"w-80 my-6 md:m-6 bg-white shadow-md flex flex-col items-center rounded cursor-pointer",on:{click:function(e){t.showDiscussionDetails(r)}}},[n("div",{staticClass:"bg-teal flex flex-col items-center w-full text-white rounded-t"},[n("div",{staticClass:"w-10 h-10 flex-none py-4"},[n("img",{staticClass:"rounded-full w-10 h-10",attrs:{src:t.generateUrl(e.creator.avatar)}})]),t._v(" "),n("div",{staticClass:"mt-6 text-xs"},[t._v("\n by "),n("a",{staticClass:"text-sm text-white font-bold cursor-pointer no-underline",attrs:{href:"/users/"+e.creator.username}},[t._v(t._s(e.creator.name))]),t._v(" on "),n("span",{staticClass:"text-sm font-bold"},[t._v(t._s(e.date))]),t._v(" in "),n("span",{staticClass:"text-sm font-bold"},[t._v(t._s(e.category.name))])]),t._v(" "),n("div",{staticClass:"text-white text-3xl text-center font-semibold p-4"},[t._v(t._s(e.name))])]),t._v(" "),n("div",{staticClass:"text-regular m-4 text-grey-darker leading-normal overflow-hidden",staticStyle:{"max-height":"12rem"}},[n("div",{domProps:{innerHTML:t._s(e.content)}})])])}))],1)},staticRenderFns:[]}},xNbt:function(t,e,n){var r=n("mnZz");"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals),n("rjj0")("3c35d20d",r,!0,{})},xQsn:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("yPE/"),i=n.n(r),o={modules:{toolbar:[[{header:[1,2,3,4,5,6,!1]}],["bold","italic","underline","strike"],[{list:"ordered"},{list:"bullet"}],["blockquote","code-block"],["image","link"]]},theme:"snow"};e.default={props:{formShown:{required:!0,type:Boolean},resourceId:{required:!0,type:Number},resourceType:{required:!0,type:String}},data:function(){return{quill:null,name:"",categoryId:"",categories:[]}},mounted:function(){this.quill=new i.a("#editor",o)},methods:{savePost:function(){var t=this,e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];axios.post("/discussions",{name:this.name,category_id:this.categoryId,content:this.quill.root.innerHTML,raw_content:JSON.stringify(this.quill.getContents()),draft:e,discussionable_type:this.resourceType,discussionable_id:this.resourceId}).then(function(e){t.name="",t.categoryId="",t.quill.setContents([]),EventBus.$emit("notification",e.data.message,e.data.status),t.$emit("close",e.data.discussion)}).catch(function(e){EventBus.$emit("notification",e.response.data.message,e.response.data.status),t.$emit("close")})},closeEditor:function(){this.$emit("close")},getCategories:function(){var t=this;this.formShown&&this.categories.length<1&&axios.get("/categories").then(function(e){t.categories=e.data.categories}).catch(function(t){})}},watch:{formShown:"getCategories"}}},xlX9:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"w-full",class:{hidden:"files"!=t.activeTab}},[n("div",[n("div",{staticClass:"flex justify-center pb-4"},[n("file-upload",{attrs:{resourceType:t.resourceType,resourceId:t.resource.id}})],1),t._v(" "),n("div",{},[n("ul",{staticClass:"flex flex-row flex-wrap justify-center list-reset"},[t._m(0),t._v(" "),n("li",{staticClass:"rounded-lg w-48 h-48 flex flex-col justify-center items-center m-4 shadow-md cursor-pointer"},[n("div",{staticClass:"bg-grey-lighter w-full h-32 flex justify-center items-center rounded-lg"},[n("font-awesome-icon",{staticClass:"text-teal text-5xl",attrs:{icon:t.faFileAlt}})],1),t._v(" "),n("div",{staticClass:"bg-white w-full h-16 text-center rounded-b-lg pt-4 px-4 text-sm text-grey-darker"},[t._v("Files section design.sketch")])]),t._v(" "),n("li",{staticClass:"rounded-lg w-48 h-48 flex flex-col justify-center items-center m-4 shadow-md cursor-pointer"},[n("div",{staticClass:"bg-grey-lighter w-full h-32 flex justify-center items-center rounded-lg"},[n("font-awesome-icon",{staticClass:"text-teal text-5xl",attrs:{icon:t.faFilePdf}})],1),t._v(" "),n("div",{staticClass:"bg-white w-full h-16 text-center rounded-b-lg pt-4 px-4 text-sm text-grey-darker"},[t._v("Files section requirements.pdf")])])])])])])},staticRenderFns:[function(){var t=this.$createElement,e=this._self._c||t;return e("li",{staticClass:"rounded-lg w-48 h-48 flex flex-col justify-center items-center m-4 shadow-md cursor-pointer"},[e("div",{staticClass:"bg-grey-lighter w-full h-32 flex justify-center items-center rounded-lg"},[e("img",{staticClass:"h-32 w-full rounded-t-lg",attrs:{src:"https://cdn.dribbble.com/users/1838892/screenshots/4916282/image_manager_and_bulk_editor.gif",alt:""}})]),this._v(" "),e("div",{staticClass:"bg-white w-full h-16 text-center rounded-b-lg pt-4 px-4 text-sm text-grey-darker"},[this._v("Files section design.jpg")])])}]}},xv6y:function(t,e,n){var r=n("VU/8")(n("fyOk"),n("F70e"),!1,null,null,null);t.exports=r.exports},xwHu:function(t,e){t.exports={render:function(){var t=this.$createElement,e=this._self._c||t;return e("div",{staticClass:"fixed pin-t text-white text-lg font-semibold rounded container mx-auto md:w-1/2 mt-16 py-6 px-8 shadow-lg z-50",class:[this.notificationShown?"":"hidden","success"===this.messageType?"bg-teal-dark":"bg-red-light"],staticStyle:{left:"0",right:"0","max-width":"640px"}},[this._v("\n "+this._s(this.message)+" \n "),e("div",{staticClass:"inline",on:{click:this.closeNotification}},[e("font-awesome-icon",{staticClass:"float-right cursor-pointer",attrs:{icon:this.faTimes}})],1)])},staticRenderFns:[]}},y8Kx:function(t,e,n){var r=n("VU/8")(n("Ms4a"),n("L8IH"),!1,null,null,null);t.exports=r.exports},"yPE/":function(t,e,n){(function(e){var n;"undefined"!=typeof self&&self,n=function(){return function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="",e(e.s=109)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(17),i=n(18),o=n(19),a=n(45),s=n(46),l=n(47),c=n(48),u=n(49),f=n(12),d=n(32),h=n(33),p=n(31),v=n(1),g={Scope:v.Scope,create:v.create,find:v.find,query:v.query,register:v.register,Container:r.default,Format:i.default,Leaf:o.default,Embed:c.default,Scroll:a.default,Block:l.default,Inline:s.default,Text:u.default,Attributor:{Attribute:f.default,Class:d.default,Style:h.default,Store:p.default}};e.default=g},function(t,e,n){"use strict";function r(t,e){var n;if(void 0===e&&(e=s.ANY),"string"==typeof t)n=f[t]||l[t];else if(t instanceof Text||t.nodeType===Node.TEXT_NODE)n=f.text;else if("number"==typeof t)t&s.LEVEL&s.BLOCK?n=f.block:t&s.LEVEL&s.INLINE&&(n=f.inline);else if(t instanceof HTMLElement){var r=(t.getAttribute("class")||"").split(/\s+/);for(var i in r)if(n=c[r[i]])break;n=n||u[t.tagName]}return null==n?null:e&s.LEVEL&n.scope&&e&s.TYPE&n.scope?n:null}var i,o=this&&this.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var a=function(t){function e(e){var n=this;return e="[Parchment] "+e,(n=t.call(this,e)||this).message=e,n.name=n.constructor.name,n}return o(e,t),e}(Error);e.ParchmentError=a;var s,l={},c={},u={},f={};e.DATA_KEY="__blot",function(t){t[t.TYPE=3]="TYPE",t[t.LEVEL=12]="LEVEL",t[t.ATTRIBUTE=13]="ATTRIBUTE",t[t.BLOT=14]="BLOT",t[t.INLINE=7]="INLINE",t[t.BLOCK=11]="BLOCK",t[t.BLOCK_BLOT=10]="BLOCK_BLOT",t[t.INLINE_BLOT=6]="INLINE_BLOT",t[t.BLOCK_ATTRIBUTE=9]="BLOCK_ATTRIBUTE",t[t.INLINE_ATTRIBUTE=5]="INLINE_ATTRIBUTE",t[t.ANY=15]="ANY"}(s=e.Scope||(e.Scope={})),e.create=function(t,e){var n=r(t);if(null==n)throw new a("Unable to create "+t+" blot");var i=n;return new i(t instanceof Node||t.nodeType===Node.TEXT_NODE?t:i.create(e),e)},e.find=function t(n,r){return void 0===r&&(r=!1),null==n?null:null!=n[e.DATA_KEY]?n[e.DATA_KEY].blot:r?t(n.parentNode,r):null},e.query=r,e.register=function t(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];if(e.length>1)return e.map(function(e){return t(e)});var r=e[0];if("string"!=typeof r.blotName&&"string"!=typeof r.attrName)throw new a("Invalid definition");if("abstract"===r.blotName)throw new a("Cannot register abstract class");return f[r.blotName||r.attrName]=r,"string"==typeof r.keyName?l[r.keyName]=r:(null!=r.className&&(c[r.className]=r),null!=r.tagName&&(Array.isArray(r.tagName)?r.tagName=r.tagName.map(function(t){return t.toUpperCase()}):r.tagName=r.tagName.toUpperCase(),(Array.isArray(r.tagName)?r.tagName:[r.tagName]).forEach(function(t){null!=u[t]&&null!=r.className||(u[t]=r)}))),r}},function(t,e,n){var r=n(51),i=n(11),o=n(3),a=n(20),s=String.fromCharCode(0),l=function(t){Array.isArray(t)?this.ops=t:null!=t&&Array.isArray(t.ops)?this.ops=t.ops:this.ops=[]};l.prototype.insert=function(t,e){var n={};return 0===t.length?this:(n.insert=t,null!=e&&"object"==typeof e&&Object.keys(e).length>0&&(n.attributes=e),this.push(n))},l.prototype.delete=function(t){return t<=0?this:this.push({delete:t})},l.prototype.retain=function(t,e){if(t<=0)return this;var n={retain:t};return null!=e&&"object"==typeof e&&Object.keys(e).length>0&&(n.attributes=e),this.push(n)},l.prototype.push=function(t){var e=this.ops.length,n=this.ops[e-1];if(t=o(!0,{},t),"object"==typeof n){if("number"==typeof t.delete&&"number"==typeof n.delete)return this.ops[e-1]={delete:n.delete+t.delete},this;if("number"==typeof n.delete&&null!=t.insert&&(e-=1,"object"!=typeof(n=this.ops[e-1])))return this.ops.unshift(t),this;if(i(t.attributes,n.attributes)){if("string"==typeof t.insert&&"string"==typeof n.insert)return this.ops[e-1]={insert:n.insert+t.insert},"object"==typeof t.attributes&&(this.ops[e-1].attributes=t.attributes),this;if("number"==typeof t.retain&&"number"==typeof n.retain)return this.ops[e-1]={retain:n.retain+t.retain},"object"==typeof t.attributes&&(this.ops[e-1].attributes=t.attributes),this}}return e===this.ops.length?this.ops.push(t):this.ops.splice(e,0,t),this},l.prototype.chop=function(){var t=this.ops[this.ops.length-1];return t&&t.retain&&!t.attributes&&this.ops.pop(),this},l.prototype.filter=function(t){return this.ops.filter(t)},l.prototype.forEach=function(t){this.ops.forEach(t)},l.prototype.map=function(t){return this.ops.map(t)},l.prototype.partition=function(t){var e=[],n=[];return this.forEach(function(r){(t(r)?e:n).push(r)}),[e,n]},l.prototype.reduce=function(t,e){return this.ops.reduce(t,e)},l.prototype.changeLength=function(){return this.reduce(function(t,e){return e.insert?t+a.length(e):e.delete?t-e.delete:t},0)},l.prototype.length=function(){return this.reduce(function(t,e){return t+a.length(e)},0)},l.prototype.slice=function(t,e){t=t||0,"number"!=typeof e&&(e=1/0);for(var n=[],r=a.iterator(this.ops),i=0;i<e&&r.hasNext();){var o;i<t?o=r.next(t-i):(o=r.next(e-i),n.push(o)),i+=a.length(o)}return new l(n)},l.prototype.compose=function(t){for(var e=a.iterator(this.ops),n=a.iterator(t.ops),r=new l;e.hasNext()||n.hasNext();)if("insert"===n.peekType())r.push(n.next());else if("delete"===e.peekType())r.push(e.next());else{var i=Math.min(e.peekLength(),n.peekLength()),o=e.next(i),s=n.next(i);if("number"==typeof s.retain){var c={};"number"==typeof o.retain?c.retain=i:c.insert=o.insert;var u=a.attributes.compose(o.attributes,s.attributes,"number"==typeof o.retain);u&&(c.attributes=u),r.push(c)}else"number"==typeof s.delete&&"number"==typeof o.retain&&r.push(s)}return r.chop()},l.prototype.concat=function(t){var e=new l(this.ops.slice());return t.ops.length>0&&(e.push(t.ops[0]),e.ops=e.ops.concat(t.ops.slice(1))),e},l.prototype.diff=function(t,e){if(this.ops===t.ops)return new l;var n=[this,t].map(function(e){return e.map(function(n){if(null!=n.insert)return"string"==typeof n.insert?n.insert:s
;throw new Error("diff() called "+(e===t?"on":"with")+" non-document")}).join("")}),o=new l,c=r(n[0],n[1],e),u=a.iterator(this.ops),f=a.iterator(t.ops);return c.forEach(function(t){for(var e=t[1].length;e>0;){var n=0;switch(t[0]){case r.INSERT:n=Math.min(f.peekLength(),e),o.push(f.next(n));break;case r.DELETE:n=Math.min(e,u.peekLength()),u.next(n),o.delete(n);break;case r.EQUAL:n=Math.min(u.peekLength(),f.peekLength(),e);var s=u.next(n),l=f.next(n);i(s.insert,l.insert)?o.retain(n,a.attributes.diff(s.attributes,l.attributes)):o.push(l).delete(n)}e-=n}}),o.chop()},l.prototype.eachLine=function(t,e){e=e||"\n";for(var n=a.iterator(this.ops),r=new l,i=0;n.hasNext();){if("insert"!==n.peekType())return;var o=n.peek(),s=a.length(o)-n.peekLength(),c="string"==typeof o.insert?o.insert.indexOf(e,s)-s:-1;if(c<0)r.push(n.next());else if(c>0)r.push(n.next(c));else{if(!1===t(r,n.next(1).attributes||{},i))return;i+=1,r=new l}}r.length()>0&&t(r,{},i)},l.prototype.transform=function(t,e){if(e=!!e,"number"==typeof t)return this.transformPosition(t,e);for(var n=a.iterator(this.ops),r=a.iterator(t.ops),i=new l;n.hasNext()||r.hasNext();)if("insert"!==n.peekType()||!e&&"insert"===r.peekType())if("insert"===r.peekType())i.push(r.next());else{var o=Math.min(n.peekLength(),r.peekLength()),s=n.next(o),c=r.next(o);if(s.delete)continue;c.delete?i.push(c):i.retain(o,a.attributes.transform(s.attributes,c.attributes,e))}else i.retain(a.length(n.next()));return i.chop()},l.prototype.transformPosition=function(t,e){e=!!e;for(var n=a.iterator(this.ops),r=0;n.hasNext()&&r<=t;){var i=n.peekLength(),o=n.peekType();n.next(),"delete"!==o?("insert"===o&&(r<t||!e)&&(t+=i),r+=i):t-=Math.min(i,t-r)}return t},t.exports=l},function(t,e){"use strict";var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString,i=function(t){return"function"==typeof Array.isArray?Array.isArray(t):"[object Array]"===r.call(t)},o=function(t){if(!t||"[object Object]"!==r.call(t))return!1;var e,i=n.call(t,"constructor"),o=t.constructor&&t.constructor.prototype&&n.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!i&&!o)return!1;for(e in t);return void 0===e||n.call(t,e)};t.exports=function t(){var e,n,r,a,s,l,c=arguments[0],u=1,f=arguments.length,d=!1;for("boolean"==typeof c&&(d=c,c=arguments[1]||{},u=2),(null==c||"object"!=typeof c&&"function"!=typeof c)&&(c={});u<f;++u)if(null!=(e=arguments[u]))for(n in e)r=c[n],c!==(a=e[n])&&(d&&a&&(o(a)||(s=i(a)))?(s?(s=!1,l=r&&i(r)?r:[]):l=r&&o(r)?r:{},c[n]=t(d,l,a)):void 0!==a&&(c[n]=a));return c}},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return null==t?e:("function"==typeof t.formats&&(e=(0,u.default)(e,t.formats())),null==t.parent||"scroll"==t.parent.blotName||t.parent.statics.scope!==t.statics.scope?e:s(t.parent,e))}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.BlockEmbed=e.bubbleFormats=void 0;var l=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),c=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},u=r(n(3)),f=r(n(2)),d=r(n(0)),h=r(n(16)),p=r(n(6)),v=r(n(7)),g=function(t){function e(){return i(this,e),o(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return a(e,d.default.Embed),l(e,[{key:"attach",value:function(){c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"attach",this).call(this),this.attributes=new d.default.Attributor.Store(this.domNode)}},{key:"delta",value:function(){return(new f.default).insert(this.value(),(0,u.default)(this.formats(),this.attributes.values()))}},{key:"format",value:function(t,e){var n=d.default.query(t,d.default.Scope.BLOCK_ATTRIBUTE);null!=n&&this.attributes.attribute(n,e)}},{key:"formatAt",value:function(t,e,n,r){this.format(n,r)}},{key:"insertAt",value:function(t,n,r){if("string"==typeof n&&n.endsWith("\n")){var i=d.default.create(m.blotName);this.parent.insertBefore(i,0===t?this:this.next),i.insertAt(0,n.slice(0,-1))}else c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertAt",this).call(this,t,n,r)}}]),e}();g.scope=d.default.Scope.BLOCK_BLOT;var m=function(t){function e(t){i(this,e);var n=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return n.cache={},n}return a(e,d.default.Block),l(e,[{key:"delta",value:function(){return null==this.cache.delta&&(this.cache.delta=this.descendants(d.default.Leaf).reduce(function(t,e){return 0===e.length()?t:t.insert(e.value(),s(e))},new f.default).insert("\n",s(this))),this.cache.delta}},{key:"deleteAt",value:function(t,n){c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"deleteAt",this).call(this,t,n),this.cache={}}},{key:"formatAt",value:function(t,n,r,i){n<=0||(d.default.query(r,d.default.Scope.BLOCK)?t+n===this.length()&&this.format(r,i):c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"formatAt",this).call(this,t,Math.min(n,this.length()-t-1),r,i),this.cache={})}},{key:"insertAt",value:function(t,n,r){if(null!=r)return c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertAt",this).call(this,t,n,r);if(0!==n.length){var i=n.split("\n"),o=i.shift();o.length>0&&(t<this.length()-1||null==this.children.tail?c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertAt",this).call(this,Math.min(t,this.length()-1),o):this.children.tail.insertAt(this.children.tail.length(),o),this.cache={});var a=this;i.reduce(function(t,e){return(a=a.split(t,!0)).insertAt(0,e),e.length},t+o.length)}}},{key:"insertBefore",value:function(t,n){var r=this.children.head;c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertBefore",this).call(this,t,n),r instanceof h.default&&r.remove(),this.cache={}}},{key:"length",value:function(){return null==this.cache.length&&(this.cache.length=c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"length",this).call(this)+1),this.cache.length}},{key:"moveChildren",value:function(t,n){c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"moveChildren",this).call(this,t,n),this.cache={}}},{key:"optimize",value:function(t){c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"optimize",this).call(this,t),this.cache={}}},{key:"path",value:function(t){return c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"path",this).call(this,t,!0)}},{key:"removeChild",value:function(t){c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"removeChild",this).call(this,t),this.cache={}}},{key:"split",value:function(t){var n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(n&&(0===t||t>=this.length()-1)){var r=this.clone();return 0===t?(this.parent.insertBefore(r,this),this):(this.parent.insertBefore(r,this.next),r)}var i=c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"split",this).call(this,t,n);return this.cache={},i}}]),e}();m.blotName="block",m.tagName="P",m.defaultChild="break",m.allowedChildren=[p.default,d.default.Embed,v.default],e.bubbleFormats=s,e.BlockEmbed=g,e.default=m},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function o(t,e){if((e=(0,b.default)(!0,{container:t,modules:{clipboard:!0,keyboard:!0,history:!0}},e)).theme&&e.theme!==k.DEFAULTS.theme){if(e.theme=k.import("themes/"+e.theme),null==e.theme)throw new Error("Invalid theme "+e.theme+". Did you register it?")}else e.theme=_.default;var n=(0,b.default)(!0,{},e.theme.DEFAULTS);[n,e].forEach(function(t){t.modules=t.modules||{},Object.keys(t.modules).forEach(function(e){!0===t.modules[e]&&(t.modules[e]={})})});var r=Object.keys(n.modules).concat(Object.keys(e.modules)).reduce(function(t,e){var n=k.import("modules/"+e);return null==n?x.error("Cannot load "+e+" module. Are you sure you registered it?"):t[e]=n.DEFAULTS||{},t},{});return null!=e.modules&&e.modules.toolbar&&e.modules.toolbar.constructor!==Object&&(e.modules.toolbar={container:e.modules.toolbar}),e=(0,b.default)(!0,{},k.DEFAULTS,{modules:r},n,e),["bounds","container","scrollingContainer"].forEach(function(t){"string"==typeof e[t]&&(e[t]=document.querySelector(e[t]))}),e.modules=Object.keys(e.modules).reduce(function(t,n){return e.modules[n]&&(t[n]=e.modules[n]),t},{}),e}function a(t,e,n,r){if(this.options.strict&&!this.isEnabled()&&e===p.default.sources.USER)return new d.default;var i=null==n?null:this.getSelection(),o=this.editor.delta,a=t();if(null!=i&&(!0===n&&(n=i.index),null==r?i=l(i,a,e):0!==r&&(i=l(i,n,r,e)),this.setSelection(i,p.default.sources.SILENT)),a.length()>0){var s,c,u=[p.default.events.TEXT_CHANGE,a,o,e];(s=this.emitter).emit.apply(s,[p.default.events.EDITOR_CHANGE].concat(u)),e!==p.default.sources.SILENT&&(c=this.emitter).emit.apply(c,u)}return a}function s(t,e,n,r,i){var o={};return"number"==typeof t.index&&"number"==typeof t.length?"number"!=typeof e?(i=r,r=n,n=e,e=t.length,t=t.index):(e=t.length,t=t.index):"number"!=typeof e&&(i=r,r=n,n=e,e=0),"object"===(void 0===n?"undefined":c(n))?(o=n,i=r):"string"==typeof n&&(null!=r?o[n]=r:i=n),[t,e,o,i=i||p.default.sources.API]}function l(t,e,n,r){if(null==t)return null;var i=void 0,o=void 0;if(e instanceof d.default){var a=[t.index,t.index+t.length].map(function(t){return e.transformPosition(t,r!==p.default.sources.USER)}),s=u(a,2);i=s[0],o=s[1]}else{var l=[t.index,t.index+t.length].map(function(t){return t<e||t===e&&r===p.default.sources.USER?t:n>=0?t+n:Math.max(e,t+n)}),c=u(l,2);i=c[0],o=c[1]}return new m.Range(i,o-i)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.overload=e.expandConfig=void 0;var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},u=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),f=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}();n(50);var d=r(n(2)),h=r(n(14)),p=r(n(8)),v=r(n(9)),g=r(n(0)),m=n(15),y=r(m),b=r(n(3)),w=r(n(10)),_=r(n(34)),x=(0,w.default)("quill"),k=function(){function t(e){var n=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.options=o(e,r),this.container=this.options.container,null==this.container)return x.error("Invalid Quill container",e);this.options.debug&&t.debug(this.options.debug);var i=this.container.innerHTML.trim();this.container.classList.add("ql-container"),this.container.innerHTML="",this.container.__quill=this,this.root=this.addContainer("ql-editor"),this.root.classList.add("ql-blank"),this.root.setAttribute("data-gramm",!1),this.scrollingContainer=this.options.scrollingContainer||this.root,this.emitter=new p.default,this.scroll=g.default.create(this.root,{emitter:this.emitter,whitelist:this.options.formats}),this.editor=new h.default(this.scroll),this.selection=new y.default(this.scroll,this.emitter),this.theme=new this.options.theme(this,this.options),this.keyboard=this.theme.addModule("keyboard"),this.clipboard=this.theme.addModule("clipboard"),this.history=this.theme.addModule("history"),this.theme.init(),this.emitter.on(p.default.events.EDITOR_CHANGE,function(t){t===p.default.events.TEXT_CHANGE&&n.root.classList.toggle("ql-blank",n.editor.isBlank())}),this.emitter.on(p.default.events.SCROLL_UPDATE,function(t,e){var r=n.selection.lastRange,i=r&&0===r.length?r.index:void 0;a.call(n,function(){return n.editor.update(null,e,i)},t)});var s=this.clipboard.convert("<div class='ql-editor' style=\"white-space: normal;\">"+i+"<p><br></p></div>");this.setContents(s),this.history.clear(),this.options.placeholder&&this.root.setAttribute("data-placeholder",this.options.placeholder),this.options.readOnly&&this.disable()}return f(t,null,[{key:"debug",value:function(t){!0===t&&(t="log"),w.default.level(t)}},{key:"find",value:function(t){return t.__quill||g.default.find(t)}},{key:"import",value:function(t){return null==this.imports[t]&&x.error("Cannot import "+t+". Are you sure it was registered?"),this.imports[t]}},{key:"register",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if("string"!=typeof t){var i=t.attrName||t.blotName;"string"==typeof i?this.register("formats/"+i,t,e):Object.keys(t).forEach(function(r){n.register(r,t[r],e)})}else null==this.imports[t]||r||x.warn("Overwriting "+t+" with",e),this.imports[t]=e,(t.startsWith("blots/")||t.startsWith("formats/"))&&"abstract"!==e.blotName?g.default.register(e):t.startsWith("modules")&&"function"==typeof e.register&&e.register()}}]),f(t,[{key:"addContainer",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if("string"==typeof t){var n=t;(t=document.createElement("div")).classList.add(n)}return this.container.insertBefore(t,e),t}},{key:"blur",value:function(){this.selection.setRange(null)}},{key:"deleteText",value:function(t,e,n){var r=this,i=s(t,e,n),o=u(i,4);return t=o[0],e=o[1],n=o[3],a.call(this,function(){return r.editor.deleteText(t,e)},n,t,-1*e)}},{key:"disable",value:function(){this.enable(!1)}},{key:"enable",value:function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.scroll.enable(t),this.container.classList.toggle("ql-disabled",!t)}},{key:"focus",value:function(){var t=this.scrollingContainer.scrollTop;this.selection.focus(),this.scrollingContainer.scrollTop=t,this.scrollIntoView()}},{key:"format",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:p.default.sources.API;return a.call(this,function(){var r=n.getSelection(!0),o=new d.default;if(null==r)return o;if(g.default.query(t,g.default.Scope.BLOCK))o=n.editor.formatLine(r.index,r.length,i({},t,e));else{if(0===r.length)return n.selection.format(t,e),o;o=n.editor.formatText(r.index,r.length,i({},t,e))}return n.setSelection(r,p.default.sources.SILENT),o},r)}},{key:"formatLine",value:function(t,e,n,r,i){var o,l=this,c=s(t,e,n,r,i),f=u(c,4);return t=f[0],e=f[1],o=f[2],i=f[3],a.call(this,function(){return l.editor.formatLine(t,e,o)},i,t,0)}},{key:"formatText",value:function(t,e,n,r,i){var o,l=this,c=s(t,e,n,r,i),f=u(c,4);return t=f[0],e=f[1],o=f[2],i=f[3],a.call(this,function(){return l.editor.formatText(t,e,o)},i,t,0)}},{key:"getBounds",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=void 0;n="number"==typeof t?this.selection.getBounds(t,e):this.selection.getBounds(t.index,t.length);var r=this.container.getBoundingClientRect();return{bottom:n.bottom-r.top,height:n.height,left:n.left-r.left,right:n.right-r.left,top:n.top-r.top,width:n.width}}},{key:"getContents",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.getLength()-t,n=s(t,e),r=u(n,2);return t=r[0],e=r[1],this.editor.getContents(t,e)}},{key:"getFormat",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.getSelection(!0),e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return"number"==typeof t?this.editor.getFormat(t,e):this.editor.getFormat(t.index,t.length)}},{key:"getIndex",value:function(t){return t.offset(this.scroll)}},{key:"getLength",value:function(){return this.scroll.length()}},{key:"getLeaf",value:function(t){return this.scroll.leaf(t)}},{key:"getLine",value:function(t){return this.scroll.line(t)}},{key:"getLines",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Number.MAX_VALUE;return"number"!=typeof t?this.scroll.lines(t.index,t.length):this.scroll.lines(t,e)}},{key:"getModule",value:function(t){return this.theme.modules[t]}},{key:"getSelection",value:function(){return arguments.length>0&&void 0!==arguments[0]&&arguments[0]&&this.focus(),this.update(),this.selection.getRange()[0]}},{key:"getText",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.getLength()-t,n=s(t,e),r=u(n,2);return t=r[0],e=r[1],this.editor.getText(t,e)}},{key:"hasFocus",value:function(){return this.selection.hasFocus()}},{key:"insertEmbed",value:function(e,n,r){var i=this,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t.sources.API;return a.call(this,function(){return i.editor.insertEmbed(e,n,r)},o,e)}},{key:"insertText",value:function(t,e,n,r,i){var o,l=this,c=s(t,0,n,r,i),f=u(c,4);return t=f[0],o=f[2],i=f[3],a.call(this,function(){return l.editor.insertText(t,e,o)},i,t,e.length)}},{key:"isEnabled",value:function(){return!this.container.classList.contains("ql-disabled")}},{key:"off",value:function(){return this.emitter.off.apply(this.emitter,arguments)}},{key:"on",value:function(){return this.emitter.on.apply(this.emitter,arguments)}},{key:"once",value:function(){return this.emitter.once.apply(this.emitter,arguments)}},{key:"pasteHTML",value:function(t,e,n){this.clipboard.dangerouslyPasteHTML(t,e,n)}},{key:"removeFormat",value:function(t,e,n){var r=this,i=s(t,e,n),o=u(i,4);return t=o[0],e=o[1],n=o[3],a.call(this,function(){return r.editor.removeFormat(t,e)},n,t)}},{key:"scrollIntoView",value:function(){this.selection.scrollIntoView(this.scrollingContainer)}},{key:"setContents",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p.default.sources.API;return a.call(this,function(){t=new d.default(t);var n=e.getLength(),r=e.editor.deleteText(0,n),i=e.editor.applyDelta(t),o=i.ops[i.ops.length-1];return null!=o&&"string"==typeof o.insert&&"\n"===o.insert[o.insert.length-1]&&(e.editor.deleteText(e.getLength()-1,1),i.delete(1)),r.compose(i)},n)}},{key:"setSelection",value:function(e,n,r){if(null==e)this.selection.setRange(null,n||t.sources.API);else{var i=s(e,n,r),o=u(i,4);e=o[0],n=o[1],r=o[3],this.selection.setRange(new m.Range(e,n),r),r!==p.default.sources.SILENT&&this.selection.scrollIntoView(this.scrollingContainer)}}},{key:"setText",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p.default.sources.API,n=(new d.default).insert(t);return this.setContents(n,e)}},{key:"update",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:p.default.sources.USER,e=this.scroll.update(t);return this.selection.update(t),e}},{key:"updateContents",value:function(t){var e=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:p.default.sources.API;return a.call(this,function(){return t=new d.default(t),e.editor.applyDelta(t,n)},n,!0)}}]),t}();k.DEFAULTS={bounds:null,formats:null,modules:{},placeholder:"",readOnly:!1,scrollingContainer:null,strict:!0,theme:"default"},k.events=p.default.events,k.sources=p.default.sources,k.version="1.3.6",k.imports={delta:d.default,parchment:g.default,"core/module":v.default,"core/theme":_.default},e.expandConfig=o,e.overload=s,e.default=k},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},a=r(n(7)),s=r(n(0)),l=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,s.default.Inline),i(e,[{key:"formatAt",value:function(t,n,r,i){if(e.compare(this.statics.blotName,r)<0&&s.default.query(r,s.default.Scope.BLOT)){var a=this.isolate(t,n);i&&a.wrap(r,i)}else o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"formatAt",this).call(this,t,n,r,i)}},{key:"optimize",value:function(t){if(o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"optimize",this).call(this,t),this.parent instanceof e&&e.compare(this.statics.blotName,this.parent.statics.blotName)>0){var n=this.parent.isolate(this.offset(),this.length());this.moveChildren(n),n.wrap(this)}}}],[{key:"compare",value:function(t,n){var r=e.order.indexOf(t),i=e.order.indexOf(n);return r>=0||i>=0?r-i:t===n?0:t<n?-1:1}}]),e}();l.allowedChildren=[l,s.default.Embed,a.default],l.order=["cursor","inline","underline","strike","italic","bold","script","link","code"],e.default=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(0),o=(r=i)&&r.__esModule?r:{default:r},a=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,o.default.Text),e}();e.default=a},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=r(n(54)),a=(0,r(n(10)).default)("quill:events");["selectionchange","mousedown","mouseup","click"].forEach(function(t){document.addEventListener(t,function(){for(var t=arguments.length,e=Array(t),n=0;n<t;n++)e[n]=arguments[n];[].slice.call(document.querySelectorAll(".ql-container")).forEach(function(t){var n;t.__quill&&t.__quill.emitter&&(n=t.__quill.emitter).handleDOM.apply(n,e)})})});var s=function(t){function e(){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var t=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));return t.listeners={},t.on("error",a.error),t}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,o.default),i(e,[{key:"emit",value:function(){a.log.apply(a,arguments),function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"emit",this).apply(this,arguments)}},{key:"handleDOM",value:function(t){for(var e=arguments.length,n=Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];(this.listeners[t.type]||[]).forEach(function(e){var r=e.node,i=e.handler;(t.target===r||r.contains(t.target))&&i.apply(void 0,[t].concat(n))})}},{key:"listenDOM",value:function(t,e,n){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push({node:e,handler:n})}}]),e}();s.events={EDITOR_CHANGE:"editor-change",SCROLL_BEFORE_UPDATE:"scroll-before-update",SCROLL_OPTIMIZE:"scroll-optimize",SCROLL_UPDATE:"scroll-update",SELECTION_CHANGE:"selection-change",TEXT_CHANGE:"text-change"},s.sources={API:"api",SILENT:"silent",USER:"user"},e.default=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.quill=e,this.options=n};r.DEFAULTS={},e.default=r},function(t,e,n){"use strict";function r(t){if(o.indexOf(t)<=o.indexOf(a)){for(var e,n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];(e=console)[t].apply(e,r)}}function i(t){return o.reduce(function(e,n){return e[n]=r.bind(console,n,t),e},{})}Object.defineProperty(e,"__esModule",{value:!0});var o=["error","warn","log","info"],a="warn";r.level=i.level=function(t){a=t},e.default=i},function(t,e,n){function r(t){return null===t||void 0===t}function i(t){return!(!t||"object"!=typeof t||"number"!=typeof t.length||"function"!=typeof t.copy||"function"!=typeof t.slice||t.length>0&&"number"!=typeof t[0])}var o=Array.prototype.slice,a=n(52),s=n(53),l=t.exports=function(t,e,n){return n||(n={}),t===e||(t instanceof Date&&e instanceof Date?t.getTime()===e.getTime():!t||!e||"object"!=typeof t&&"object"!=typeof e?n.strict?t===e:t==e:function(t,e,n){var c,u;if(r(t)||r(e))return!1;if(t.prototype!==e.prototype)return!1;if(s(t))return!!s(e)&&(t=o.call(t),e=o.call(e),l(t,e,n));if(i(t)){if(!i(e))return!1;if(t.length!==e.length)return!1;for(c=0;c<t.length;c++)if(t[c]!==e[c])return!1;return!0}try{var f=a(t),d=a(e)}catch(t){return!1}if(f.length!=d.length)return!1;for(f.sort(),d.sort(),c=f.length-1;c>=0;c--)if(f[c]!=d[c])return!1;for(c=f.length-1;c>=0;c--)if(u=f[c],!l(t[u],e[u],n))return!1;return typeof t==typeof e}(t,e,n))}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=function(){function t(t,e,n){void 0===n&&(n={}),this.attrName=t,this.keyName=e;var i=r.Scope.TYPE&r.Scope.ATTRIBUTE;null!=n.scope?this.scope=n.scope&r.Scope.LEVEL|i:this.scope=r.Scope.ATTRIBUTE,null!=n.whitelist&&(this.whitelist=n.whitelist)}return t.keys=function(t){return[].map.call(t.attributes,function(t){return t.name})},t.prototype.add=function(t,e){return!!this.canAdd(t,e)&&(t.setAttribute(this.keyName,e),!0)},t.prototype.canAdd=function(t,e){return null!=r.query(t,r.Scope.BLOT&(this.scope|r.Scope.TYPE))&&(null==this.whitelist||("string"==typeof e?this.whitelist.indexOf(e.replace(/["']/g,""))>-1:this.whitelist.indexOf(e)>-1))},t.prototype.remove=function(t){t.removeAttribute(this.keyName)},t.prototype.value=function(t){var e=t.getAttribute(this.keyName);return this.canAdd(t,e)&&e?e:""},t}();e.default=i},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.Code=void 0;var s=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),l=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),c=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},u=r(n(2)),f=r(n(0)),d=r(n(4)),h=r(n(6)),p=r(n(7)),v=function(t){function e(){return i(this,e),o(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return a(e,h.default),e}();v.blotName="code",v.tagName="CODE";var g=function(t){function e(){return i(this,e),o(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return a(e,d.default),l(e,[{key:"delta",value:function(){var t=this,e=this.domNode.textContent;return e.endsWith("\n")&&(e=e.slice(0,-1)),e.split("\n").reduce(function(e,n){return e.insert(n).insert("\n",t.formats())},new u.default)}},{key:"format",value:function(t,n){if(t!==this.statics.blotName||!n){var r=this.descendant(p.default,this.length()-1),i=s(r,1)[0];null!=i&&i.deleteAt(i.length()-1,1),c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"format",this).call(this,t,n)}}},{key:"formatAt",value:function(t,n,r,i){if(0!==n&&null!=f.default.query(r,f.default.Scope.BLOCK)&&(r!==this.statics.blotName||i!==this.statics.formats(this.domNode))){var o=this.newlineIndex(t);if(!(o<0||o>=t+n)){var a=this.newlineIndex(t,!0)+1,s=o-a+1,l=this.isolate(a,s),c=l.next;l.format(r,i),c instanceof e&&c.formatAt(0,t-a+n-s,r,i)}}}},{key:"insertAt",value:function(t,e,n){if(null==n){var r=this.descendant(p.default,t),i=s(r,2),o=i[0],a=i[1];o.insertAt(a,e)}}},{key:"length",value:function(){var t=this.domNode.textContent.length;return this.domNode.textContent.endsWith("\n")?t:t+1}},{key:"newlineIndex",value:function(t){if(arguments.length>1&&void 0!==arguments[1]&&arguments[1])return this.domNode.textContent.slice(0,t).lastIndexOf("\n");var e=this.domNode.textContent.slice(t).indexOf("\n");return e>-1?t+e:-1}},{key:"optimize",value:function(t){
this.domNode.textContent.endsWith("\n")||this.appendChild(f.default.create("text","\n")),c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"optimize",this).call(this,t);var n=this.next;null!=n&&n.prev===this&&n.statics.blotName===this.statics.blotName&&this.statics.formats(this.domNode)===n.statics.formats(n.domNode)&&(n.optimize(t),n.moveChildren(this),n.remove())}},{key:"replace",value:function(t){c(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"replace",this).call(this,t),[].slice.call(this.domNode.querySelectorAll("*")).forEach(function(t){var e=f.default.find(t);null==e?t.parentNode.removeChild(t):e instanceof f.default.Embed?e.remove():e.unwrap()})}}],[{key:"create",value:function(t){var n=c(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this,t);return n.setAttribute("spellcheck",!1),n}},{key:"formats",value:function(){return!0}}]),e}();g.blotName="code-block",g.tagName="PRE",g.TAB=" ",e.Code=v,e.default=g},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){return Object.keys(e).reduce(function(n,r){return null==t[r]?n:(e[r]===t[r]?n[r]=e[r]:Array.isArray(e[r])?e[r].indexOf(t[r])<0&&(n[r]=e[r].concat([t[r]])):n[r]=[e[r],t[r]],n)},{})}Object.defineProperty(e,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),l=r(n(2)),c=r(n(20)),u=r(n(0)),f=r(n(13)),d=r(n(24)),h=n(4),p=r(h),v=r(n(16)),g=r(n(21)),m=r(n(11)),y=r(n(3)),b=/^[ -~]*$/,w=function(){function t(e){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.scroll=e,this.delta=this.getDelta()}return s(t,[{key:"applyDelta",value:function(t){var e=this,n=!1;this.scroll.update();var r=this.scroll.length();return this.scroll.batchStart(),(t=function(t){return t.reduce(function(t,e){if(1===e.insert){var n=(0,g.default)(e.attributes);return delete n.image,t.insert({image:e.attributes.image},n)}if(null==e.attributes||!0!==e.attributes.list&&!0!==e.attributes.bullet||((e=(0,g.default)(e)).attributes.list?e.attributes.list="ordered":(e.attributes.list="bullet",delete e.attributes.bullet)),"string"==typeof e.insert){var r=e.insert.replace(/\r\n/g,"\n").replace(/\r/g,"\n");return t.insert(r,e.attributes)}return t.push(e)},new l.default)}(t)).reduce(function(t,i){var s=i.retain||i.delete||i.insert.length||1,l=i.attributes||{};if(null!=i.insert){if("string"==typeof i.insert){var f=i.insert;f.endsWith("\n")&&n&&(n=!1,f=f.slice(0,-1)),t>=r&&!f.endsWith("\n")&&(n=!0),e.scroll.insertAt(t,f);var d=e.scroll.line(t),v=a(d,2),g=v[0],m=v[1],b=(0,y.default)({},(0,h.bubbleFormats)(g));if(g instanceof p.default){var w=g.descendant(u.default.Leaf,m),_=a(w,1)[0];b=(0,y.default)(b,(0,h.bubbleFormats)(_))}l=c.default.attributes.diff(b,l)||{}}else if("object"===o(i.insert)){var x=Object.keys(i.insert)[0];if(null==x)return t;e.scroll.insertAt(t,x,i.insert[x])}r+=s}return Object.keys(l).forEach(function(n){e.scroll.formatAt(t,s,n,l[n])}),t+s},0),t.reduce(function(t,n){return"number"==typeof n.delete?(e.scroll.deleteAt(t,n.delete),t):t+(n.retain||n.insert.length||1)},0),this.scroll.batchEnd(),this.update(t)}},{key:"deleteText",value:function(t,e){return this.scroll.deleteAt(t,e),this.update((new l.default).retain(t).delete(e))}},{key:"formatLine",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.scroll.update(),Object.keys(r).forEach(function(i){if(null==n.scroll.whitelist||n.scroll.whitelist[i]){var o=n.scroll.lines(t,Math.max(e,1)),a=e;o.forEach(function(e){var o=e.length();if(e instanceof f.default){var s=t-e.offset(n.scroll),l=e.newlineIndex(s+a)-s+1;e.formatAt(s,l,i,r[i])}else e.format(i,r[i]);a-=o})}}),this.scroll.optimize(),this.update((new l.default).retain(t).retain(e,(0,g.default)(r)))}},{key:"formatText",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return Object.keys(r).forEach(function(i){n.scroll.formatAt(t,e,i,r[i])}),this.update((new l.default).retain(t).retain(e,(0,g.default)(r)))}},{key:"getContents",value:function(t,e){return this.delta.slice(t,t+e)}},{key:"getDelta",value:function(){return this.scroll.lines().reduce(function(t,e){return t.concat(e.delta())},new l.default)}},{key:"getFormat",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=[],r=[];0===e?this.scroll.path(t).forEach(function(t){var e=a(t,1)[0];e instanceof p.default?n.push(e):e instanceof u.default.Leaf&&r.push(e)}):(n=this.scroll.lines(t,e),r=this.scroll.descendants(u.default.Leaf,t,e));var o=[n,r].map(function(t){if(0===t.length)return{};for(var e=(0,h.bubbleFormats)(t.shift());Object.keys(e).length>0;){var n=t.shift();if(null==n)return e;e=i((0,h.bubbleFormats)(n),e)}return e});return y.default.apply(y.default,o)}},{key:"getText",value:function(t,e){return this.getContents(t,e).filter(function(t){return"string"==typeof t.insert}).map(function(t){return t.insert}).join("")}},{key:"insertEmbed",value:function(t,e,n){return this.scroll.insertAt(t,e,n),this.update((new l.default).retain(t).insert(function(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},e,n)))}},{key:"insertText",value:function(t,e){var n=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return e=e.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),this.scroll.insertAt(t,e),Object.keys(r).forEach(function(i){n.scroll.formatAt(t,e.length,i,r[i])}),this.update((new l.default).retain(t).insert(e,(0,g.default)(r)))}},{key:"isBlank",value:function(){if(0==this.scroll.children.length)return!0;if(this.scroll.children.length>1)return!1;var t=this.scroll.children.head;return t.statics.blotName===p.default.blotName&&!(t.children.length>1)&&t.children.head instanceof v.default}},{key:"removeFormat",value:function(t,e){var n=this.getText(t,e),r=this.scroll.line(t+e),i=a(r,2),o=i[0],s=i[1],c=0,u=new l.default;null!=o&&(c=o instanceof f.default?o.newlineIndex(s)-s+1:o.length()-s,u=o.delta().slice(s,s+c-1).insert("\n"));var d=this.getContents(t,e+c).diff((new l.default).insert(n).concat(u)),h=(new l.default).retain(t).concat(d);return this.applyDelta(h)}},{key:"update",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,r=this.delta;if(1===e.length&&"characterData"===e[0].type&&e[0].target.data.match(b)&&u.default.find(e[0].target)){var i=u.default.find(e[0].target),o=(0,h.bubbleFormats)(i),a=i.offset(this.scroll),s=e[0].oldValue.replace(d.default.CONTENTS,""),c=(new l.default).insert(s),f=(new l.default).insert(i.value());t=(new l.default).retain(a).concat(c.diff(f,n)).reduce(function(t,e){return e.insert?t.insert(e.insert,o):t.push(e)},new l.default),this.delta=r.compose(t)}else this.delta=this.getDelta(),t&&(0,m.default)(r.compose(t),this.delta)||(t=r.diff(this.delta,n));return t}}]),t}();e.default=w},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)}function o(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){try{e.parentNode}catch(t){return!1}return e instanceof Text&&(e=e.parentNode),t.contains(e)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.Range=void 0;var s=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),l=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),c=r(n(0)),u=r(n(21)),f=r(n(11)),d=r(n(8)),h=(0,r(n(10)).default)("quill:selection"),p=function t(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;o(this,t),this.index=e,this.length=n},v=function(){function t(e,n){var r=this;o(this,t),this.emitter=n,this.scroll=e,this.composing=!1,this.mouseDown=!1,this.root=this.scroll.domNode,this.cursor=c.default.create("cursor",this),this.lastRange=this.savedRange=new p(0,0),this.handleComposition(),this.handleDragging(),this.emitter.listenDOM("selectionchange",document,function(){r.mouseDown||setTimeout(r.update.bind(r,d.default.sources.USER),1)}),this.emitter.on(d.default.events.EDITOR_CHANGE,function(t,e){t===d.default.events.TEXT_CHANGE&&e.length()>0&&r.update(d.default.sources.SILENT)}),this.emitter.on(d.default.events.SCROLL_BEFORE_UPDATE,function(){if(r.hasFocus()){var t=r.getNativeRange();null!=t&&t.start.node!==r.cursor.textNode&&r.emitter.once(d.default.events.SCROLL_UPDATE,function(){try{r.setNativeRange(t.start.node,t.start.offset,t.end.node,t.end.offset)}catch(t){}})}}),this.emitter.on(d.default.events.SCROLL_OPTIMIZE,function(t,e){if(e.range){var n=e.range,i=n.startNode,o=n.startOffset,a=n.endNode,s=n.endOffset;r.setNativeRange(i,o,a,s)}}),this.update(d.default.sources.SILENT)}return l(t,[{key:"handleComposition",value:function(){var t=this;this.root.addEventListener("compositionstart",function(){t.composing=!0}),this.root.addEventListener("compositionend",function(){if(t.composing=!1,t.cursor.parent){var e=t.cursor.restore();if(!e)return;setTimeout(function(){t.setNativeRange(e.startNode,e.startOffset,e.endNode,e.endOffset)},1)}})}},{key:"handleDragging",value:function(){var t=this;this.emitter.listenDOM("mousedown",document.body,function(){t.mouseDown=!0}),this.emitter.listenDOM("mouseup",document.body,function(){t.mouseDown=!1,t.update(d.default.sources.USER)})}},{key:"focus",value:function(){this.hasFocus()||(this.root.focus(),this.setRange(this.savedRange))}},{key:"format",value:function(t,e){if(null==this.scroll.whitelist||this.scroll.whitelist[t]){this.scroll.update();var n=this.getNativeRange();if(null!=n&&n.native.collapsed&&!c.default.query(t,c.default.Scope.BLOCK)){if(n.start.node!==this.cursor.textNode){var r=c.default.find(n.start.node,!1);if(null==r)return;if(r instanceof c.default.Leaf){var i=r.split(n.start.offset);r.parent.insertBefore(this.cursor,i)}else r.insertBefore(this.cursor,n.start.node);this.cursor.attach()}this.cursor.format(t,e),this.scroll.optimize(),this.setNativeRange(this.cursor.textNode,this.cursor.textNode.data.length),this.update()}}}},{key:"getBounds",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=this.scroll.length();t=Math.min(t,n-1),e=Math.min(t+e,n-1)-t;var r=void 0,i=this.scroll.leaf(t),o=s(i,2),a=o[0],l=o[1];if(null==a)return null;var c=a.position(l,!0),u=s(c,2);r=u[0],l=u[1];var f=document.createRange();if(e>0){f.setStart(r,l);var d=this.scroll.leaf(t+e),h=s(d,2);if(a=h[0],l=h[1],null==a)return null;var p=a.position(l,!0),v=s(p,2);return r=v[0],l=v[1],f.setEnd(r,l),f.getBoundingClientRect()}var g="left",m=void 0;return r instanceof Text?(l<r.data.length?(f.setStart(r,l),f.setEnd(r,l+1)):(f.setStart(r,l-1),f.setEnd(r,l),g="right"),m=f.getBoundingClientRect()):(m=a.domNode.getBoundingClientRect(),l>0&&(g="right")),{bottom:m.top+m.height,height:m.height,left:m[g],right:m[g],top:m.top,width:0}}},{key:"getNativeRange",value:function(){var t=document.getSelection();if(null==t||t.rangeCount<=0)return null;var e=t.getRangeAt(0);if(null==e)return null;var n=this.normalizeNative(e);return h.info("getNativeRange",n),n}},{key:"getRange",value:function(){var t=this.getNativeRange();return null==t?[null,null]:[this.normalizedToRange(t),t]}},{key:"hasFocus",value:function(){return document.activeElement===this.root}},{key:"normalizedToRange",value:function(t){var e=this,n=[[t.start.node,t.start.offset]];t.native.collapsed||n.push([t.end.node,t.end.offset]);var r=n.map(function(t){var n=s(t,2),r=n[0],i=n[1],o=c.default.find(r,!0),a=o.offset(e.scroll);return 0===i?a:o instanceof c.default.Container?a+o.length():a+o.index(r,i)}),o=Math.min(Math.max.apply(Math,i(r)),this.scroll.length()-1),a=Math.min.apply(Math,[o].concat(i(r)));return new p(a,o-a)}},{key:"normalizeNative",value:function(t){if(!a(this.root,t.startContainer)||!t.collapsed&&!a(this.root,t.endContainer))return null;var e={start:{node:t.startContainer,offset:t.startOffset},end:{node:t.endContainer,offset:t.endOffset},native:t};return[e.start,e.end].forEach(function(t){for(var e=t.node,n=t.offset;!(e instanceof Text)&&e.childNodes.length>0;)if(e.childNodes.length>n)e=e.childNodes[n],n=0;else{if(e.childNodes.length!==n)break;n=(e=e.lastChild)instanceof Text?e.data.length:e.childNodes.length+1}t.node=e,t.offset=n}),e}},{key:"rangeToNative",value:function(t){var e=this,n=t.collapsed?[t.index]:[t.index,t.index+t.length],r=[],i=this.scroll.length();return n.forEach(function(t,n){t=Math.min(i-1,t);var o,a=e.scroll.leaf(t),l=s(a,2),c=l[0],u=l[1],f=c.position(u,0!==n),d=s(f,2);o=d[0],u=d[1],r.push(o,u)}),r.length<2&&(r=r.concat(r)),r}},{key:"scrollIntoView",value:function(t){var e=this.lastRange;if(null!=e){var n=this.getBounds(e.index,e.length);if(null!=n){var r=this.scroll.length()-1,i=this.scroll.line(Math.min(e.index,r)),o=s(i,1)[0],a=o;if(e.length>0){var l=this.scroll.line(Math.min(e.index+e.length,r));a=s(l,1)[0]}if(null!=o&&null!=a){var c=t.getBoundingClientRect();n.top<c.top?t.scrollTop-=c.top-n.top:n.bottom>c.bottom&&(t.scrollTop+=n.bottom-c.bottom)}}}}},{key:"setNativeRange",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e,i=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if(h.info("setNativeRange",t,e,n,r),null==t||null!=this.root.parentNode&&null!=t.parentNode&&null!=n.parentNode){var o=document.getSelection();if(null!=o)if(null!=t){this.hasFocus()||this.root.focus();var a=(this.getNativeRange()||{}).native;if(null==a||i||t!==a.startContainer||e!==a.startOffset||n!==a.endContainer||r!==a.endOffset){"BR"==t.tagName&&(e=[].indexOf.call(t.parentNode.childNodes,t),t=t.parentNode),"BR"==n.tagName&&(r=[].indexOf.call(n.parentNode.childNodes,n),n=n.parentNode);var s=document.createRange();s.setStart(t,e),s.setEnd(n,r),o.removeAllRanges(),o.addRange(s)}}else o.removeAllRanges(),this.root.blur(),document.body.focus()}}},{key:"setRange",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d.default.sources.API;if("string"==typeof e&&(n=e,e=!1),h.info("setRange",t),null!=t){var r=this.rangeToNative(t);this.setNativeRange.apply(this,i(r).concat([e]))}else this.setNativeRange(null);this.update(n)}},{key:"update",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:d.default.sources.USER,e=this.lastRange,n=this.getRange(),r=s(n,2),i=r[0],o=r[1];if(this.lastRange=i,null!=this.lastRange&&(this.savedRange=this.lastRange),!(0,f.default)(e,this.lastRange)){var a;!this.composing&&null!=o&&o.native.collapsed&&o.start.node!==this.cursor.textNode&&this.cursor.restore();var l,c=[d.default.events.SELECTION_CHANGE,(0,u.default)(this.lastRange),(0,u.default)(e),t];(a=this.emitter).emit.apply(a,[d.default.events.EDITOR_CHANGE].concat(c)),t!==d.default.sources.SILENT&&(l=this.emitter).emit.apply(l,c)}}}]),t}();e.Range=p,e.default=v},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(0),a=(r=o)&&r.__esModule?r:{default:r},s=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,a.default.Embed),i(e,[{key:"insertInto",value:function(t,n){0===t.children.length?function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertInto",this).call(this,t,n):this.remove()}},{key:"length",value:function(){return 0}},{key:"value",value:function(){return""}}],[{key:"value",value:function(){}}]),e}();s.blotName="break",s.tagName="BR",e.default=s},function(t,e,n){"use strict";function r(t){var e=l.find(t);if(null==e)try{e=l.create(t)}catch(n){e=l.create(l.Scope.INLINE),[].slice.call(t.childNodes).forEach(function(t){e.domNode.appendChild(t)}),t.parentNode&&t.parentNode.replaceChild(e.domNode,t),e.attach()}return e}var i,o=this&&this.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var a=n(44),s=n(30),l=n(1),c=function(t){function e(e){var n=t.call(this,e)||this;return n.build(),n}return o(e,t),e.prototype.appendChild=function(t){this.insertBefore(t)},e.prototype.attach=function(){t.prototype.attach.call(this),this.children.forEach(function(t){t.attach()})},e.prototype.build=function(){var t=this;this.children=new a.default,[].slice.call(this.domNode.childNodes).reverse().forEach(function(e){try{var n=r(e);t.insertBefore(n,t.children.head||void 0)}catch(t){if(t instanceof l.ParchmentError)return;throw t}})},e.prototype.deleteAt=function(t,e){if(0===t&&e===this.length())return this.remove();this.children.forEachAt(t,e,function(t,e,n){t.deleteAt(e,n)})},e.prototype.descendant=function(t,n){var r=this.children.find(n),i=r[0],o=r[1];return null==t.blotName&&t(i)||null!=t.blotName&&i instanceof t?[i,o]:i instanceof e?i.descendant(t,o):[null,-1]},e.prototype.descendants=function(t,n,r){void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE);var i=[],o=r;return this.children.forEachAt(n,r,function(n,r,a){(null==t.blotName&&t(n)||null!=t.blotName&&n instanceof t)&&i.push(n),n instanceof e&&(i=i.concat(n.descendants(t,r,o))),o-=a}),i},e.prototype.detach=function(){this.children.forEach(function(t){t.detach()}),t.prototype.detach.call(this)},e.prototype.formatAt=function(t,e,n,r){this.children.forEachAt(t,e,function(t,e,i){t.formatAt(e,i,n,r)})},e.prototype.insertAt=function(t,e,n){var r=this.children.find(t),i=r[0],o=r[1];if(i)i.insertAt(o,e,n);else{var a=null==n?l.create("text",e):l.create(e,n);this.appendChild(a)}},e.prototype.insertBefore=function(t,e){if(null!=this.statics.allowedChildren&&!this.statics.allowedChildren.some(function(e){return t instanceof e}))throw new l.ParchmentError("Cannot insert "+t.statics.blotName+" into "+this.statics.blotName);t.insertInto(this,e)},e.prototype.length=function(){return this.children.reduce(function(t,e){return t+e.length()},0)},e.prototype.moveChildren=function(t,e){this.children.forEach(function(n){t.insertBefore(n,e)})},e.prototype.optimize=function(e){if(t.prototype.optimize.call(this,e),0===this.children.length)if(null!=this.statics.defaultChild){var n=l.create(this.statics.defaultChild);this.appendChild(n),n.optimize(e)}else this.remove()},e.prototype.path=function(t,n){void 0===n&&(n=!1);var r=this.children.find(t,n),i=r[0],o=r[1],a=[[this,t]];return i instanceof e?a.concat(i.path(o,n)):(null!=i&&a.push([i,o]),a)},e.prototype.removeChild=function(t){this.children.remove(t)},e.prototype.replace=function(n){n instanceof e&&n.moveChildren(this),t.prototype.replace.call(this,n)},e.prototype.split=function(t,e){if(void 0===e&&(e=!1),!e){if(0===t)return this;if(t===this.length())return this.next}var n=this.clone();return this.parent.insertBefore(n,this.next),this.children.forEachAt(t,this.length(),function(t,r,i){t=t.split(r,e),n.appendChild(t)}),n},e.prototype.unwrap=function(){this.moveChildren(this.parent,this.next),this.remove()},e.prototype.update=function(t,e){var n=this,i=[],o=[];t.forEach(function(t){t.target===n.domNode&&"childList"===t.type&&(i.push.apply(i,t.addedNodes),o.push.apply(o,t.removedNodes))}),o.forEach(function(t){if(!(null!=t.parentNode&&"IFRAME"!==t.tagName&&document.body.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_CONTAINED_BY)){var e=l.find(t);null!=e&&(null!=e.domNode.parentNode&&e.domNode.parentNode!==n.domNode||e.detach())}}),i.filter(function(t){return t.parentNode==n.domNode}).sort(function(t,e){return t===e?0:t.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING?1:-1}).forEach(function(t){var e=null;null!=t.nextSibling&&(e=l.find(t.nextSibling));var i=r(t);i.next==e&&null!=i.next||(null!=i.parent&&i.parent.removeChild(n),n.insertBefore(i,e||void 0))})},e}(s.default);e.default=c},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(12),a=n(31),s=n(17),l=n(1),c=function(t){function e(e){var n=t.call(this,e)||this;return n.attributes=new a.default(n.domNode),n}return i(e,t),e.formats=function(t){return"string"==typeof this.tagName||(Array.isArray(this.tagName)?t.tagName.toLowerCase():void 0)},e.prototype.format=function(t,e){var n=l.query(t);n instanceof o.default?this.attributes.attribute(n,e):e&&(null==n||t===this.statics.blotName&&this.formats()[t]===e||this.replaceWith(t,e))},e.prototype.formats=function(){var t=this.attributes.values(),e=this.statics.formats(this.domNode);return null!=e&&(t[this.statics.blotName]=e),t},e.prototype.replaceWith=function(e,n){var r=t.prototype.replaceWith.call(this,e,n);return this.attributes.copy(r),r},e.prototype.update=function(e,n){var r=this;t.prototype.update.call(this,e,n),e.some(function(t){return t.target===r.domNode&&"attributes"===t.type})&&this.attributes.build()},e.prototype.wrap=function(n,r){var i=t.prototype.wrap.call(this,n,r);return i instanceof e&&i.statics.scope===this.statics.scope&&this.attributes.move(i),i},e}(s.default);e.default=c},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(30),a=n(1),s=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.value=function(t){return!0},e.prototype.index=function(t,e){return this.domNode===t||this.domNode.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_CONTAINED_BY?Math.min(e,1):-1},e.prototype.position=function(t,e){var n=[].indexOf.call(this.parent.domNode.childNodes,this.domNode);return t>0&&(n+=1),[this.parent.domNode,n]},e.prototype.value=function(){return(t={})[this.statics.blotName]=this.statics.value(this.domNode)||!0,t;var t},e.scope=a.Scope.INLINE_BLOT,e}(o.default);e.default=s},function(t,e,n){function r(t){this.ops=t,this.index=0,this.offset=0}var i=n(11),o=n(3),a={attributes:{compose:function(t,e,n){"object"!=typeof t&&(t={}),"object"!=typeof e&&(e={});var r=o(!0,{},e);for(var i in n||(r=Object.keys(r).reduce(function(t,e){return null!=r[e]&&(t[e]=r[e]),t},{})),t)void 0!==t[i]&&void 0===e[i]&&(r[i]=t[i]);return Object.keys(r).length>0?r:void 0},diff:function(t,e){"object"!=typeof t&&(t={}),"object"!=typeof e&&(e={});var n=Object.keys(t).concat(Object.keys(e)).reduce(function(n,r){return i(t[r],e[r])||(n[r]=void 0===e[r]?null:e[r]),n},{});return Object.keys(n).length>0?n:void 0},transform:function(t,e,n){if("object"!=typeof t)return e;if("object"==typeof e){if(!n)return e;var r=Object.keys(e).reduce(function(n,r){return void 0===t[r]&&(n[r]=e[r]),n},{});return Object.keys(r).length>0?r:void 0}}},iterator:function(t){return new r(t)},length:function(t){return"number"==typeof t.delete?t.delete:"number"==typeof t.retain?t.retain:"string"==typeof t.insert?t.insert.length:1}};r.prototype.hasNext=function(){return this.peekLength()<1/0},r.prototype.next=function(t){t||(t=1/0);var e=this.ops[this.index];if(e){var n=this.offset,r=a.length(e);if(t>=r-n?(t=r-n,this.index+=1,this.offset=0):this.offset+=t,"number"==typeof e.delete)return{delete:t};var i={};return e.attributes&&(i.attributes=e.attributes),"number"==typeof e.retain?i.retain=t:"string"==typeof e.insert?i.insert=e.insert.substr(n,t):i.insert=e.insert,i}return{retain:1/0}},r.prototype.peek=function(){return this.ops[this.index]},r.prototype.peekLength=function(){return this.ops[this.index]?a.length(this.ops[this.index])-this.offset:1/0},r.prototype.peekType=function(){return this.ops[this.index]?"number"==typeof this.ops[this.index].delete?"delete":"number"==typeof this.ops[this.index].retain?"retain":"insert":"retain"},t.exports=a},function(t,n){var r=function(){"use strict";function t(t,e){return null!=e&&t instanceof e}function n(r,l,c,u,f){"object"==typeof l&&(c=l.depth,u=l.prototype,f=l.includeNonEnumerable,l=l.circular);var d=[],h=[],p=void 0!==e;return void 0===l&&(l=!0),void 0===c&&(c=1/0),function r(c,v){if(null===c)return null;if(0===v)return c;var g,m;if("object"!=typeof c)return c;if(t(c,o))g=new o;else if(t(c,a))g=new a;else if(t(c,s))g=new s(function(t,e){c.then(function(e){t(r(e,v-1))},function(t){e(r(t,v-1))})});else if(n.__isArray(c))g=[];else if(n.__isRegExp(c))g=new RegExp(c.source,i(c)),c.lastIndex&&(g.lastIndex=c.lastIndex);else if(n.__isDate(c))g=new Date(c.getTime());else{if(p&&e.isBuffer(c))return g=new e(c.length),c.copy(g),g;t(c,Error)?g=Object.create(c):void 0===u?(m=Object.getPrototypeOf(c),g=Object.create(m)):(g=Object.create(u),m=u)}if(l){var y=d.indexOf(c);if(-1!=y)return h[y];d.push(c),h.push(g)}for(var b in t(c,o)&&c.forEach(function(t,e){var n=r(e,v-1),i=r(t,v-1);g.set(n,i)}),t(c,a)&&c.forEach(function(t){var e=r(t,v-1);g.add(e)}),c){var w;m&&(w=Object.getOwnPropertyDescriptor(m,b)),w&&null==w.set||(g[b]=r(c[b],v-1))}if(Object.getOwnPropertySymbols){var _=Object.getOwnPropertySymbols(c);for(b=0;b<_.length;b++){var x=_[b];(!(q=Object.getOwnPropertyDescriptor(c,x))||q.enumerable||f)&&(g[x]=r(c[x],v-1),q.enumerable||Object.defineProperty(g,x,{enumerable:!1}))}}if(f){var k=Object.getOwnPropertyNames(c);for(b=0;b<k.length;b++){var q,O=k[b];(q=Object.getOwnPropertyDescriptor(c,O))&&q.enumerable||(g[O]=r(c[O],v-1),Object.defineProperty(g,O,{enumerable:!1}))}}return g}(r,c)}function r(t){return Object.prototype.toString.call(t)}function i(t){var e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),e}var o,a,s;try{o=Map}catch(t){o=function(){}}try{a=Set}catch(t){a=function(){}}try{s=Promise}catch(t){s=function(){}}return n.clonePrototype=function(t){if(null===t)return null;var e=function(){};return e.prototype=t,new e},n.__objToStr=r,n.__isDate=function(t){return"object"==typeof t&&"[object Date]"===r(t)},n.__isArray=function(t){return"object"==typeof t&&"[object Array]"===r(t)},n.__isRegExp=function(t){return"object"==typeof t&&"[object RegExp]"===r(t)},n.__getRegExpFlags=i,n}();"object"==typeof t&&t.exports&&(t.exports=r)},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t){return t instanceof f.default||t instanceof u.BlockEmbed}Object.defineProperty(e,"__esModule",{value:!0});var o=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),a=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),s=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},l=r(n(0)),c=r(n(8)),u=n(4),f=r(u),d=r(n(16)),h=r(n(13)),p=r(n(25)),v=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return r.emitter=n.emitter,Array.isArray(n.whitelist)&&(r.whitelist=n.whitelist.reduce(function(t,e){return t[e]=!0,t},{})),r.domNode.addEventListener("DOMNodeInserted",function(){}),r.optimize(),r.enable(),r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,l.default.Scroll),a(e,[{key:"batchStart",value:function(){this.batch=!0}},{key:"batchEnd",value:function(){this.batch=!1,this.optimize()}},{key:"deleteAt",value:function(t,n){var r=this.line(t),i=o(r,2),a=i[0],l=i[1],c=this.line(t+n),f=o(c,1)[0];if(s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"deleteAt",this).call(this,t,n),null!=f&&a!==f&&l>0){if(a instanceof u.BlockEmbed||f instanceof u.BlockEmbed)return void this.optimize();if(a instanceof h.default){var p=a.newlineIndex(a.length(),!0);if(p>-1&&(a=a.split(p+1))===f)return void this.optimize()}else if(f instanceof h.default){var v=f.newlineIndex(0);v>-1&&f.split(v+1)}var g=f.children.head instanceof d.default?null:f.children.head;a.moveChildren(f,g),a.remove()}this.optimize()}},{key:"enable",value:function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this.domNode.setAttribute("contenteditable",t)}},{key:"formatAt",value:function(t,n,r,i){
(null==this.whitelist||this.whitelist[r])&&(s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"formatAt",this).call(this,t,n,r,i),this.optimize())}},{key:"insertAt",value:function(t,n,r){if(null==r||null==this.whitelist||this.whitelist[n]){if(t>=this.length())if(null==r||null==l.default.query(n,l.default.Scope.BLOCK)){var i=l.default.create(this.statics.defaultChild);this.appendChild(i),null==r&&n.endsWith("\n")&&(n=n.slice(0,-1)),i.insertAt(0,n,r)}else{var o=l.default.create(n,r);this.appendChild(o)}else s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertAt",this).call(this,t,n,r);this.optimize()}}},{key:"insertBefore",value:function(t,n){if(t.statics.scope===l.default.Scope.INLINE_BLOT){var r=l.default.create(this.statics.defaultChild);r.appendChild(t),t=r}s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertBefore",this).call(this,t,n)}},{key:"leaf",value:function(t){return this.path(t).pop()||[null,-1]}},{key:"line",value:function(t){return t===this.length()?this.line(t-1):this.descendant(i,t)}},{key:"lines",value:function(){return function t(e,n,r){var o=[],a=r;return e.children.forEachAt(n,r,function(e,n,r){i(e)?o.push(e):e instanceof l.default.Container&&(o=o.concat(t(e,n,a))),a-=r}),o}(this,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,arguments.length>1&&void 0!==arguments[1]?arguments[1]:Number.MAX_VALUE)}},{key:"optimize",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};!0!==this.batch&&(s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"optimize",this).call(this,t,n),t.length>0&&this.emitter.emit(c.default.events.SCROLL_OPTIMIZE,t,n))}},{key:"path",value:function(t){return s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"path",this).call(this,t).slice(1)}},{key:"update",value:function(t){if(!0!==this.batch){var n=c.default.sources.USER;"string"==typeof t&&(n=t),Array.isArray(t)||(t=this.observer.takeRecords()),t.length>0&&this.emitter.emit(c.default.events.SCROLL_BEFORE_UPDATE,n,t),s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"update",this).call(this,t.concat([])),t.length>0&&this.emitter.emit(c.default.events.SCROLL_UPDATE,n,t)}}}]),e}();v.blotName="scroll",v.className="ql-editor",v.tagName="DIV",v.defaultChild="block",v.allowedChildren=[f.default,u.BlockEmbed,p.default],e.default=v},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function o(t,e){var n,r=t===C.keys.LEFT?"prefix":"suffix";return i(n={key:t,shiftKey:e,altKey:null},r,/^$/),i(n,"handler",function(n){var r=n.index;t===C.keys.RIGHT&&(r+=n.length+1);var i=this.quill.getLeaf(r);return!(p(i,1)[0]instanceof _.default.Embed&&(t===C.keys.LEFT?e?this.quill.setSelection(n.index-1,n.length+1,x.default.sources.USER):this.quill.setSelection(n.index-1,x.default.sources.USER):e?this.quill.setSelection(n.index,n.length+1,x.default.sources.USER):this.quill.setSelection(n.index+n.length+1,x.default.sources.USER),1))}),n}function a(t,e){if(!(0===t.index||this.quill.getLength()<=1)){var n=this.quill.getLine(t.index),r=p(n,1)[0],i={};if(0===e.offset){var o=this.quill.getLine(t.index-1),a=p(o,1)[0];if(null!=a&&a.length()>1){var s=r.formats(),l=this.quill.getFormat(t.index-1,1);i=w.default.attributes.diff(s,l)||{}}}var c=/[\uD800-\uDBFF][\uDC00-\uDFFF]$/.test(e.prefix)?2:1;this.quill.deleteText(t.index-c,c,x.default.sources.USER),Object.keys(i).length>0&&this.quill.formatLine(t.index-c,c,i,x.default.sources.USER),this.quill.focus()}}function s(t,e){var n=/^[\uD800-\uDBFF][\uDC00-\uDFFF]/.test(e.suffix)?2:1;if(!(t.index>=this.quill.getLength()-n)){var r={},i=0,o=this.quill.getLine(t.index),a=p(o,1)[0];if(e.offset>=a.length()-1){var s=this.quill.getLine(t.index+1),l=p(s,1)[0];if(l){var c=a.formats(),u=this.quill.getFormat(t.index,1);r=w.default.attributes.diff(c,u)||{},i=l.length()}}this.quill.deleteText(t.index,n,x.default.sources.USER),Object.keys(r).length>0&&this.quill.formatLine(t.index+i-1,n,r,x.default.sources.USER)}}function l(t){var e=this.quill.getLines(t),n={};if(e.length>1){var r=e[0].formats(),i=e[e.length-1].formats();n=w.default.attributes.diff(i,r)||{}}this.quill.deleteText(t,x.default.sources.USER),Object.keys(n).length>0&&this.quill.formatLine(t.index,1,n,x.default.sources.USER),this.quill.setSelection(t.index,x.default.sources.SILENT),this.quill.focus()}function c(t,e){var n=this;t.length>0&&this.quill.scroll.deleteAt(t.index,t.length);var r=Object.keys(e.format).reduce(function(t,n){return _.default.query(n,_.default.Scope.BLOCK)&&!Array.isArray(e.format[n])&&(t[n]=e.format[n]),t},{});this.quill.insertText(t.index,"\n",r,x.default.sources.USER),this.quill.setSelection(t.index+1,x.default.sources.SILENT),this.quill.focus(),Object.keys(e.format).forEach(function(t){null==r[t]&&(Array.isArray(e.format[t])||"link"!==t&&n.quill.format(t,e.format[t],x.default.sources.USER))})}function u(t){return{key:C.keys.TAB,shiftKey:!t,format:{"code-block":!0},handler:function(e){var n=_.default.query("code-block"),r=e.index,i=e.length,o=this.quill.scroll.descendant(n,r),a=p(o,2),s=a[0],l=a[1];if(null!=s){var c=this.quill.getIndex(s),u=s.newlineIndex(l,!0)+1,f=s.newlineIndex(c+l+i),d=s.domNode.textContent.slice(u,f).split("\n");l=0,d.forEach(function(e,o){t?(s.insertAt(u+l,n.TAB),l+=n.TAB.length,0===o?r+=n.TAB.length:i+=n.TAB.length):e.startsWith(n.TAB)&&(s.deleteAt(u+l,n.TAB.length),l-=n.TAB.length,0===o?r-=n.TAB.length:i-=n.TAB.length),l+=e.length+1}),this.quill.update(x.default.sources.USER),this.quill.setSelection(r,i,x.default.sources.SILENT)}}}}function f(t){return{key:t[0].toUpperCase(),shortKey:!0,handler:function(e,n){this.quill.format(t,!n.format[t],x.default.sources.USER)}}}function d(t){if("string"==typeof t||"number"==typeof t)return d({key:t});if("object"===(void 0===t?"undefined":h(t))&&(t=(0,g.default)(t,!1)),"string"==typeof t.key)if(null!=C.keys[t.key.toUpperCase()])t.key=C.keys[t.key.toUpperCase()];else{if(1!==t.key.length)return null;t.key=t.key.toUpperCase().charCodeAt(0)}return t.shortKey&&(t[A]=t.shortKey,delete t.shortKey),t}Object.defineProperty(e,"__esModule",{value:!0}),e.SHORTKEY=e.default=void 0;var h="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},p=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),v=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),g=r(n(21)),m=r(n(11)),y=r(n(3)),b=r(n(2)),w=r(n(20)),_=r(n(0)),x=r(n(5)),k=r(n(10)),q=r(n(9)),O=(0,k.default)("quill:keyboard"),A=/Mac/i.test(navigator.platform)?"metaKey":"ctrlKey",C=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.bindings={},Object.keys(r.options.bindings).forEach(function(e){("list autofill"!==e||null==t.scroll.whitelist||t.scroll.whitelist.list)&&r.options.bindings[e]&&r.addBinding(r.options.bindings[e])}),r.addBinding({key:e.keys.ENTER,shiftKey:null},c),r.addBinding({key:e.keys.ENTER,metaKey:null,ctrlKey:null,altKey:null},function(){}),/Firefox/i.test(navigator.userAgent)?(r.addBinding({key:e.keys.BACKSPACE},{collapsed:!0},a),r.addBinding({key:e.keys.DELETE},{collapsed:!0},s)):(r.addBinding({key:e.keys.BACKSPACE},{collapsed:!0,prefix:/^.?$/},a),r.addBinding({key:e.keys.DELETE},{collapsed:!0,suffix:/^.?$/},s)),r.addBinding({key:e.keys.BACKSPACE},{collapsed:!1},l),r.addBinding({key:e.keys.DELETE},{collapsed:!1},l),r.addBinding({key:e.keys.BACKSPACE,altKey:null,ctrlKey:null,metaKey:null,shiftKey:null},{collapsed:!0,offset:0},a),r.listen(),r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,q.default),v(e,null,[{key:"match",value:function(t,e){return e=d(e),!["altKey","ctrlKey","metaKey","shiftKey"].some(function(n){return!!e[n]!==t[n]&&null!==e[n]})&&e.key===(t.which||t.keyCode)}}]),v(e,[{key:"addBinding",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=d(t);if(null==r||null==r.key)return O.warn("Attempted to add invalid keyboard binding",r);"function"==typeof e&&(e={handler:e}),"function"==typeof n&&(n={handler:n}),r=(0,y.default)(r,e,n),this.bindings[r.key]=this.bindings[r.key]||[],this.bindings[r.key].push(r)}},{key:"listen",value:function(){var t=this;this.quill.root.addEventListener("keydown",function(n){if(!n.defaultPrevented){var r=n.which||n.keyCode,i=(t.bindings[r]||[]).filter(function(t){return e.match(n,t)});if(0!==i.length){var o=t.quill.getSelection();if(null!=o&&t.quill.hasFocus()){var a=t.quill.getLine(o.index),s=p(a,2),l=s[0],c=s[1],u=t.quill.getLeaf(o.index),f=p(u,2),d=f[0],v=f[1],g=0===o.length?[d,v]:t.quill.getLeaf(o.index+o.length),y=p(g,2),b=y[0],w=y[1],x=d instanceof _.default.Text?d.value().slice(0,v):"",k=b instanceof _.default.Text?b.value().slice(w):"",q={collapsed:0===o.length,empty:0===o.length&&l.length()<=1,format:t.quill.getFormat(o),offset:c,prefix:x,suffix:k};i.some(function(e){if(null!=e.collapsed&&e.collapsed!==q.collapsed)return!1;if(null!=e.empty&&e.empty!==q.empty)return!1;if(null!=e.offset&&e.offset!==q.offset)return!1;if(Array.isArray(e.format)){if(e.format.every(function(t){return null==q.format[t]}))return!1}else if("object"===h(e.format)&&!Object.keys(e.format).every(function(t){return!0===e.format[t]?null!=q.format[t]:!1===e.format[t]?null==q.format[t]:(0,m.default)(e.format[t],q.format[t])}))return!1;return!(null!=e.prefix&&!e.prefix.test(q.prefix)||null!=e.suffix&&!e.suffix.test(q.suffix)||!0===e.handler.call(t,o,q))})&&n.preventDefault()}}}})}}]),e}();C.keys={BACKSPACE:8,TAB:9,ENTER:13,ESCAPE:27,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46},C.DEFAULTS={bindings:{bold:f("bold"),italic:f("italic"),underline:f("underline"),indent:{key:C.keys.TAB,format:["blockquote","indent","list"],handler:function(t,e){if(e.collapsed&&0!==e.offset)return!0;this.quill.format("indent","+1",x.default.sources.USER)}},outdent:{key:C.keys.TAB,shiftKey:!0,format:["blockquote","indent","list"],handler:function(t,e){if(e.collapsed&&0!==e.offset)return!0;this.quill.format("indent","-1",x.default.sources.USER)}},"outdent backspace":{key:C.keys.BACKSPACE,collapsed:!0,shiftKey:null,metaKey:null,ctrlKey:null,altKey:null,format:["indent","list"],offset:0,handler:function(t,e){null!=e.format.indent?this.quill.format("indent","-1",x.default.sources.USER):null!=e.format.list&&this.quill.format("list",!1,x.default.sources.USER)}},"indent code-block":u(!0),"outdent code-block":u(!1),"remove tab":{key:C.keys.TAB,shiftKey:!0,collapsed:!0,prefix:/\t$/,handler:function(t){this.quill.deleteText(t.index-1,1,x.default.sources.USER)}},tab:{key:C.keys.TAB,handler:function(t){this.quill.history.cutoff();var e=(new b.default).retain(t.index).delete(t.length).insert("\t");this.quill.updateContents(e,x.default.sources.USER),this.quill.history.cutoff(),this.quill.setSelection(t.index+1,x.default.sources.SILENT)}},"list empty enter":{key:C.keys.ENTER,collapsed:!0,format:["list"],empty:!0,handler:function(t,e){this.quill.format("list",!1,x.default.sources.USER),e.format.indent&&this.quill.format("indent",!1,x.default.sources.USER)}},"checklist enter":{key:C.keys.ENTER,collapsed:!0,format:{list:"checked"},handler:function(t){var e=this.quill.getLine(t.index),n=p(e,2),r=n[0],i=n[1],o=(0,y.default)({},r.formats(),{list:"checked"}),a=(new b.default).retain(t.index).insert("\n",o).retain(r.length()-i-1).retain(1,{list:"unchecked"});this.quill.updateContents(a,x.default.sources.USER),this.quill.setSelection(t.index+1,x.default.sources.SILENT),this.quill.scrollIntoView()}},"header enter":{key:C.keys.ENTER,collapsed:!0,format:["header"],suffix:/^$/,handler:function(t,e){var n=this.quill.getLine(t.index),r=p(n,2),i=r[0],o=r[1],a=(new b.default).retain(t.index).insert("\n",e.format).retain(i.length()-o-1).retain(1,{header:null});this.quill.updateContents(a,x.default.sources.USER),this.quill.setSelection(t.index+1,x.default.sources.SILENT),this.quill.scrollIntoView()}},"list autofill":{key:" ",collapsed:!0,format:{list:!1},prefix:/^\s*?(\d+\.|-|\*|\[ ?\]|\[x\])$/,handler:function(t,e){var n=e.prefix.length,r=this.quill.getLine(t.index),i=p(r,2),o=i[0],a=i[1];if(a>n)return!0;var s=void 0;switch(e.prefix.trim()){case"[]":case"[ ]":s="unchecked";break;case"[x]":s="checked";break;case"-":case"*":s="bullet";break;default:s="ordered"}this.quill.insertText(t.index," ",x.default.sources.USER),this.quill.history.cutoff();var l=(new b.default).retain(t.index-a).delete(n+1).retain(o.length()-2-a).retain(1,{list:s});this.quill.updateContents(l,x.default.sources.USER),this.quill.history.cutoff(),this.quill.setSelection(t.index-n,x.default.sources.SILENT)}},"code exit":{key:C.keys.ENTER,collapsed:!0,format:["code-block"],prefix:/\n\n$/,suffix:/^\s+$/,handler:function(t){var e=this.quill.getLine(t.index),n=p(e,2),r=n[0],i=n[1],o=(new b.default).retain(t.index+r.length()-i-2).retain(1,{"code-block":null}).delete(1);this.quill.updateContents(o,x.default.sources.USER)}},"embed left":o(C.keys.LEFT,!1),"embed left shift":o(C.keys.LEFT,!0),"embed right":o(C.keys.RIGHT,!1),"embed right shift":o(C.keys.RIGHT,!0)}},e.default=C,e.SHORTKEY=A},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),o=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},a=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),s=r(n(0)),l=r(n(7)),c=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return r.selection=n,r.textNode=document.createTextNode(e.CONTENTS),r.domNode.appendChild(r.textNode),r._length=0,r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,s.default.Embed),a(e,null,[{key:"value",value:function(){}}]),a(e,[{key:"detach",value:function(){null!=this.parent&&this.parent.removeChild(this)}},{key:"format",value:function(t,n){if(0!==this._length)return o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"format",this).call(this,t,n);for(var r=this,i=0;null!=r&&r.statics.scope!==s.default.Scope.BLOCK_BLOT;)i+=r.offset(r.parent),r=r.parent;null!=r&&(this._length=e.CONTENTS.length,r.optimize(),r.formatAt(i,e.CONTENTS.length,t,n),this._length=0)}},{key:"index",value:function(t,n){return t===this.textNode?0:o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"index",this).call(this,t,n)}},{key:"length",value:function(){return this._length}},{key:"position",value:function(){return[this.textNode,this.textNode.data.length]}},{key:"remove",value:function(){o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"remove",this).call(this),this.parent=null}},{key:"restore",value:function(){if(!this.selection.composing&&null!=this.parent){var t=this.textNode,n=this.selection.getNativeRange(),r=void 0,o=void 0,a=void 0;if(null!=n&&n.start.node===t&&n.end.node===t){var c=[t,n.start.offset,n.end.offset];r=c[0],o=c[1],a=c[2]}for(;null!=this.domNode.lastChild&&this.domNode.lastChild!==this.textNode;)this.domNode.parentNode.insertBefore(this.domNode.lastChild,this.domNode);if(this.textNode.data!==e.CONTENTS){var u=this.textNode.data.split(e.CONTENTS).join("");this.next instanceof l.default?(r=this.next.domNode,this.next.insertAt(0,u),this.textNode.data=e.CONTENTS):(this.textNode.data=u,this.parent.insertBefore(s.default.create(this.textNode),this),this.textNode=document.createTextNode(e.CONTENTS),this.domNode.appendChild(this.textNode))}if(this.remove(),null!=o){var f=[o,a].map(function(t){return Math.max(0,Math.min(r.data.length,t-1))}),d=i(f,2);return o=d[0],a=d[1],{startNode:r,startOffset:o,endNode:r,endOffset:a}}}}},{key:"update",value:function(t,e){var n=this;if(t.some(function(t){return"characterData"===t.type&&t.target===n.textNode})){var r=this.restore();r&&(e.range=r)}}},{key:"value",value:function(){return""}}]),e}();c.blotName="cursor",c.className="ql-cursor",c.tagName="span",c.CONTENTS="\ufeff",e.default=c},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=r(n(0)),o=n(4),a=r(o),s=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,i.default.Container),e}();s.allowedChildren=[a.default,o.BlockEmbed,s],e.default=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ColorStyle=e.ColorClass=e.ColorAttributor=void 0;var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(0),a=(r=o)&&r.__esModule?r:{default:r},s=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,a.default.Attributor.Style),i(e,[{key:"value",value:function(t){var n=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"value",this).call(this,t);return n.startsWith("rgb(")?(n=n.replace(/^[^\d]+/,"").replace(/[^\d]+$/,""),"#"+n.split(",").map(function(t){return("00"+parseInt(t).toString(16)).slice(-2)}).join("")):n}}]),e}(),l=new a.default.Attributor.Class("color","ql-color",{scope:a.default.Scope.INLINE}),c=new s("color","color",{scope:a.default.Scope.INLINE});e.ColorAttributor=s,e.ColorClass=l,e.ColorStyle=c},function(t,e,n){"use strict";function r(t,e){var n=document.createElement("a");n.href=t;var r=n.href.slice(0,n.href.indexOf(":"));return e.indexOf(r)>-1}Object.defineProperty(e,"__esModule",{value:!0}),e.sanitize=e.default=void 0;var i,o=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},s=n(6),l=(i=s)&&i.__esModule?i:{default:i},c=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,l.default),o(e,[{key:"format",value:function(t,n){if(t!==this.statics.blotName||!n)return a(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"format",this).call(this,t,n);n=this.constructor.sanitize(n),this.domNode.setAttribute("href",n)}}],[{key:"create",value:function(t){var n=a(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this,t);return t=this.sanitize(t),n.setAttribute("href",t),n.setAttribute("target","_blank"),n}},{key:"formats",value:function(t){return t.getAttribute("href")}},{key:"sanitize",value:function(t){return r(t,this.PROTOCOL_WHITELIST)?t:this.SANITIZED_URL}}]),e}();c.blotName="link",c.tagName="A",c.SANITIZED_URL="about:blank",c.PROTOCOL_WHITELIST=["http","https","mailto","tel"],e.default=c,e.sanitize=r},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){t.setAttribute(e,!("true"===t.getAttribute(e)))}Object.defineProperty(e,"__esModule",{value:!0});var o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),s=r(n(23)),l=r(n(107)),c=0,u=function(){function t(e){var n=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.select=e,this.container=document.createElement("span"),this.buildPicker(),this.select.style.display="none",this.select.parentNode.insertBefore(this.container,this.select),this.label.addEventListener("mousedown",function(){n.togglePicker()}),this.label.addEventListener("keydown",function(t){switch(t.keyCode){case s.default.keys.ENTER:n.togglePicker();break;case s.default.keys.ESCAPE:n.escape(),t.preventDefault()}}),this.select.addEventListener("change",this.update.bind(this))}return a(t,[{key:"togglePicker",value:function(){this.container.classList.toggle("ql-expanded"),i(this.label,"aria-expanded"),i(this.options,"aria-hidden")}},{key:"buildItem",value:function(t){var e=this,n=document.createElement("span");return n.tabIndex="0",n.setAttribute("role","button"),n.classList.add("ql-picker-item"),t.hasAttribute("value")&&n.setAttribute("data-value",t.getAttribute("value")),t.textContent&&n.setAttribute("data-label",t.textContent),n.addEventListener("click",function(){e.selectItem(n,!0)}),n.addEventListener("keydown",function(t){switch(t.keyCode){case s.default.keys.ENTER:e.selectItem(n,!0),t.preventDefault();break;case s.default.keys.ESCAPE:e.escape(),t.preventDefault()}}),n}},{key:"buildLabel",value:function(){var t=document.createElement("span");return t.classList.add("ql-picker-label"),t.innerHTML=l.default,t.tabIndex="0",t.setAttribute("role","button"),t.setAttribute("aria-expanded","false"),this.container.appendChild(t),t}},{key:"buildOptions",value:function(){var t=this,e=document.createElement("span");e.classList.add("ql-picker-options"),e.setAttribute("aria-hidden","true"),e.tabIndex="-1",e.id="ql-picker-options-"+c,c+=1,this.label.setAttribute("aria-controls",e.id),this.options=e,[].slice.call(this.select.options).forEach(function(n){var r=t.buildItem(n);e.appendChild(r),!0===n.selected&&t.selectItem(r)}),this.container.appendChild(e)}},{key:"buildPicker",value:function(){var t=this;[].slice.call(this.select.attributes).forEach(function(e){t.container.setAttribute(e.name,e.value)}),this.container.classList.add("ql-picker"),this.label=this.buildLabel(),this.buildOptions()}},{key:"escape",value:function(){var t=this;this.close(),setTimeout(function(){return t.label.focus()},1)}},{key:"close",value:function(){this.container.classList.remove("ql-expanded"),this.label.setAttribute("aria-expanded","false"),this.options.setAttribute("aria-hidden","true")}},{key:"selectItem",value:function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=this.container.querySelector(".ql-selected");if(t!==n&&(null!=n&&n.classList.remove("ql-selected"),null!=t&&(t.classList.add("ql-selected"),this.select.selectedIndex=[].indexOf.call(t.parentNode.children,t),t.hasAttribute("data-value")?this.label.setAttribute("data-value",t.getAttribute("data-value")):this.label.removeAttribute("data-value"),t.hasAttribute("data-label")?this.label.setAttribute("data-label",t.getAttribute("data-label")):this.label.removeAttribute("data-label"),e))){if("function"==typeof Event)this.select.dispatchEvent(new Event("change"));else if("object"===("undefined"==typeof Event?"undefined":o(Event))){var r=document.createEvent("Event");r.initEvent("change",!0,!0),this.select.dispatchEvent(r)}this.close()}}},{key:"update",value:function(){var t=void 0;if(this.select.selectedIndex>-1){var e=this.container.querySelector(".ql-picker-options").children[this.select.selectedIndex];t=this.select.options[this.select.selectedIndex],this.selectItem(e)}else this.selectItem(null);var n=null!=t&&t!==this.select.querySelector("option[selected]");this.label.classList.toggle("ql-active",n)}}]),t}();e.default=u},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=r(n(0)),o=r(n(5)),a=n(4),s=r(a),l=r(n(16)),c=r(n(25)),u=r(n(24)),f=r(n(35)),d=r(n(6)),h=r(n(22)),p=r(n(7)),v=r(n(55)),g=r(n(42)),m=r(n(23));o.default.register({"blots/block":s.default,"blots/block/embed":a.BlockEmbed,"blots/break":l.default,"blots/container":c.default,"blots/cursor":u.default,"blots/embed":f.default,"blots/inline":d.default,"blots/scroll":h.default,"blots/text":p.default,"modules/clipboard":v.default,"modules/history":g.default,"modules/keyboard":m.default}),i.default.register(s.default,l.default,u.default,d.default,h.default,p.default),e.default=o.default},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=function(){function t(t){this.domNode=t,this.domNode[r.DATA_KEY]={blot:this}}return Object.defineProperty(t.prototype,"statics",{get:function(){return this.constructor},enumerable:!0,configurable:!0}),t.create=function(t){if(null==this.tagName)throw new r.ParchmentError("Blot definition missing tagName");var e;return Array.isArray(this.tagName)?("string"==typeof t&&(t=t.toUpperCase(),parseInt(t).toString()===t&&(t=parseInt(t))),e="number"==typeof t?document.createElement(this.tagName[t-1]):this.tagName.indexOf(t)>-1?document.createElement(t):document.createElement(this.tagName[0])):e=document.createElement(this.tagName),this.className&&e.classList.add(this.className),e},t.prototype.attach=function(){null!=this.parent&&(this.scroll=this.parent.scroll)},t.prototype.clone=function(){var t=this.domNode.cloneNode(!1);return r.create(t)},t.prototype.detach=function(){null!=this.parent&&this.parent.removeChild(this),delete this.domNode[r.DATA_KEY]},t.prototype.deleteAt=function(t,e){this.isolate(t,e).remove()},t.prototype.formatAt=function(t,e,n,i){var o=this.isolate(t,e);if(null!=r.query(n,r.Scope.BLOT)&&i)o.wrap(n,i);else if(null!=r.query(n,r.Scope.ATTRIBUTE)){var a=r.create(this.statics.scope);o.wrap(a),a.format(n,i)}},t.prototype.insertAt=function(t,e,n){var i=null==n?r.create("text",e):r.create(e,n),o=this.split(t);this.parent.insertBefore(i,o)},t.prototype.insertInto=function(t,e){void 0===e&&(e=null),null!=this.parent&&this.parent.children.remove(this);var n=null;t.children.insertBefore(this,e),null!=e&&(n=e.domNode),this.domNode.parentNode==t.domNode&&this.domNode.nextSibling==n||t.domNode.insertBefore(this.domNode,n),this.parent=t,this.attach()},t.prototype.isolate=function(t,e){var n=this.split(t);return n.split(e),n},t.prototype.length=function(){return 1},t.prototype.offset=function(t){return void 0===t&&(t=this.parent),null==this.parent||this==t?0:this.parent.children.offset(this)+this.parent.offset(t)},t.prototype.optimize=function(t){null!=this.domNode[r.DATA_KEY]&&delete this.domNode[r.DATA_KEY].mutations},t.prototype.remove=function(){null!=this.domNode.parentNode&&this.domNode.parentNode.removeChild(this.domNode),this.detach()},t.prototype.replace=function(t){null!=t.parent&&(t.parent.insertBefore(this,t.next),t.remove())},t.prototype.replaceWith=function(t,e){var n="string"==typeof t?r.create(t,e):t;return n.replace(this),n},t.prototype.split=function(t,e){return 0===t?this:this.next},t.prototype.update=function(t,e){},t.prototype.wrap=function(t,e){var n="string"==typeof t?r.create(t,e):t;return null!=this.parent&&this.parent.insertBefore(n,this.next),n.appendChild(this),n},t.blotName="abstract",t}();e.default=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(12),i=n(32),o=n(33),a=n(1),s=function(){function t(t){this.attributes={},this.domNode=t,this.build()}return t.prototype.attribute=function(t,e){e?t.add(this.domNode,e)&&(null!=t.value(this.domNode)?this.attributes[t.attrName]=t:delete this.attributes[t.attrName]):(t.remove(this.domNode),delete this.attributes[t.attrName])},t.prototype.build=function(){var t=this;this.attributes={}
;var e=r.default.keys(this.domNode),n=i.default.keys(this.domNode),s=o.default.keys(this.domNode);e.concat(n).concat(s).forEach(function(e){var n=a.query(e,a.Scope.ATTRIBUTE);n instanceof r.default&&(t.attributes[n.attrName]=n)})},t.prototype.copy=function(t){var e=this;Object.keys(this.attributes).forEach(function(n){var r=e.attributes[n].value(e.domNode);t.format(n,r)})},t.prototype.move=function(t){var e=this;this.copy(t),Object.keys(this.attributes).forEach(function(t){e.attributes[t].remove(e.domNode)}),this.attributes={}},t.prototype.values=function(){var t=this;return Object.keys(this.attributes).reduce(function(e,n){return e[n]=t.attributes[n].value(t.domNode),e},{})},t}();e.default=s},function(t,e,n){"use strict";function r(t,e){return(t.getAttribute("class")||"").split(/\s+/).filter(function(t){return 0===t.indexOf(e+"-")})}var i,o=this&&this.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var a=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.keys=function(t){return(t.getAttribute("class")||"").split(/\s+/).map(function(t){return t.split("-").slice(0,-1).join("-")})},e.prototype.add=function(t,e){return!!this.canAdd(t,e)&&(this.remove(t),t.classList.add(this.keyName+"-"+e),!0)},e.prototype.remove=function(t){r(t,this.keyName).forEach(function(e){t.classList.remove(e)}),0===t.classList.length&&t.removeAttribute("class")},e.prototype.value=function(t){var e=(r(t,this.keyName)[0]||"").slice(this.keyName.length+1);return this.canAdd(t,e)?e:""},e}(n(12).default);e.default=a},function(t,e,n){"use strict";function r(t){var e=t.split("-"),n=e.slice(1).map(function(t){return t[0].toUpperCase()+t.slice(1)}).join("");return e[0]+n}var i,o=this&&this.__extends||(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}i(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var a=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.keys=function(t){return(t.getAttribute("style")||"").split(";").map(function(t){return t.split(":")[0].trim()})},e.prototype.add=function(t,e){return!!this.canAdd(t,e)&&(t.style[r(this.keyName)]=e,!0)},e.prototype.remove=function(t){t.style[r(this.keyName)]="",t.getAttribute("style")||t.removeAttribute("style")},e.prototype.value=function(t){var e=t.style[r(this.keyName)];return this.canAdd(t,e)?e:""},e}(n(12).default);e.default=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i=function(){function t(e,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.quill=e,this.options=n,this.modules={}}return r(t,[{key:"init",value:function(){var t=this;Object.keys(this.options.modules).forEach(function(e){null==t.modules[e]&&t.addModule(e)})}},{key:"addModule",value:function(t){var e=this.quill.constructor.import("modules/"+t);return this.modules[t]=new e(this.quill,this.options.modules[t]||{}),this.modules[t]}}]),t}();i.DEFAULTS={modules:{}},i.themes={default:i},e.default=i},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=r(n(0)),a=r(n(7)),s="\ufeff",l=function(t){function e(t){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var n=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return n.contentNode=document.createElement("span"),n.contentNode.setAttribute("contenteditable",!1),[].slice.call(n.domNode.childNodes).forEach(function(t){n.contentNode.appendChild(t)}),n.leftGuard=document.createTextNode(s),n.rightGuard=document.createTextNode(s),n.domNode.appendChild(n.leftGuard),n.domNode.appendChild(n.contentNode),n.domNode.appendChild(n.rightGuard),n}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,o.default.Embed),i(e,[{key:"index",value:function(t,n){return t===this.leftGuard?0:t===this.rightGuard?1:function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"index",this).call(this,t,n)}},{key:"restore",value:function(t){var e=void 0,n=void 0,r=t.data.split(s).join("");if(t===this.leftGuard)if(this.prev instanceof a.default){var i=this.prev.length();this.prev.insertAt(i,r),e={startNode:this.prev.domNode,startOffset:i+r.length}}else n=document.createTextNode(r),this.parent.insertBefore(o.default.create(n),this),e={startNode:n,startOffset:r.length};else t===this.rightGuard&&(this.next instanceof a.default?(this.next.insertAt(0,r),e={startNode:this.next.domNode,startOffset:r.length}):(n=document.createTextNode(r),this.parent.insertBefore(o.default.create(n),this.next),e={startNode:n,startOffset:r.length}));return t.data=s,e}},{key:"update",value:function(t,e){var n=this;t.forEach(function(t){if("characterData"===t.type&&(t.target===n.leftGuard||t.target===n.rightGuard)){var r=n.restore(t.target);r&&(e.range=r)}})}}]),e}();e.default=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AlignStyle=e.AlignClass=e.AlignAttribute=void 0;var r,i=n(0),o=(r=i)&&r.__esModule?r:{default:r},a={scope:o.default.Scope.BLOCK,whitelist:["right","center","justify"]},s=new o.default.Attributor.Attribute("align","align",a),l=new o.default.Attributor.Class("align","ql-align",a),c=new o.default.Attributor.Style("align","text-align",a);e.AlignAttribute=s,e.AlignClass=l,e.AlignStyle=c},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.BackgroundStyle=e.BackgroundClass=void 0;var r,i=n(0),o=(r=i)&&r.__esModule?r:{default:r},a=n(26),s=new o.default.Attributor.Class("background","ql-bg",{scope:o.default.Scope.INLINE}),l=new a.ColorAttributor("background","background-color",{scope:o.default.Scope.INLINE});e.BackgroundClass=s,e.BackgroundStyle=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DirectionStyle=e.DirectionClass=e.DirectionAttribute=void 0;var r,i=n(0),o=(r=i)&&r.__esModule?r:{default:r},a={scope:o.default.Scope.BLOCK,whitelist:["rtl"]},s=new o.default.Attributor.Attribute("direction","dir",a),l=new o.default.Attributor.Class("direction","ql-direction",a),c=new o.default.Attributor.Style("direction","direction",a);e.DirectionAttribute=s,e.DirectionClass=l,e.DirectionStyle=c},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.FontClass=e.FontStyle=void 0;var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(0),a=(r=o)&&r.__esModule?r:{default:r},s={scope:a.default.Scope.INLINE,whitelist:["serif","monospace"]},l=new a.default.Attributor.Class("font","ql-font",s),c=new(function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,a.default.Attributor.Style),i(e,[{key:"value",value:function(t){return function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"value",this).call(this,t).replace(/["']/g,"")}}]),e}())("font","font-family",s);e.FontStyle=c,e.FontClass=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SizeStyle=e.SizeClass=void 0;var r,i=n(0),o=(r=i)&&r.__esModule?r:{default:r},a=new o.default.Attributor.Class("size","ql-size",{scope:o.default.Scope.INLINE,whitelist:["small","large","huge"]}),s=new o.default.Attributor.Style("size","font-size",{scope:o.default.Scope.INLINE,whitelist:["10px","18px","32px"]});e.SizeClass=a,e.SizeStyle=s},function(t,e,n){"use strict";t.exports={align:{"":n(76),center:n(77),right:n(78),justify:n(79)},background:n(80),blockquote:n(81),bold:n(82),clean:n(83),code:n(58),"code-block":n(58),color:n(84),direction:{"":n(85),rtl:n(86)},float:{center:n(87),full:n(88),left:n(89),right:n(90)},formula:n(91),header:{1:n(92),2:n(93)},italic:n(94),image:n(95),indent:{"+1":n(96),"-1":n(97)},link:n(98),list:{ordered:n(99),bullet:n(100),check:n(101)},script:{sub:n(102),super:n(103)},strike:n(104),underline:n(105),video:n(106)}},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t){var e=t.reduce(function(t,e){return t+=e.delete||0},0),n=t.length()-e;return function(t){var e=t.ops[t.ops.length-1];return null!=e&&(null!=e.insert?"string"==typeof e.insert&&e.insert.endsWith("\n"):null!=e.attributes&&Object.keys(e.attributes).some(function(t){return null!=a.default.query(t,a.default.Scope.BLOCK)}))}(t)&&(n-=1),n}Object.defineProperty(e,"__esModule",{value:!0}),e.getLastChangeIndex=e.default=void 0;var o=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),a=r(n(0)),s=r(n(5)),l=r(n(9)),c=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.lastRecorded=0,r.ignoreChange=!1,r.clear(),r.quill.on(s.default.events.EDITOR_CHANGE,function(t,e,n,i){t!==s.default.events.TEXT_CHANGE||r.ignoreChange||(r.options.userOnly&&i!==s.default.sources.USER?r.transform(e):r.record(e,n))}),r.quill.keyboard.addBinding({key:"Z",shortKey:!0},r.undo.bind(r)),r.quill.keyboard.addBinding({key:"Z",shortKey:!0,shiftKey:!0},r.redo.bind(r)),/Win/i.test(navigator.platform)&&r.quill.keyboard.addBinding({key:"Y",shortKey:!0},r.redo.bind(r)),r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,l.default),o(e,[{key:"change",value:function(t,e){if(0!==this.stack[t].length){var n=this.stack[t].pop();this.stack[e].push(n),this.lastRecorded=0,this.ignoreChange=!0,this.quill.updateContents(n[t],s.default.sources.USER),this.ignoreChange=!1;var r=i(n[t]);this.quill.setSelection(r)}}},{key:"clear",value:function(){this.stack={undo:[],redo:[]}}},{key:"cutoff",value:function(){this.lastRecorded=0}},{key:"record",value:function(t,e){if(0!==t.ops.length){this.stack.redo=[];var n=this.quill.getContents().diff(e),r=Date.now();if(this.lastRecorded+this.options.delay>r&&this.stack.undo.length>0){var i=this.stack.undo.pop();n=n.compose(i.undo),t=i.redo.compose(t)}else this.lastRecorded=r;this.stack.undo.push({redo:t,undo:n}),this.stack.undo.length>this.options.maxStack&&this.stack.undo.shift()}}},{key:"redo",value:function(){this.change("redo","undo")}},{key:"transform",value:function(t){this.stack.undo.forEach(function(e){e.undo=t.transform(e.undo,!0),e.redo=t.transform(e.redo,!0)}),this.stack.redo.forEach(function(e){e.undo=t.transform(e.undo,!0),e.redo=t.transform(e.redo,!0)})}},{key:"undo",value:function(){this.change("undo","redo")}}]),e}();c.DEFAULTS={delay:1e3,maxStack:100,userOnly:!1},e.default=c,e.getLastChangeIndex=i},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function s(t,e){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];e.forEach(function(e){var r=document.createElement("option");e===n?r.setAttribute("selected","selected"):r.setAttribute("value",e),t.appendChild(r)})}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.BaseTooltip=void 0;var l=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),c=r(n(3)),u=r(n(2)),f=r(n(8)),d=r(n(23)),h=r(n(34)),p=r(n(59)),v=r(n(60)),g=r(n(28)),m=r(n(61)),y=[!1,"center","right","justify"],b=["#000000","#e60000","#ff9900","#ffff00","#008a00","#0066cc","#9933ff","#ffffff","#facccc","#ffebcc","#ffffcc","#cce8cc","#cce0f5","#ebd6ff","#bbbbbb","#f06666","#ffc266","#ffff66","#66b966","#66a3e0","#c285ff","#888888","#a10000","#b26b00","#b2b200","#006100","#0047b2","#6b24b2","#444444","#5c0000","#663d00","#666600","#003700","#002966","#3d1466"],w=[!1,"serif","monospace"],_=["1","2","3",!1],x=["small",!1,"large","huge"],k=function(t){function e(t,n){i(this,e);var r=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return t.emitter.listenDOM("click",document.body,function e(n){if(!document.body.contains(t.root))return document.body.removeEventListener("click",e);null==r.tooltip||r.tooltip.root.contains(n.target)||document.activeElement===r.tooltip.textbox||r.quill.hasFocus()||r.tooltip.hide(),null!=r.pickers&&r.pickers.forEach(function(t){t.container.contains(n.target)||t.close()})}),r}return a(e,h.default),l(e,[{key:"addModule",value:function(t){var n=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"addModule",this).call(this,t);return"toolbar"===t&&this.extendToolbar(n),n}},{key:"buildButtons",value:function(t,e){t.forEach(function(t){(t.getAttribute("class")||"").split(/\s+/).forEach(function(n){if(n.startsWith("ql-")&&(n=n.slice("ql-".length),null!=e[n]))if("direction"===n)t.innerHTML=e[n][""]+e[n].rtl;else if("string"==typeof e[n])t.innerHTML=e[n];else{var r=t.value||"";null!=r&&e[n][r]&&(t.innerHTML=e[n][r])}})})}},{key:"buildPickers",value:function(t,e){var n=this;this.pickers=t.map(function(t){if(t.classList.contains("ql-align"))return null==t.querySelector("option")&&s(t,y),new v.default(t,e.align);if(t.classList.contains("ql-background")||t.classList.contains("ql-color")){var n=t.classList.contains("ql-background")?"background":"color";return null==t.querySelector("option")&&s(t,b,"background"===n?"#ffffff":"#000000"),new p.default(t,e[n])}return null==t.querySelector("option")&&(t.classList.contains("ql-font")?s(t,w):t.classList.contains("ql-header")?s(t,_):t.classList.contains("ql-size")&&s(t,x)),new g.default(t)}),this.quill.on(f.default.events.EDITOR_CHANGE,function(){n.pickers.forEach(function(t){t.update()})})}}]),e}();k.DEFAULTS=(0,c.default)(!0,{},h.default.DEFAULTS,{modules:{toolbar:{handlers:{formula:function(){this.quill.theme.tooltip.edit("formula")},image:function(){var t=this,e=this.container.querySelector("input.ql-image[type=file]");null==e&&((e=document.createElement("input")).setAttribute("type","file"),e.setAttribute("accept","image/png, image/gif, image/jpeg, image/bmp, image/x-icon"),e.classList.add("ql-image"),e.addEventListener("change",function(){if(null!=e.files&&null!=e.files[0]){var n=new FileReader;n.onload=function(n){var r=t.quill.getSelection(!0);t.quill.updateContents((new u.default).retain(r.index).delete(r.length).insert({image:n.target.result}),f.default.sources.USER),t.quill.setSelection(r.index+1,f.default.sources.SILENT),e.value=""},n.readAsDataURL(e.files[0])}}),this.container.appendChild(e)),e.click()},video:function(){this.quill.theme.tooltip.edit("video")}}}}});var q=function(t){function e(t,n){i(this,e);var r=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.textbox=r.root.querySelector('input[type="text"]'),r.listen(),r}return a(e,m.default),l(e,[{key:"listen",value:function(){var t=this;this.textbox.addEventListener("keydown",function(e){d.default.match(e,"enter")?(t.save(),e.preventDefault()):d.default.match(e,"escape")&&(t.cancel(),e.preventDefault())})}},{key:"cancel",value:function(){this.hide()}},{key:"edit",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"link",e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;this.root.classList.remove("ql-hidden"),this.root.classList.add("ql-editing"),null!=e?this.textbox.value=e:t!==this.root.getAttribute("data-mode")&&(this.textbox.value=""),this.position(this.quill.getBounds(this.quill.selection.savedRange)),this.textbox.select(),this.textbox.setAttribute("placeholder",this.textbox.getAttribute("data-"+t)||""),this.root.setAttribute("data-mode",t)}},{key:"restoreFocus",value:function(){var t=this.quill.scrollingContainer.scrollTop;this.quill.focus(),this.quill.scrollingContainer.scrollTop=t}},{key:"save",value:function(){var t=this.textbox.value;switch(this.root.getAttribute("data-mode")){case"link":var e=this.quill.root.scrollTop;this.linkRange?(this.quill.formatText(this.linkRange,"link",t,f.default.sources.USER),delete this.linkRange):(this.restoreFocus(),this.quill.format("link",t,f.default.sources.USER)),this.quill.root.scrollTop=e;break;case"video":t=function(t){var e=t.match(/^(?:(https?):\/\/)?(?:(?:www|m)\.)?youtube\.com\/watch.*v=([a-zA-Z0-9_-]+)/)||t.match(/^(?:(https?):\/\/)?(?:(?:www|m)\.)?youtu\.be\/([a-zA-Z0-9_-]+)/);return e?(e[1]||"https")+"://www.youtube.com/embed/"+e[2]+"?showinfo=0":(e=t.match(/^(?:(https?):\/\/)?(?:www\.)?vimeo\.com\/(\d+)/))?(e[1]||"https")+"://player.vimeo.com/video/"+e[2]+"/":t}(t);case"formula":if(!t)break;var n=this.quill.getSelection(!0);if(null!=n){var r=n.index+n.length;this.quill.insertEmbed(r,this.root.getAttribute("data-mode"),t,f.default.sources.USER),"formula"===this.root.getAttribute("data-mode")&&this.quill.insertText(r+1," ",f.default.sources.USER),this.quill.setSelection(r+2,f.default.sources.USER)}}this.textbox.value="",this.hide()}}]),e}();e.BaseTooltip=q,e.default=k},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(){this.head=this.tail=null,this.length=0}return t.prototype.append=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.insertBefore(t[0],null),t.length>1&&this.append.apply(this,t.slice(1))},t.prototype.contains=function(t){for(var e,n=this.iterator();e=n();)if(e===t)return!0;return!1},t.prototype.insertBefore=function(t,e){t&&(t.next=e,null!=e?(t.prev=e.prev,null!=e.prev&&(e.prev.next=t),e.prev=t,e===this.head&&(this.head=t)):null!=this.tail?(this.tail.next=t,t.prev=this.tail,this.tail=t):(t.prev=null,this.head=this.tail=t),this.length+=1)},t.prototype.offset=function(t){for(var e=0,n=this.head;null!=n;){if(n===t)return e;e+=n.length(),n=n.next}return-1},t.prototype.remove=function(t){this.contains(t)&&(null!=t.prev&&(t.prev.next=t.next),null!=t.next&&(t.next.prev=t.prev),t===this.head&&(this.head=t.next),t===this.tail&&(this.tail=t.prev),this.length-=1)},t.prototype.iterator=function(t){return void 0===t&&(t=this.head),function(){var e=t;return null!=t&&(t=t.next),e}},t.prototype.find=function(t,e){void 0===e&&(e=!1);for(var n,r=this.iterator();n=r();){var i=n.length();if(t<i||e&&t===i&&(null==n.next||0!==n.next.length()))return[n,t];t-=i}return[null,0]},t.prototype.forEach=function(t){for(var e,n=this.iterator();e=n();)t(e)},t.prototype.forEachAt=function(t,e,n){if(!(e<=0))for(var r,i=this.find(t),o=i[0],a=t-i[1],s=this.iterator(o);(r=s())&&a<t+e;){var l=r.length();t>a?n(r,t-a,Math.min(e,a+l-t)):n(r,0,Math.min(l,t+e-a)),a+=l}},t.prototype.map=function(t){return this.reduce(function(e,n){return e.push(t(n)),e},[])},t.prototype.reduce=function(t,e){for(var n,r=this.iterator();n=r();)e=t(e,n);return e},t}();e.default=r},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(17),a=n(1),s={attributes:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0},l=function(t){function e(e){var n=t.call(this,e)||this;return n.scroll=n,n.observer=new MutationObserver(function(t){n.update(t)}),n.observer.observe(n.domNode,s),n.attach(),n}return i(e,t),e.prototype.detach=function(){t.prototype.detach.call(this),this.observer.disconnect()},e.prototype.deleteAt=function(e,n){this.update(),0===e&&n===this.length()?this.children.forEach(function(t){t.remove()}):t.prototype.deleteAt.call(this,e,n)},e.prototype.formatAt=function(e,n,r,i){this.update(),t.prototype.formatAt.call(this,e,n,r,i)},e.prototype.insertAt=function(e,n,r){this.update(),t.prototype.insertAt.call(this,e,n,r)},e.prototype.optimize=function(e,n){var r=this;void 0===e&&(e=[]),void 0===n&&(n={}),t.prototype.optimize.call(this,n);for(var i=[].slice.call(this.observer.takeRecords());i.length>0;)e.push(i.pop());for(var s=function(t,e){void 0===e&&(e=!0),null!=t&&t!==r&&null!=t.domNode.parentNode&&(null==t.domNode[a.DATA_KEY].mutations&&(t.domNode[a.DATA_KEY].mutations=[]),e&&s(t.parent))},l=function(t){null!=t.domNode[a.DATA_KEY]&&null!=t.domNode[a.DATA_KEY].mutations&&(t instanceof o.default&&t.children.forEach(l),t.optimize(n))},c=e,u=0;c.length>0;u+=1){if(u>=100)throw new Error("[Parchment] Maximum optimize iterations reached");for(c.forEach(function(t){var e=a.find(t.target,!0);null!=e&&(e.domNode===t.target&&("childList"===t.type?(s(a.find(t.previousSibling,!1)),[].forEach.call(t.addedNodes,function(t){var e=a.find(t,!1);s(e,!1),e instanceof o.default&&e.children.forEach(function(t){s(t,!1)})})):"attributes"===t.type&&s(e.prev)),s(e))}),this.children.forEach(l),i=(c=[].slice.call(this.observer.takeRecords())).slice();i.length>0;)e.push(i.pop())}},e.prototype.update=function(e,n){var r=this;void 0===n&&(n={}),(e=e||this.observer.takeRecords()).map(function(t){var e=a.find(t.target,!0);return null==e?null:null==e.domNode[a.DATA_KEY].mutations?(e.domNode[a.DATA_KEY].mutations=[t],e):(e.domNode[a.DATA_KEY].mutations.push(t),null)}).forEach(function(t){null!=t&&t!==r&&null!=t.domNode[a.DATA_KEY]&&t.update(t.domNode[a.DATA_KEY].mutations||[],n)}),null!=this.domNode[a.DATA_KEY].mutations&&t.prototype.update.call(this,this.domNode[a.DATA_KEY].mutations,n),this.optimize(e,n)},e.blotName="scroll",e.defaultChild="block",e.scope=a.Scope.BLOCK_BLOT,e.tagName="DIV",e}(o.default);e.default=l},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(18),a=n(1),s=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.formats=function(n){if(n.tagName!==e.tagName)return t.formats.call(this,n)},e.prototype.format=function(n,r){var i=this;n!==this.statics.blotName||r?t.prototype.format.call(this,n,r):(this.children.forEach(function(t){t instanceof o.default||(t=t.wrap(e.blotName,!0)),i.attributes.copy(t)}),this.unwrap())},e.prototype.formatAt=function(e,n,r,i){null!=this.formats()[r]||a.query(r,a.Scope.ATTRIBUTE)?this.isolate(e,n).format(r,i):t.prototype.formatAt.call(this,e,n,r,i)},e.prototype.optimize=function(n){t.prototype.optimize.call(this,n);var r=this.formats();if(0===Object.keys(r).length)return this.unwrap();var i=this.next;i instanceof e&&i.prev===this&&function(t,e){if(Object.keys(t).length!==Object.keys(e).length)return!1;for(var n in t)if(t[n]!==e[n])return!1;return!0}(r,i.formats())&&(i.moveChildren(this),i.remove())},e.blotName="inline",e.scope=a.Scope.INLINE_BLOT,e.tagName="SPAN",e}(o.default);e.default=s},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(18),a=n(1),s=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.formats=function(n){var r=a.query(e.blotName).tagName;if(n.tagName!==r)return t.formats.call(this,n)},e.prototype.format=function(n,r){null!=a.query(n,a.Scope.BLOCK)&&(n!==this.statics.blotName||r?t.prototype.format.call(this,n,r):this.replaceWith(e.blotName))},e.prototype.formatAt=function(e,n,r,i){null!=a.query(r,a.Scope.BLOCK)?this.format(r,i):t.prototype.formatAt.call(this,e,n,r,i)},e.prototype.insertAt=function(e,n,r){if(null==r||null!=a.query(n,a.Scope.INLINE))t.prototype.insertAt.call(this,e,n,r);else{var i=this.split(e),o=a.create(n,r);i.parent.insertBefore(o,i)}},e.prototype.update=function(e,n){navigator.userAgent.match(/Trident/)?this.build():t.prototype.update.call(this,e,n)},e.blotName="block",e.scope=a.Scope.BLOCK_BLOT,e.tagName="P",e}(o.default);e.default=s},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.formats=function(t){},e.prototype.format=function(e,n){t.prototype.formatAt.call(this,0,this.length(),e,n)},e.prototype.formatAt=function(e,n,r,i){0===e&&n===this.length()?this.format(r,i):t.prototype.formatAt.call(this,e,n,r,i)},e.prototype.formats=function(){return this.statics.formats(this.domNode)},e}(n(19).default);e.default=o},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])},function(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(19),a=n(1),s=function(t){function e(e){var n=t.call(this,e)||this;return n.text=n.statics.value(n.domNode),n}return i(e,t),e.create=function(t){return document.createTextNode(t)},e.value=function(t){var e=t.data;return e.normalize&&(e=e.normalize()),e},e.prototype.deleteAt=function(t,e){this.domNode.data=this.text=this.text.slice(0,t)+this.text.slice(t+e)},e.prototype.index=function(t,e){return this.domNode===t?e:-1},e.prototype.insertAt=function(e,n,r){null==r?(this.text=this.text.slice(0,e)+n+this.text.slice(e),this.domNode.data=this.text):t.prototype.insertAt.call(this,e,n,r)},e.prototype.length=function(){return this.text.length},e.prototype.optimize=function(n){t.prototype.optimize.call(this,n),this.text=this.statics.value(this.domNode),0===this.text.length?this.remove():this.next instanceof e&&this.next.prev===this&&(this.insertAt(this.length(),this.next.value()),this.next.remove())},e.prototype.position=function(t,e){return void 0===e&&(e=!1),[this.domNode,t]},e.prototype.split=function(t,e){if(void 0===e&&(e=!1),!e){if(0===t)return this;if(t===this.length())return this.next}var n=a.create(this.domNode.splitText(t));return this.parent.insertBefore(n,this.next),this.text=this.statics.value(this.domNode),n},e.prototype.update=function(t,e){var n=this;t.some(function(t){return"characterData"===t.type&&t.target===n.domNode})&&(this.text=this.statics.value(this.domNode))},e.prototype.value=function(){return this.text},e.blotName="text",e.scope=a.Scope.INLINE_BLOT,e}(o.default);e.default=s},function(t,e,n){"use strict";var r=document.createElement("div");if(r.classList.toggle("test-class",!1),r.classList.contains("test-class")){var i=DOMTokenList.prototype.toggle;DOMTokenList.prototype.toggle=function(t,e){return arguments.length>1&&!this.contains(t)==!e?e:i.call(this,t)}}String.prototype.startsWith||(String.prototype.startsWith=function(t,e){return e=e||0,this.substr(e,t.length)===t}),String.prototype.endsWith||(String.prototype.endsWith=function(t,e){var n=this.toString();("number"!=typeof e||!isFinite(e)||Math.floor(e)!==e||e>n.length)&&(e=n.length),e-=t.length;var r=n.indexOf(t,e);return-1!==r&&r===e}),Array.prototype.find||Object.defineProperty(Array.prototype,"find",{value:function(t){if(null===this)throw new TypeError("Array.prototype.find called on null or undefined");if("function"!=typeof t)throw new TypeError("predicate must be a function");for(var e,n=Object(this),r=n.length>>>0,i=arguments[1],o=0;o<r;o++)if(e=n[o],t.call(i,e,o,n))return e}}),document.addEventListener("DOMContentLoaded",function(){document.execCommand("enableObjectResizing",!1,!1),document.execCommand("autoUrlDetect",!1,!1)})},function(t,e){function n(t,e,u){if(t==e)return t?[[c,t]]:[];(u<0||t.length<u)&&(u=null);var f=i(t,e),d=t.substring(0,f) | ;f=o(t=t.substring(f),e=e.substring(f));var h=t.substring(t.length-f),p=function(t,e){var a;if(!t)return[[l,e]];if(!e)return[[s,t]];var u=t.length>e.length?t:e,f=t.length>e.length?e:t,d=u.indexOf(f);if(-1!=d)return a=[[l,u.substring(0,d)],[c,f],[l,u.substring(d+f.length)]],t.length>e.length&&(a[0][0]=a[2][0]=s),a;if(1==f.length)return[[s,t],[l,e]];var h=function(t,e){function n(t,e,n){for(var r,a,s,l,c=t.substring(n,n+Math.floor(t.length/4)),u=-1,f="";-1!=(u=e.indexOf(c,u+1));){var d=i(t.substring(n),e.substring(u)),h=o(t.substring(0,n),e.substring(0,u));f.length<h+d&&(f=e.substring(u-h,u)+e.substring(u,u+d),r=t.substring(0,n-h),a=t.substring(n+d),s=e.substring(0,u-h),l=e.substring(u+d))}return 2*f.length>=t.length?[r,a,s,l,f]:null}var r=t.length>e.length?t:e,a=t.length>e.length?e:t;if(r.length<4||2*a.length<r.length)return null;var s,l,c,u,f,d=n(r,a,Math.ceil(r.length/4)),h=n(r,a,Math.ceil(r.length/2));return d||h?(s=h?d&&d[4].length>h[4].length?d:h:d,t.length>e.length?(l=s[0],c=s[1],u=s[2],f=s[3]):(u=s[0],f=s[1],l=s[2],c=s[3]),[l,c,u,f,s[4]]):null}(t,e);if(h){var p=h[0],v=h[1],g=h[2],m=h[3],y=h[4],b=n(p,g),w=n(v,m);return b.concat([[c,y]],w)}return function(t,e){for(var n=t.length,i=e.length,o=Math.ceil((n+i)/2),a=o,c=2*o,u=new Array(c),f=new Array(c),d=0;d<c;d++)u[d]=-1,f[d]=-1;u[a+1]=0,f[a+1]=0;for(var h=n-i,p=h%2!=0,v=0,g=0,m=0,y=0,b=0;b<o;b++){for(var w=-b+v;w<=b-g;w+=2){for(var _=a+w,x=(C=w==-b||w!=b&&u[_-1]<u[_+1]?u[_+1]:u[_-1]+1)-w;C<n&&x<i&&t.charAt(C)==e.charAt(x);)C++,x++;if(u[_]=C,C>n)g+=2;else if(x>i)v+=2;else if(p){var k=a+h-w;if(k>=0&&k<c&&-1!=f[k]){var q=n-f[k];if(C>=q)return r(t,e,C,x)}}}for(var O=-b+m;O<=b-y;O+=2){for(var k=a+O,A=(q=O==-b||O!=b&&f[k-1]<f[k+1]?f[k+1]:f[k-1]+1)-O;q<n&&A<i&&t.charAt(n-q-1)==e.charAt(i-A-1);)q++,A++;if(f[k]=q,q>n)y+=2;else if(A>i)m+=2;else if(!p){var _=a+h-O;if(_>=0&&_<c&&-1!=u[_]){var C=u[_],x=a+C-_;if(C>=(q=n-q))return r(t,e,C,x)}}}}return[[s,t],[l,e]]}(t,e)}(t=t.substring(0,t.length-f),e=e.substring(0,e.length-f));return d&&p.unshift([c,d]),h&&p.push([c,h]),function t(e){e.push([c,""]);for(var n,r=0,a=0,u=0,f="",d="";r<e.length;)switch(e[r][0]){case l:u++,d+=e[r][1],r++;break;case s:a++,f+=e[r][1],r++;break;case c:a+u>1?(0!==a&&0!==u&&(0!==(n=i(d,f))&&(r-a-u>0&&e[r-a-u-1][0]==c?e[r-a-u-1][1]+=d.substring(0,n):(e.splice(0,0,[c,d.substring(0,n)]),r++),d=d.substring(n),f=f.substring(n)),0!==(n=o(d,f))&&(e[r][1]=d.substring(d.length-n)+e[r][1],d=d.substring(0,d.length-n),f=f.substring(0,f.length-n))),0===a?e.splice(r-u,a+u,[l,d]):0===u?e.splice(r-a,a+u,[s,f]):e.splice(r-a-u,a+u,[s,f],[l,d]),r=r-a-u+(a?1:0)+(u?1:0)+1):0!==r&&e[r-1][0]==c?(e[r-1][1]+=e[r][1],e.splice(r,1)):r++,u=0,a=0,f="",d=""}""===e[e.length-1][1]&&e.pop();var h=!1;for(r=1;r<e.length-1;)e[r-1][0]==c&&e[r+1][0]==c&&(e[r][1].substring(e[r][1].length-e[r-1][1].length)==e[r-1][1]?(e[r][1]=e[r-1][1]+e[r][1].substring(0,e[r][1].length-e[r-1][1].length),e[r+1][1]=e[r-1][1]+e[r+1][1],e.splice(r-1,1),h=!0):e[r][1].substring(0,e[r+1][1].length)==e[r+1][1]&&(e[r-1][1]+=e[r+1][1],e[r][1]=e[r][1].substring(e[r+1][1].length)+e[r+1][1],e.splice(r+1,1),h=!0)),r++;h&&t(e)}(p),null!=u&&(p=function(t,e){var n=function(t,e){if(0===e)return[c,t];for(var n=0,r=0;r<t.length;r++){var i=t[r];if(i[0]===s||i[0]===c){var o=n+i[1].length;if(e===o)return[r+1,t];if(e<o){t=t.slice();var a=e-n,l=[i[0],i[1].slice(0,a)],u=[i[0],i[1].slice(a)];return t.splice(r,1,l,u),[r+1,t]}n=o}}throw new Error("cursor_pos is out of bounds!")}(t,e),r=n[1],i=n[0],o=r[i],l=r[i+1];if(null==o)return t;if(o[0]!==c)return t;if(null!=l&&o[1]+l[1]===l[1]+o[1])return r.splice(i,2,l,o),a(r,i,2);if(null!=l&&0===l[1].indexOf(o[1])){r.splice(i,2,[l[0],o[1]],[0,o[1]]);var u=l[1].slice(o[1].length);return u.length>0&&r.splice(i+2,0,[l[0],u]),a(r,i,3)}return t}(p,u)),p=function(t){for(var e=!1,n=function(t){return t.charCodeAt(0)>=56320&&t.charCodeAt(0)<=57343},r=2;r<t.length;r+=1)t[r-2][0]===c&&(i=t[r-2][1]).charCodeAt(i.length-1)>=55296&&i.charCodeAt(i.length-1)<=56319&&t[r-1][0]===s&&n(t[r-1][1])&&t[r][0]===l&&n(t[r][1])&&(e=!0,t[r-1][1]=t[r-2][1].slice(-1)+t[r-1][1],t[r][1]=t[r-2][1].slice(-1)+t[r][1],t[r-2][1]=t[r-2][1].slice(0,-1));var i;if(!e)return t;for(var o=[],r=0;r<t.length;r+=1)t[r][1].length>0&&o.push(t[r]);return o}(p)}function r(t,e,r,i){var o=t.substring(0,r),a=e.substring(0,i),s=t.substring(r),l=e.substring(i),c=n(o,a),u=n(s,l);return c.concat(u)}function i(t,e){if(!t||!e||t.charAt(0)!=e.charAt(0))return 0;for(var n=0,r=Math.min(t.length,e.length),i=r,o=0;n<i;)t.substring(o,i)==e.substring(o,i)?o=n=i:r=i,i=Math.floor((r-n)/2+n);return i}function o(t,e){if(!t||!e||t.charAt(t.length-1)!=e.charAt(e.length-1))return 0;for(var n=0,r=Math.min(t.length,e.length),i=r,o=0;n<i;)t.substring(t.length-i,t.length-o)==e.substring(e.length-i,e.length-o)?o=n=i:r=i,i=Math.floor((r-n)/2+n);return i}function a(t,e,n){for(var r=e+n-1;r>=0&&r>=e-1;r--)if(r+1<t.length){var i=t[r],o=t[r+1];i[0]===o[1]&&t.splice(r,2,[i[0],i[1]+o[1]])}return t}var s=-1,l=1,c=0,u=n;u.INSERT=l,u.DELETE=s,u.EQUAL=c,t.exports=u},function(t,e){function n(t){var e=[];for(var n in t)e.push(n);return e}(t.exports="function"==typeof Object.keys?Object.keys:n).shim=n},function(t,e){function n(t){return"[object Arguments]"==Object.prototype.toString.call(t)}function r(t){return t&&"object"==typeof t&&"number"==typeof t.length&&Object.prototype.hasOwnProperty.call(t,"callee")&&!Object.prototype.propertyIsEnumerable.call(t,"callee")||!1}var i="[object Arguments]"==function(){return Object.prototype.toString.call(arguments)}();(e=t.exports=i?n:r).supported=n,e.unsupported=r},function(t,e){"use strict";function n(){}function r(t,e,n){this.fn=t,this.context=e,this.once=n||!1}function i(){this._events=new n,this._eventsCount=0}var o=Object.prototype.hasOwnProperty,a="~";Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(a=!1)),i.prototype.eventNames=function(){var t,e,n=[];if(0===this._eventsCount)return n;for(e in t=this._events)o.call(t,e)&&n.push(a?e.slice(1):e);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(t)):n},i.prototype.listeners=function(t,e){var n=a?a+t:t,r=this._events[n];if(e)return!!r;if(!r)return[];if(r.fn)return[r.fn];for(var i=0,o=r.length,s=new Array(o);i<o;i++)s[i]=r[i].fn;return s},i.prototype.emit=function(t,e,n,r,i,o){var s=a?a+t:t;if(!this._events[s])return!1;var l,c,u=this._events[s],f=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),f){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,n),!0;case 4:return u.fn.call(u.context,e,n,r),!0;case 5:return u.fn.call(u.context,e,n,r,i),!0;case 6:return u.fn.call(u.context,e,n,r,i,o),!0}for(c=1,l=new Array(f-1);c<f;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var d,h=u.length;for(c=0;c<h;c++)switch(u[c].once&&this.removeListener(t,u[c].fn,void 0,!0),f){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,e);break;case 3:u[c].fn.call(u[c].context,e,n);break;case 4:u[c].fn.call(u[c].context,e,n,r);break;default:if(!l)for(d=1,l=new Array(f-1);d<f;d++)l[d-1]=arguments[d];u[c].fn.apply(u[c].context,l)}}return!0},i.prototype.on=function(t,e,n){var i=new r(e,n||this),o=a?a+t:t;return this._events[o]?this._events[o].fn?this._events[o]=[this._events[o],i]:this._events[o].push(i):(this._events[o]=i,this._eventsCount++),this},i.prototype.once=function(t,e,n){var i=new r(e,n||this,!0),o=a?a+t:t;return this._events[o]?this._events[o].fn?this._events[o]=[this._events[o],i]:this._events[o].push(i):(this._events[o]=i,this._eventsCount++),this},i.prototype.removeListener=function(t,e,r,i){var o=a?a+t:t;if(!this._events[o])return this;if(!e)return 0==--this._eventsCount?this._events=new n:delete this._events[o],this;var s=this._events[o];if(s.fn)s.fn!==e||i&&!s.once||r&&s.context!==r||(0==--this._eventsCount?this._events=new n:delete this._events[o]);else{for(var l=0,c=[],u=s.length;l<u;l++)(s[l].fn!==e||i&&!s[l].once||r&&s[l].context!==r)&&c.push(s[l]);c.length?this._events[o]=1===c.length?c[0]:c:0==--this._eventsCount?this._events=new n:delete this._events[o]}return this},i.prototype.removeAllListeners=function(t){var e;return t?(e=a?a+t:t,this._events[e]&&(0==--this._eventsCount?this._events=new n:delete this._events[e])):(this._events=new n,this._eventsCount=0),this},i.prototype.off=i.prototype.removeListener,i.prototype.addListener=i.prototype.on,i.prototype.setMaxListeners=function(){return this},i.prefixed=a,i.EventEmitter=i,void 0!==t&&(t.exports=i)},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function o(t,e,n){return"object"===(void 0===e?"undefined":v(e))?Object.keys(e).reduce(function(t,n){return o(t,n,e[n])},t):t.reduce(function(t,r){return r.attributes&&r.attributes[e]?t.push(r):t.insert(r.insert,(0,y.default)({},i({},e,n),r.attributes))},new b.default)}function a(t){return t.nodeType!==Node.ELEMENT_NODE?{}:t["__ql-computed-style"]||(t["__ql-computed-style"]=window.getComputedStyle(t))}function s(t,e){for(var n="",r=t.ops.length-1;r>=0&&n.length<e.length;--r){var i=t.ops[r];if("string"!=typeof i.insert)break;n=i.insert+n}return n.slice(-1*e.length)===e}function l(t){return 0!==t.childNodes.length&&["block","list-item"].indexOf(a(t).display)>-1}function c(t,e,n){return o(n,t,!0)}function u(t,e){var n=w.default.Attributor.Attribute.keys(t),r=w.default.Attributor.Class.keys(t),i=w.default.Attributor.Style.keys(t),a={};return n.concat(r).concat(i).forEach(function(e){var n=w.default.query(e,w.default.Scope.ATTRIBUTE);null!=n&&(a[n.attrName]=n.value(t),a[n.attrName])||(null==(n=P[e])||n.attrName!==e&&n.keyName!==e||(a[n.attrName]=n.value(t)||void 0),null==(n=D[e])||n.attrName!==e&&n.keyName!==e||(n=D[e],a[n.attrName]=n.value(t)||void 0))}),Object.keys(a).length>0&&(e=o(e,a)),e}function f(t,e){var n=w.default.query(t);if(null==n)return e;if(n.prototype instanceof w.default.Embed){var r={},i=n.value(t);null!=i&&(r[n.blotName]=i,e=(new b.default).insert(r,n.formats(t)))}else"function"==typeof n.formats&&(e=o(e,n.blotName,n.formats(t)));return e}function d(t,e){return s(e,"\n")||(l(t)||e.length()>0&&t.nextSibling&&l(t.nextSibling))&&e.insert("\n"),e}function h(t,e){if(l(t)&&null!=t.nextElementSibling&&!s(e,"\n\n")){var n=t.offsetHeight+parseFloat(a(t).marginTop)+parseFloat(a(t).marginBottom);t.nextElementSibling.offsetTop>t.offsetTop+1.5*n&&e.insert("\n")}return e}function p(t,e){var n=t.data;if("O:P"===t.parentNode.tagName)return e.insert(n.trim());if(0===n.trim().length&&t.parentNode.classList.contains("ql-clipboard"))return e;if(!a(t.parentNode).whiteSpace.startsWith("pre")){var r=function(t,e){return(e=e.replace(/[^\u00a0]/g,"")).length<1&&t?" ":e};n=(n=n.replace(/\r\n/g," ").replace(/\n/g," ")).replace(/\s\s+/g,r.bind(r,!0)),(null==t.previousSibling&&l(t.parentNode)||null!=t.previousSibling&&l(t.previousSibling))&&(n=n.replace(/^\s+/,r.bind(r,!1))),(null==t.nextSibling&&l(t.parentNode)||null!=t.nextSibling&&l(t.nextSibling))&&(n=n.replace(/\s+$/,r.bind(r,!1)))}return e.insert(n)}Object.defineProperty(e,"__esModule",{value:!0}),e.matchText=e.matchSpacing=e.matchNewline=e.matchBlot=e.matchAttributor=e.default=void 0;var v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},g=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),m=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),y=r(n(3)),b=r(n(2)),w=r(n(0)),_=r(n(5)),x=r(n(10)),k=r(n(9)),q=n(36),O=n(37),A=r(n(13)),C=n(26),E=n(38),S=n(39),T=n(40),N=(0,x.default)("quill:clipboard"),j="__ql-matcher",M=[[Node.TEXT_NODE,p],[Node.TEXT_NODE,d],["br",function(t,e){return s(e,"\n")||e.insert("\n"),e}],[Node.ELEMENT_NODE,d],[Node.ELEMENT_NODE,f],[Node.ELEMENT_NODE,h],[Node.ELEMENT_NODE,u],[Node.ELEMENT_NODE,function(t,e){var n={},r=t.style||{};return r.fontStyle&&"italic"===a(t).fontStyle&&(n.italic=!0),r.fontWeight&&(a(t).fontWeight.startsWith("bold")||parseInt(a(t).fontWeight)>=700)&&(n.bold=!0),Object.keys(n).length>0&&(e=o(e,n)),parseFloat(r.textIndent||0)>0&&(e=(new b.default).insert("\t").concat(e)),e}],["li",function(t,e){var n=w.default.query(t);if(null==n||"list-item"!==n.blotName||!s(e,"\n"))return e;for(var r=-1,i=t.parentNode;!i.classList.contains("ql-clipboard");)"list"===(w.default.query(i)||{}).blotName&&(r+=1),i=i.parentNode;return r<=0?e:e.compose((new b.default).retain(e.length()-1).retain(1,{indent:r}))}],["b",c.bind(c,"bold")],["i",c.bind(c,"italic")],["style",function(){return new b.default}]],P=[q.AlignAttribute,E.DirectionAttribute].reduce(function(t,e){return t[e.keyName]=e,t},{}),D=[q.AlignStyle,O.BackgroundStyle,C.ColorStyle,E.DirectionStyle,S.FontStyle,T.SizeStyle].reduce(function(t,e){return t[e.keyName]=e,t},{}),L=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.quill.root.addEventListener("paste",r.onPaste.bind(r)),r.container=r.quill.addContainer("ql-clipboard"),r.container.setAttribute("contenteditable",!0),r.container.setAttribute("tabindex",-1),r.matchers=[],M.concat(r.options.matchers).forEach(function(t){var e=g(t,2),i=e[0],o=e[1];(n.matchVisual||o!==h)&&r.addMatcher(i,o)}),r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,k.default),m(e,[{key:"addMatcher",value:function(t,e){this.matchers.push([t,e])}},{key:"convert",value:function(t){if("string"==typeof t)return this.container.innerHTML=t.replace(/\>\r?\n +\</g,"><"),this.convert();var e=this.quill.getFormat(this.quill.selection.savedRange.index);if(e[A.default.blotName]){var n=this.container.innerText;return this.container.innerHTML="",(new b.default).insert(n,i({},A.default.blotName,e[A.default.blotName]))}var r=this.prepareMatching(),o=g(r,2),a=o[0],l=o[1],c=function t(e,n,r){return e.nodeType===e.TEXT_NODE?r.reduce(function(t,n){return n(e,t)},new b.default):e.nodeType===e.ELEMENT_NODE?[].reduce.call(e.childNodes||[],function(i,o){var a=t(o,n,r);return o.nodeType===e.ELEMENT_NODE&&(a=n.reduce(function(t,e){return e(o,t)},a),a=(o[j]||[]).reduce(function(t,e){return e(o,t)},a)),i.concat(a)},new b.default):new b.default}(this.container,a,l);return s(c,"\n")&&null==c.ops[c.ops.length-1].attributes&&(c=c.compose((new b.default).retain(c.length()-1).delete(1))),N.log("convert",this.container.innerHTML,c),this.container.innerHTML="",c}},{key:"dangerouslyPasteHTML",value:function(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:_.default.sources.API;if("string"==typeof t)this.quill.setContents(this.convert(t),e),this.quill.setSelection(0,_.default.sources.SILENT);else{var r=this.convert(e);this.quill.updateContents((new b.default).retain(t).concat(r),n),this.quill.setSelection(t+r.length(),_.default.sources.SILENT)}}},{key:"onPaste",value:function(t){var e=this;if(!t.defaultPrevented&&this.quill.isEnabled()){var n=this.quill.getSelection(),r=(new b.default).retain(n.index),i=this.quill.scrollingContainer.scrollTop;this.container.focus(),this.quill.selection.update(_.default.sources.SILENT),setTimeout(function(){r=r.concat(e.convert()).delete(n.length),e.quill.updateContents(r,_.default.sources.USER),e.quill.setSelection(r.length()-n.length,_.default.sources.SILENT),e.quill.scrollingContainer.scrollTop=i,e.quill.focus()},1)}}},{key:"prepareMatching",value:function(){var t=this,e=[],n=[];return this.matchers.forEach(function(r){var i=g(r,2),o=i[0],a=i[1];switch(o){case Node.TEXT_NODE:n.push(a);break;case Node.ELEMENT_NODE:e.push(a);break;default:[].forEach.call(t.container.querySelectorAll(o),function(t){t[j]=t[j]||[],t[j].push(a)})}}),[e,n]}}]),e}();L.DEFAULTS={matchers:[],matchVisual:!0},e.default=L,e.matchAttributor=u,e.matchBlot=f,e.matchNewline=d,e.matchSpacing=h,e.matchText=p},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},a=n(6),s=(r=a)&&r.__esModule?r:{default:r},l=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,s.default),i(e,[{key:"optimize",value:function(t){o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"optimize",this).call(this,t),this.domNode.tagName!==this.statics.tagName[0]&&this.replaceWith(this.statics.blotName)}}],[{key:"create",value:function(){return o(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this)}},{key:"formats",value:function(){return!0}}]),e}();l.blotName="bold",l.tagName=["STRONG","B"],e.default=l},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function o(t,e,n){var r=document.createElement("button");r.setAttribute("type","button"),r.classList.add("ql-"+e),null!=n&&(r.value=n),t.appendChild(r)}function a(t,e){Array.isArray(e[0])||(e=[e]),e.forEach(function(e){var n=document.createElement("span");n.classList.add("ql-formats"),e.forEach(function(t){if("string"==typeof t)o(n,t);else{var e=Object.keys(t)[0],r=t[e];Array.isArray(r)?function(t,e,n){var r=document.createElement("select");r.classList.add("ql-"+e),n.forEach(function(t){var e=document.createElement("option");!1!==t?e.setAttribute("value",t):e.setAttribute("selected","selected"),r.appendChild(e)}),t.appendChild(r)}(n,e,r):o(n,e,r)}}),t.appendChild(n)})}Object.defineProperty(e,"__esModule",{value:!0}),e.addControls=e.default=void 0;var s=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),l=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),c=r(n(2)),u=r(n(0)),f=r(n(5)),d=r(n(10)),h=r(n(9)),p=(0,d.default)("quill:toolbar"),v=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r,o=i(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));if(Array.isArray(o.options.container)){var l=document.createElement("div");a(l,o.options.container),t.container.parentNode.insertBefore(l,t.container),o.container=l}else"string"==typeof o.options.container?o.container=document.querySelector(o.options.container):o.container=o.options.container;return o.container instanceof HTMLElement?(o.container.classList.add("ql-toolbar"),o.controls=[],o.handlers={},Object.keys(o.options.handlers).forEach(function(t){o.addHandler(t,o.options.handlers[t])}),[].forEach.call(o.container.querySelectorAll("button, select"),function(t){o.attach(t)}),o.quill.on(f.default.events.EDITOR_CHANGE,function(t,e){t===f.default.events.SELECTION_CHANGE&&o.update(e)}),o.quill.on(f.default.events.SCROLL_OPTIMIZE,function(){var t=o.quill.selection.getRange(),e=s(t,1)[0];o.update(e)}),o):(r=p.error("Container required for toolbar",o.options),i(o,r))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,h.default),l(e,[{key:"addHandler",value:function(t,e){this.handlers[t]=e}},{key:"attach",value:function(t){var e=this,n=[].find.call(t.classList,function(t){return 0===t.indexOf("ql-")});if(n){if(n=n.slice("ql-".length),"BUTTON"===t.tagName&&t.setAttribute("type","button"),null==this.handlers[n]){if(null!=this.quill.scroll.whitelist&&null==this.quill.scroll.whitelist[n])return void p.warn("ignoring attaching to disabled format",n,t);if(null==u.default.query(n))return void p.warn("ignoring attaching to nonexistent format",n,t)}var r="SELECT"===t.tagName?"change":"click";t.addEventListener(r,function(r){var i=void 0;if("SELECT"===t.tagName){if(t.selectedIndex<0)return;var o=t.options[t.selectedIndex];i=!o.hasAttribute("selected")&&(o.value||!1)}else i=!t.classList.contains("ql-active")&&(t.value||!t.hasAttribute("value")),r.preventDefault();e.quill.focus();var a=e.quill.selection.getRange(),l=s(a,1)[0];if(null!=e.handlers[n])e.handlers[n].call(e,i);else if(u.default.query(n).prototype instanceof u.default.Embed){if(!(i=prompt("Enter "+n)))return;e.quill.updateContents((new c.default).retain(l.index).delete(l.length).insert(function(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}({},n,i)),f.default.sources.USER)}else e.quill.format(n,i,f.default.sources.USER);e.update(l)}),this.controls.push([n,t])}}},{key:"update",value:function(t){var e=null==t?{}:this.quill.getFormat(t);this.controls.forEach(function(n){var r=s(n,2),i=r[0],o=r[1];if("SELECT"===o.tagName){var a=void 0;if(null==t)a=null;else if(null==e[i])a=o.querySelector("option[selected]");else if(!Array.isArray(e[i])){var l=e[i];"string"==typeof l&&(l=l.replace(/\"/g,'\\"')),a=o.querySelector('option[value="'+l+'"]')}null==a?(o.value="",o.selectedIndex=-1):a.selected=!0}else if(null==t)o.classList.remove("ql-active");else if(o.hasAttribute("value")){var c=e[i]===o.getAttribute("value")||null!=e[i]&&e[i].toString()===o.getAttribute("value")||null==e[i]&&!o.getAttribute("value");o.classList.toggle("ql-active",c)}else o.classList.toggle("ql-active",null!=e[i])})}}]),e}();v.DEFAULTS={},v.DEFAULTS={container:null,handlers:{clean:function(){var t=this,e=this.quill.getSelection();if(null!=e)if(0==e.length){var n=this.quill.getFormat();Object.keys(n).forEach(function(e){null!=u.default.query(e,u.default.Scope.INLINE)&&t.quill.format(e,!1)})}else this.quill.removeFormat(e,f.default.sources.USER)},direction:function(t){var e=this.quill.getFormat().align;"rtl"===t&&null==e?this.quill.format("align","right",f.default.sources.USER):t||"right"!==e||this.quill.format("align",!1,f.default.sources.USER),this.quill.format("direction",t,f.default.sources.USER)},indent:function(t){var e=this.quill.getSelection(),n=this.quill.getFormat(e),r=parseInt(n.indent||0);if("+1"===t||"-1"===t){var i="+1"===t?1:-1;"rtl"===n.direction&&(i*=-1),this.quill.format("indent",r+i,f.default.sources.USER)}},link:function(t){!0===t&&(t=prompt("Enter link URL:")),this.quill.format("link",t,f.default.sources.USER)},list:function(t){var e=this.quill.getSelection(),n=this.quill.getFormat(e);"check"===t?"checked"===n.list||"unchecked"===n.list?this.quill.format("list",!1,f.default.sources.USER):this.quill.format("list","unchecked",f.default.sources.USER):this.quill.format("list",t,f.default.sources.USER)}}},e.default=v,e.addControls=a},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <polyline class="ql-even ql-stroke" points="5 7 3 9 5 11"></polyline> <polyline class="ql-even ql-stroke" points="13 7 15 9 13 11"></polyline> <line class=ql-stroke x1=10 x2=8 y1=5 y2=13></line> </svg>'},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},a=n(28),s=(r=a)&&r.__esModule?r:{default:r},l=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return r.label.innerHTML=n,r.container.classList.add("ql-color-picker"),[].slice.call(r.container.querySelectorAll(".ql-picker-item"),0,7).forEach(function(t){t.classList.add("ql-primary")}),r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,s.default),i(e,[{key:"buildItem",value:function(t){var n=o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"buildItem",this).call(this,t);return n.style.backgroundColor=t.getAttribute("value")||"",n}},{key:"selectItem",value:function(t,n){o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"selectItem",this).call(this,t,n);var r=this.label.querySelector(".ql-color-label"),i=t&&t.getAttribute("data-value")||"";r&&("line"===r.tagName?r.style.stroke=i:r.style.fill=i)}}]),e}();e.default=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(28),a=(r=o)&&r.__esModule?r:{default:r},s=function(t){function e(t,n){!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e);var r=function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t));return r.container.classList.add("ql-icon-picker"),[].forEach.call(r.container.querySelectorAll(".ql-picker-item"),function(t){t.innerHTML=n[t.getAttribute("data-value")||""]}),r.defaultItem=r.container.querySelector(".ql-selected"),r.selectItem(r.defaultItem),r}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,a.default),i(e,[{key:"selectItem",value:function(t,n){(function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0})(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"selectItem",this).call(this,t,n),t=t||this.defaultItem,this.label.innerHTML=t.innerHTML}}]),e}();e.default=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),i=function(){function t(e,n){var r=this;!function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,t),this.quill=e,this.boundsContainer=n||document.body,this.root=e.addContainer("ql-tooltip"),this.root.innerHTML=this.constructor.TEMPLATE,this.quill.root===this.quill.scrollingContainer&&this.quill.root.addEventListener("scroll",function(){r.root.style.marginTop=-1*r.quill.root.scrollTop+"px"}),this.hide()}return r(t,[{key:"hide",value:function(){this.root.classList.add("ql-hidden")}},{key:"position",value:function(t){var e=t.left+t.width/2-this.root.offsetWidth/2,n=t.bottom+this.quill.root.scrollTop;this.root.style.left=e+"px",this.root.style.top=n+"px",this.root.classList.remove("ql-flip");var r=this.boundsContainer.getBoundingClientRect(),i=this.root.getBoundingClientRect(),o=0;if(i.right>r.right&&(o=r.right-i.right,this.root.style.left=e+o+"px"),i.left<r.left&&(o=r.left-i.left,this.root.style.left=e+o+"px"),i.bottom>r.bottom){var a=i.bottom-i.top,s=t.bottom-t.top+a;this.root.style.top=n-s+"px",this.root.classList.add("ql-flip")}return o}},{key:"show",value:function(){this.root.classList.remove("ql-editing"),this.root.classList.remove("ql-hidden")}}]),t}();e.default=i},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var s=function(){return function(t,e){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return function(t,e){var n=[],r=!0,i=!1,o=void 0;try{for(var a,s=t[Symbol.iterator]();!(r=(a=s.next()).done)&&(n.push(a.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{!r&&s.return&&s.return()}finally{if(i)throw o}}return n}(t,e)
;throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),l=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},c=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),u=r(n(3)),f=r(n(8)),d=n(43),h=r(d),p=r(n(27)),v=n(15),g=r(n(41)),m=[[{header:["1","2","3",!1]}],["bold","italic","underline","link"],[{list:"ordered"},{list:"bullet"}],["clean"]],y=function(t){function e(t,n){i(this,e),null!=n.modules.toolbar&&null==n.modules.toolbar.container&&(n.modules.toolbar.container=m);var r=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.quill.container.classList.add("ql-snow"),r}return a(e,h.default),c(e,[{key:"extendToolbar",value:function(t){t.container.classList.add("ql-snow"),this.buildButtons([].slice.call(t.container.querySelectorAll("button")),g.default),this.buildPickers([].slice.call(t.container.querySelectorAll("select")),g.default),this.tooltip=new b(this.quill,this.options.bounds),t.container.querySelector(".ql-link")&&this.quill.keyboard.addBinding({key:"K",shortKey:!0},function(e,n){t.handlers.link.call(t,!n.format.link)})}}]),e}();y.DEFAULTS=(0,u.default)(!0,{},h.default.DEFAULTS,{modules:{toolbar:{handlers:{link:function(t){if(t){var e=this.quill.getSelection();if(null==e||0==e.length)return;var n=this.quill.getText(e);/^\S+@\S+\.\S+$/.test(n)&&0!==n.indexOf("mailto:")&&(n="mailto:"+n),this.quill.theme.tooltip.edit("link",n)}else this.quill.format("link",!1)}}}}});var b=function(t){function e(t,n){i(this,e);var r=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.preview=r.root.querySelector("a.ql-preview"),r}return a(e,d.BaseTooltip),c(e,[{key:"listen",value:function(){var t=this;l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"listen",this).call(this),this.root.querySelector("a.ql-action").addEventListener("click",function(e){t.root.classList.contains("ql-editing")?t.save():t.edit("link",t.preview.textContent),e.preventDefault()}),this.root.querySelector("a.ql-remove").addEventListener("click",function(e){if(null!=t.linkRange){var n=t.linkRange;t.restoreFocus(),t.quill.formatText(n,"link",!1,f.default.sources.USER),delete t.linkRange}e.preventDefault(),t.hide()}),this.quill.on(f.default.events.SELECTION_CHANGE,function(e,n,r){if(null!=e){if(0===e.length&&r===f.default.sources.USER){var i=t.quill.scroll.descendant(p.default,e.index),o=s(i,2),a=o[0],l=o[1];if(null!=a){t.linkRange=new v.Range(e.index-l,a.length());var c=p.default.formats(a.domNode);return t.preview.textContent=c,t.preview.setAttribute("href",c),t.show(),void t.position(t.quill.getBounds(t.linkRange))}}else delete t.linkRange;t.hide()}})}},{key:"show",value:function(){l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"show",this).call(this),this.root.removeAttribute("data-mode")}}]),e}();b.TEMPLATE=['<a class="ql-preview" target="_blank" href="about:blank"></a>','<input type="text" data-formula="e=mc^2" data-link="https://quilljs.com" data-video="Embed URL">','<a class="ql-action"></a>','<a class="ql-remove"></a>'].join(""),e.default=y},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}Object.defineProperty(e,"__esModule",{value:!0});var i=r(n(29)),o=n(36),a=n(38),s=n(64),l=r(n(65)),c=r(n(66)),u=n(67),f=r(u),d=n(37),h=n(26),p=n(39),v=n(40),g=r(n(56)),m=r(n(68)),y=r(n(27)),b=r(n(69)),w=r(n(70)),_=r(n(71)),x=r(n(72)),k=r(n(73)),q=n(13),O=r(q),A=r(n(74)),C=r(n(75)),E=r(n(57)),S=r(n(41)),T=r(n(28)),N=r(n(59)),j=r(n(60)),M=r(n(61)),P=r(n(108)),D=r(n(62));i.default.register({"attributors/attribute/direction":a.DirectionAttribute,"attributors/class/align":o.AlignClass,"attributors/class/background":d.BackgroundClass,"attributors/class/color":h.ColorClass,"attributors/class/direction":a.DirectionClass,"attributors/class/font":p.FontClass,"attributors/class/size":v.SizeClass,"attributors/style/align":o.AlignStyle,"attributors/style/background":d.BackgroundStyle,"attributors/style/color":h.ColorStyle,"attributors/style/direction":a.DirectionStyle,"attributors/style/font":p.FontStyle,"attributors/style/size":v.SizeStyle},!0),i.default.register({"formats/align":o.AlignClass,"formats/direction":a.DirectionClass,"formats/indent":s.IndentClass,"formats/background":d.BackgroundStyle,"formats/color":h.ColorStyle,"formats/font":p.FontClass,"formats/size":v.SizeClass,"formats/blockquote":l.default,"formats/code-block":O.default,"formats/header":c.default,"formats/list":f.default,"formats/bold":g.default,"formats/code":q.Code,"formats/italic":m.default,"formats/link":y.default,"formats/script":b.default,"formats/strike":w.default,"formats/underline":_.default,"formats/image":x.default,"formats/video":k.default,"formats/list/item":u.ListItem,"modules/formula":A.default,"modules/syntax":C.default,"modules/toolbar":E.default,"themes/bubble":P.default,"themes/snow":D.default,"ui/icons":S.default,"ui/picker":T.default,"ui/icon-picker":j.default,"ui/color-picker":N.default,"ui/tooltip":M.default},!0),e.default=i.default},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.IndentClass=void 0;var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},a=n(0),s=(r=a)&&r.__esModule?r:{default:r},l=new(function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,s.default.Attributor.Class),i(e,[{key:"add",value:function(t,n){if("+1"===n||"-1"===n){var r=this.value(t)||0;n="+1"===n?r+1:r-1}return 0===n?(this.remove(t),!0):o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"add",this).call(this,t,n)}},{key:"canAdd",value:function(t,n){return o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"canAdd",this).call(this,t,n)||o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"canAdd",this).call(this,t,parseInt(n))}},{key:"value",value:function(t){return parseInt(o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"value",this).call(this,t))||void 0}}]),e}())("indent","ql-indent",{scope:s.default.Scope.BLOCK,whitelist:[1,2,3,4,5,6,7,8]});e.IndentClass=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(4),o=(r=i)&&r.__esModule?r:{default:r},a=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,o.default),e}();a.blotName="blockquote",a.tagName="blockquote",e.default=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(4),a=(r=o)&&r.__esModule?r:{default:r},s=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,a.default),i(e,null,[{key:"formats",value:function(t){return this.tagName.indexOf(t.tagName)+1}}]),e}();s.blotName="header",s.tagName=["H1","H2","H3","H4","H5","H6"],e.default=s},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.ListItem=void 0;var s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),l=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},c=r(n(0)),u=r(n(4)),f=r(n(25)),d=function(t){function e(){return i(this,e),o(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return a(e,u.default),s(e,[{key:"format",value:function(t,n){t!==h.blotName||n?l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"format",this).call(this,t,n):this.replaceWith(c.default.create(this.statics.scope))}},{key:"remove",value:function(){null==this.prev&&null==this.next?this.parent.remove():l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"remove",this).call(this)}},{key:"replaceWith",value:function(t,n){return this.parent.isolate(this.offset(this.parent),this.length()),t===this.parent.statics.blotName?(this.parent.replaceWith(t,n),this):(this.parent.unwrap(),l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"replaceWith",this).call(this,t,n))}}],[{key:"formats",value:function(t){return t.tagName===this.tagName?void 0:l(e.__proto__||Object.getPrototypeOf(e),"formats",this).call(this,t)}}]),e}();d.blotName="list-item",d.tagName="LI";var h=function(t){function e(t){i(this,e);var n=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t)),r=function(e){if(e.target.parentNode===t){var r=n.statics.formats(t),i=c.default.find(e.target);"checked"===r?i.format("list","unchecked"):"unchecked"===r&&i.format("list","checked")}};return t.addEventListener("touchstart",r),t.addEventListener("mousedown",r),n}return a(e,f.default),s(e,null,[{key:"create",value:function(t){var n="ordered"===t?"OL":"UL",r=l(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this,n);return"checked"!==t&&"unchecked"!==t||r.setAttribute("data-checked","checked"===t),r}},{key:"formats",value:function(t){return"OL"===t.tagName?"ordered":"UL"===t.tagName?t.hasAttribute("data-checked")?"true"===t.getAttribute("data-checked")?"checked":"unchecked":"bullet":void 0}}]),s(e,[{key:"format",value:function(t,e){this.children.length>0&&this.children.tail.format(t,e)}},{key:"formats",value:function(){return t={},e=this.statics.blotName,n=this.statics.formats(this.domNode),e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t;var t,e,n}},{key:"insertBefore",value:function(t,n){if(t instanceof d)l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"insertBefore",this).call(this,t,n);else{var r=null==n?this.length():n.offset(this),i=this.split(r);i.parent.insertBefore(t,i)}}},{key:"optimize",value:function(t){l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"optimize",this).call(this,t);var n=this.next;null!=n&&n.prev===this&&n.statics.blotName===this.statics.blotName&&n.domNode.tagName===this.domNode.tagName&&n.domNode.getAttribute("data-checked")===this.domNode.getAttribute("data-checked")&&(n.moveChildren(this),n.remove())}},{key:"replace",value:function(t){if(t.statics.blotName!==this.statics.blotName){var n=c.default.create(this.statics.defaultChild);t.moveChildren(n),this.appendChild(n)}l(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"replace",this).call(this,t)}}]),e}();h.blotName="list",h.scope=c.default.Scope.BLOCK_BLOT,h.tagName=["OL","UL"],h.defaultChild="list-item",h.allowedChildren=[d],e.ListItem=d,e.default=h},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(56),o=(r=i)&&r.__esModule?r:{default:r},a=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,o.default),e}();a.blotName="italic",a.tagName=["EM","I"],e.default=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=n(6),a=(r=o)&&r.__esModule?r:{default:r},s=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,a.default),i(e,null,[{key:"create",value:function(t){return"super"===t?document.createElement("sup"):"sub"===t?document.createElement("sub"):function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this,t)}},{key:"formats",value:function(t){return"SUB"===t.tagName?"sub":"SUP"===t.tagName?"super":void 0}}]),e}();s.blotName="script",s.tagName=["SUB","SUP"],e.default=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(6),o=(r=i)&&r.__esModule?r:{default:r},a=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,o.default),e}();a.blotName="strike",a.tagName="S",e.default=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(6),o=(r=i)&&r.__esModule?r:{default:r},a=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,o.default),e}();a.blotName="underline",a.tagName="U",e.default=a},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},a=n(0),s=(r=a)&&r.__esModule?r:{default:r},l=n(27),c=["alt","height","width"],u=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,s.default.Embed),i(e,[{key:"format",value:function(t,n){c.indexOf(t)>-1?n?this.domNode.setAttribute(t,n):this.domNode.removeAttribute(t):o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"format",this).call(this,t,n)}}],[{key:"create",value:function(t){var n=o(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this,t);return"string"==typeof t&&n.setAttribute("src",this.sanitize(t)),n}},{key:"formats",value:function(t){return c.reduce(function(e,n){return t.hasAttribute(n)&&(e[n]=t.getAttribute(n)),e},{})}},{key:"match",value:function(t){return/\.(jpe?g|gif|png)$/.test(t)||/^data:image\/.+;base64/.test(t)}},{key:"sanitize",value:function(t){return(0,l.sanitize)(t,["http","https","data"])?t:"//:0"}},{key:"value",value:function(t){return t.getAttribute("src")}}]),e}();u.blotName="image",u.tagName="IMG",e.default=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),o=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},a=n(4),s=n(27),l=(r=s)&&r.__esModule?r:{default:r},c=["height","width"],u=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),function(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}(e,a.BlockEmbed),i(e,[{key:"format",value:function(t,n){c.indexOf(t)>-1?n?this.domNode.setAttribute(t,n):this.domNode.removeAttribute(t):o(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"format",this).call(this,t,n)}}],[{key:"create",value:function(t){var n=o(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this,t);return n.setAttribute("frameborder","0"),n.setAttribute("allowfullscreen",!0),n.setAttribute("src",this.sanitize(t)),n}},{key:"formats",value:function(t){return c.reduce(function(e,n){return t.hasAttribute(n)&&(e[n]=t.getAttribute(n)),e},{})}},{key:"sanitize",value:function(t){return l.default.sanitize(t)}},{key:"value",value:function(t){return t.getAttribute("src")}}]),e}();u.blotName="video",u.className="ql-video",u.tagName="IFRAME",e.default=u},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.FormulaBlot=void 0;var s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),l=r(n(35)),c=r(n(5)),u=r(n(9)),f=function(t){function e(){return i(this,e),o(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return a(e,l.default),s(e,null,[{key:"create",value:function(t){var n=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.__proto__||Object.getPrototypeOf(e),"create",this).call(this,t);return"string"==typeof t&&(window.katex.render(t,n,{throwOnError:!1,errorColor:"#f00"}),n.setAttribute("data-value",t)),n}},{key:"value",value:function(t){return t.getAttribute("data-value")}}]),e}();f.blotName="formula",f.className="ql-formula",f.tagName="SPAN";var d=function(t){function e(){i(this,e);var t=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this));if(null==window.katex)throw new Error("Formula module requires KaTeX.");return t}return a(e,u.default),s(e,null,[{key:"register",value:function(){c.default.register(f,!0)}}]),e}();e.FormulaBlot=f,e.default=d},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.CodeToken=e.CodeBlock=void 0;var s=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),l=r(n(0)),c=r(n(5)),u=r(n(9)),f=r(n(13)),d=function(t){function e(){return i(this,e),o(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return a(e,f.default),s(e,[{key:"replaceWith",value:function(t){this.domNode.textContent=this.domNode.textContent,this.attach(),function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0}(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"replaceWith",this).call(this,t)}},{key:"highlight",value:function(t){var e=this.domNode.textContent;this.cachedText!==e&&((e.trim().length>0||null==this.cachedText)&&(this.domNode.innerHTML=t(e),this.domNode.normalize(),this.attach()),this.cachedText=e)}}]),e}();d.className="ql-syntax";var h=new l.default.Attributor.Class("token","hljs",{scope:l.default.Scope.INLINE}),p=function(t){function e(t,n){i(this,e);var r=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));if("function"!=typeof r.options.highlight)throw new Error("Syntax module requires highlight.js. Please include the library on the page before Quill.");var a=null;return r.quill.on(c.default.events.SCROLL_OPTIMIZE,function(){clearTimeout(a),a=setTimeout(function(){r.highlight(),a=null},r.options.interval)}),r.highlight(),r}return a(e,u.default),s(e,null,[{key:"register",value:function(){c.default.register(h,!0),c.default.register(d,!0)}}]),s(e,[{key:"highlight",value:function(){var t=this;if(!this.quill.selection.composing){this.quill.update(c.default.sources.USER);var e=this.quill.getSelection();this.quill.scroll.descendants(d).forEach(function(e){e.highlight(t.options.highlight)}),this.quill.update(c.default.sources.SILENT),null!=e&&this.quill.setSelection(e,c.default.sources.SILENT)}}}]),e}();p.DEFAULTS={highlight:null==window.hljs?null:function(t){return window.hljs.highlightAuto(t).value},interval:1e3},e.CodeBlock=d,e.CodeToken=h,e.default=p},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=3 x2=15 y1=9 y2=9></line> <line class=ql-stroke x1=3 x2=13 y1=14 y2=14></line> <line class=ql-stroke x1=3 x2=9 y1=4 y2=4></line> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=15 x2=3 y1=9 y2=9></line> <line class=ql-stroke x1=14 x2=4 y1=14 y2=14></line> <line class=ql-stroke x1=12 x2=6 y1=4 y2=4></line> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=15 x2=3 y1=9 y2=9></line> <line class=ql-stroke x1=15 x2=5 y1=14 y2=14></line> <line class=ql-stroke x1=15 x2=9 y1=4 y2=4></line> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=15 x2=3 y1=9 y2=9></line> <line class=ql-stroke x1=15 x2=3 y1=14 y2=14></line> <line class=ql-stroke x1=15 x2=3 y1=4 y2=4></line> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <g class="ql-fill ql-color-label"> <polygon points="6 6.868 6 6 5 6 5 7 5.942 7 6 6.868"></polygon> <rect height=1 width=1 x=4 y=4></rect> <polygon points="6.817 5 6 5 6 6 6.38 6 6.817 5"></polygon> <rect height=1 width=1 x=2 y=6></rect> <rect height=1 width=1 x=3 y=5></rect> <rect height=1 width=1 x=4 y=7></rect> <polygon points="4 11.439 4 11 3 11 3 12 3.755 12 4 11.439"></polygon> <rect height=1 width=1 x=2 y=12></rect> <rect height=1 width=1 x=2 y=9></rect> <rect height=1 width=1 x=2 y=15></rect> <polygon points="4.63 10 4 10 4 11 4.192 11 4.63 10"></polygon> <rect height=1 width=1 x=3 y=8></rect> <path d=M10.832,4.2L11,4.582V4H10.708A1.948,1.948,0,0,1,10.832,4.2Z></path> <path d=M7,4.582L7.168,4.2A1.929,1.929,0,0,1,7.292,4H7V4.582Z></path> <path d=M8,13H7.683l-0.351.8a1.933,1.933,0,0,1-.124.2H8V13Z></path> <rect height=1 width=1 x=12 y=2></rect> <rect height=1 width=1 x=11 y=3></rect> <path d=M9,3H8V3.282A1.985,1.985,0,0,1,9,3Z></path> <rect height=1 width=1 x=2 y=3></rect> <rect height=1 width=1 x=6 y=2></rect> <rect height=1 width=1 x=3 y=2></rect> <rect height=1 width=1 x=5 y=3></rect> <rect height=1 width=1 x=9 y=2></rect> <rect height=1 width=1 x=15 y=14></rect> <polygon points="13.447 10.174 13.469 10.225 13.472 10.232 13.808 11 14 11 14 10 13.37 10 13.447 10.174"></polygon> <rect height=1 width=1 x=13 y=7></rect> <rect height=1 width=1 x=15 y=5></rect> <rect height=1 width=1 x=14 y=6></rect> <rect height=1 width=1 x=15 y=8></rect> <rect height=1 width=1 x=14 y=9></rect> <path d=M3.775,14H3v1H4V14.314A1.97,1.97,0,0,1,3.775,14Z></path> <rect height=1 width=1 x=14 y=3></rect> <polygon points="12 6.868 12 6 11.62 6 12 6.868"></polygon> <rect height=1 width=1 x=15 y=2></rect> <rect height=1 width=1 x=12 y=5></rect> <rect height=1 width=1 x=13 y=4></rect> <polygon points="12.933 9 13 9 13 8 12.495 8 12.933 9"></polygon> <rect height=1 width=1 x=9 y=14></rect> <rect height=1 width=1 x=8 y=15></rect> <path d=M6,14.926V15H7V14.316A1.993,1.993,0,0,1,6,14.926Z></path> <rect height=1 width=1 x=5 y=15></rect> <path d=M10.668,13.8L10.317,13H10v1h0.792A1.947,1.947,0,0,1,10.668,13.8Z></path> <rect height=1 width=1 x=11 y=15></rect> <path d=M14.332,12.2a1.99,1.99,0,0,1,.166.8H15V12H14.245Z></path> <rect height=1 width=1 x=14 y=15></rect> <rect height=1 width=1 x=15 y=11></rect> </g> <polyline class=ql-stroke points="5.5 13 9 5 12.5 13"></polyline> <line class=ql-stroke x1=11.63 x2=6.38 y1=11 y2=11></line> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <rect class="ql-fill ql-stroke" height=3 width=3 x=4 y=5></rect> <rect class="ql-fill ql-stroke" height=3 width=3 x=11 y=5></rect> <path class="ql-even ql-fill ql-stroke" d=M7,8c0,4.031-3,5-3,5></path> <path class="ql-even ql-fill ql-stroke" d=M14,8c0,4.031-3,5-3,5></path> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-stroke d=M5,4H9.5A2.5,2.5,0,0,1,12,6.5v0A2.5,2.5,0,0,1,9.5,9H5A0,0,0,0,1,5,9V4A0,0,0,0,1,5,4Z></path> <path class=ql-stroke d=M5,9h5.5A2.5,2.5,0,0,1,13,11.5v0A2.5,2.5,0,0,1,10.5,14H5a0,0,0,0,1,0,0V9A0,0,0,0,1,5,9Z></path> </svg>'},function(t,e){
t.exports='<svg class="" viewbox="0 0 18 18"> <line class=ql-stroke x1=5 x2=13 y1=3 y2=3></line> <line class=ql-stroke x1=6 x2=9.35 y1=12 y2=3></line> <line class=ql-stroke x1=11 x2=15 y1=11 y2=15></line> <line class=ql-stroke x1=15 x2=11 y1=11 y2=15></line> <rect class=ql-fill height=1 rx=0.5 ry=0.5 width=7 x=2 y=14></rect> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class="ql-color-label ql-stroke ql-transparent" x1=3 x2=15 y1=15 y2=15></line> <polyline class=ql-stroke points="5.5 11 9 3 12.5 11"></polyline> <line class=ql-stroke x1=11.63 x2=6.38 y1=9 y2=9></line> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <polygon class="ql-stroke ql-fill" points="3 11 5 9 3 7 3 11"></polygon> <line class="ql-stroke ql-fill" x1=15 x2=11 y1=4 y2=4></line> <path class=ql-fill d=M11,3a3,3,0,0,0,0,6h1V3H11Z></path> <rect class=ql-fill height=11 width=1 x=11 y=4></rect> <rect class=ql-fill height=11 width=1 x=13 y=4></rect> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <polygon class="ql-stroke ql-fill" points="15 12 13 10 15 8 15 12"></polygon> <line class="ql-stroke ql-fill" x1=9 x2=5 y1=4 y2=4></line> <path class=ql-fill d=M5,3A3,3,0,0,0,5,9H6V3H5Z></path> <rect class=ql-fill height=11 width=1 x=5 y=4></rect> <rect class=ql-fill height=11 width=1 x=7 y=4></rect> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-fill d=M14,16H4a1,1,0,0,1,0-2H14A1,1,0,0,1,14,16Z /> <path class=ql-fill d=M14,4H4A1,1,0,0,1,4,2H14A1,1,0,0,1,14,4Z /> <rect class=ql-fill x=3 y=6 width=12 height=6 rx=1 ry=1 /> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-fill d=M13,16H5a1,1,0,0,1,0-2h8A1,1,0,0,1,13,16Z /> <path class=ql-fill d=M13,4H5A1,1,0,0,1,5,2h8A1,1,0,0,1,13,4Z /> <rect class=ql-fill x=2 y=6 width=14 height=6 rx=1 ry=1 /> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-fill d=M15,8H13a1,1,0,0,1,0-2h2A1,1,0,0,1,15,8Z /> <path class=ql-fill d=M15,12H13a1,1,0,0,1,0-2h2A1,1,0,0,1,15,12Z /> <path class=ql-fill d=M15,16H5a1,1,0,0,1,0-2H15A1,1,0,0,1,15,16Z /> <path class=ql-fill d=M15,4H5A1,1,0,0,1,5,2H15A1,1,0,0,1,15,4Z /> <rect class=ql-fill x=2 y=6 width=8 height=6 rx=1 ry=1 /> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-fill d=M5,8H3A1,1,0,0,1,3,6H5A1,1,0,0,1,5,8Z /> <path class=ql-fill d=M5,12H3a1,1,0,0,1,0-2H5A1,1,0,0,1,5,12Z /> <path class=ql-fill d=M13,16H3a1,1,0,0,1,0-2H13A1,1,0,0,1,13,16Z /> <path class=ql-fill d=M13,4H3A1,1,0,0,1,3,2H13A1,1,0,0,1,13,4Z /> <rect class=ql-fill x=8 y=6 width=8 height=6 rx=1 ry=1 transform="translate(24 18) rotate(-180)"/> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-fill d=M11.759,2.482a2.561,2.561,0,0,0-3.53.607A7.656,7.656,0,0,0,6.8,6.2C6.109,9.188,5.275,14.677,4.15,14.927a1.545,1.545,0,0,0-1.3-.933A0.922,0.922,0,0,0,2,15.036S1.954,16,4.119,16s3.091-2.691,3.7-5.553c0.177-.826.36-1.726,0.554-2.6L8.775,6.2c0.381-1.421.807-2.521,1.306-2.676a1.014,1.014,0,0,0,1.02.56A0.966,0.966,0,0,0,11.759,2.482Z></path> <rect class=ql-fill height=1.6 rx=0.8 ry=0.8 width=5 x=5.15 y=6.2></rect> <path class=ql-fill d=M13.663,12.027a1.662,1.662,0,0,1,.266-0.276q0.193,0.069.456,0.138a2.1,2.1,0,0,0,.535.069,1.075,1.075,0,0,0,.767-0.3,1.044,1.044,0,0,0,.314-0.8,0.84,0.84,0,0,0-.238-0.619,0.8,0.8,0,0,0-.594-0.239,1.154,1.154,0,0,0-.781.3,4.607,4.607,0,0,0-.781,1q-0.091.15-.218,0.346l-0.246.38c-0.068-.288-0.137-0.582-0.212-0.885-0.459-1.847-2.494-.984-2.941-0.8-0.482.2-.353,0.647-0.094,0.529a0.869,0.869,0,0,1,1.281.585c0.217,0.751.377,1.436,0.527,2.038a5.688,5.688,0,0,1-.362.467,2.69,2.69,0,0,1-.264.271q-0.221-.08-0.471-0.147a2.029,2.029,0,0,0-.522-0.066,1.079,1.079,0,0,0-.768.3A1.058,1.058,0,0,0,9,15.131a0.82,0.82,0,0,0,.832.852,1.134,1.134,0,0,0,.787-0.3,5.11,5.11,0,0,0,.776-0.993q0.141-.219.215-0.34c0.046-.076.122-0.194,0.223-0.346a2.786,2.786,0,0,0,.918,1.726,2.582,2.582,0,0,0,2.376-.185c0.317-.181.212-0.565,0-0.494A0.807,0.807,0,0,1,14.176,15a5.159,5.159,0,0,1-.913-2.446l0,0Q13.487,12.24,13.663,12.027Z></path> </svg>'},function(t,e){t.exports='<svg viewBox="0 0 18 18"> <path class=ql-fill d=M10,4V14a1,1,0,0,1-2,0V10H3v4a1,1,0,0,1-2,0V4A1,1,0,0,1,3,4V8H8V4a1,1,0,0,1,2,0Zm6.06787,9.209H14.98975V7.59863a.54085.54085,0,0,0-.605-.60547h-.62744a1.01119,1.01119,0,0,0-.748.29688L11.645,8.56641a.5435.5435,0,0,0-.022.8584l.28613.30762a.53861.53861,0,0,0,.84717.0332l.09912-.08789a1.2137,1.2137,0,0,0,.2417-.35254h.02246s-.01123.30859-.01123.60547V13.209H12.041a.54085.54085,0,0,0-.605.60547v.43945a.54085.54085,0,0,0,.605.60547h4.02686a.54085.54085,0,0,0,.605-.60547v-.43945A.54085.54085,0,0,0,16.06787,13.209Z /> </svg>'},function(t,e){t.exports='<svg viewBox="0 0 18 18"> <path class=ql-fill d=M16.73975,13.81445v.43945a.54085.54085,0,0,1-.605.60547H11.855a.58392.58392,0,0,1-.64893-.60547V14.0127c0-2.90527,3.39941-3.42187,3.39941-4.55469a.77675.77675,0,0,0-.84717-.78125,1.17684,1.17684,0,0,0-.83594.38477c-.2749.26367-.561.374-.85791.13184l-.4292-.34082c-.30811-.24219-.38525-.51758-.1543-.81445a2.97155,2.97155,0,0,1,2.45361-1.17676,2.45393,2.45393,0,0,1,2.68408,2.40918c0,2.45312-3.1792,2.92676-3.27832,3.93848h2.79443A.54085.54085,0,0,1,16.73975,13.81445ZM9,3A.99974.99974,0,0,0,8,4V8H3V4A1,1,0,0,0,1,4V14a1,1,0,0,0,2,0V10H8v4a1,1,0,0,0,2,0V4A.99974.99974,0,0,0,9,3Z /> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=7 x2=13 y1=4 y2=4></line> <line class=ql-stroke x1=5 x2=11 y1=14 y2=14></line> <line class=ql-stroke x1=8 x2=10 y1=14 y2=4></line> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <rect class=ql-stroke height=10 width=12 x=3 y=4></rect> <circle class=ql-fill cx=6 cy=7 r=1></circle> <polyline class="ql-even ql-fill" points="5 12 5 11 7 9 8 10 11 7 13 9 13 12 5 12"></polyline> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=3 x2=15 y1=14 y2=14></line> <line class=ql-stroke x1=3 x2=15 y1=4 y2=4></line> <line class=ql-stroke x1=9 x2=15 y1=9 y2=9></line> <polyline class="ql-fill ql-stroke" points="3 7 3 11 5 9 3 7"></polyline> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=3 x2=15 y1=14 y2=14></line> <line class=ql-stroke x1=3 x2=15 y1=4 y2=4></line> <line class=ql-stroke x1=9 x2=15 y1=9 y2=9></line> <polyline class=ql-stroke points="5 7 5 11 3 9 5 7"></polyline> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=7 x2=11 y1=7 y2=11></line> <path class="ql-even ql-stroke" d=M8.9,4.577a3.476,3.476,0,0,1,.36,4.679A3.476,3.476,0,0,1,4.577,8.9C3.185,7.5,2.035,6.4,4.217,4.217S7.5,3.185,8.9,4.577Z></path> <path class="ql-even ql-stroke" d=M13.423,9.1a3.476,3.476,0,0,0-4.679-.36,3.476,3.476,0,0,0,.36,4.679c1.392,1.392,2.5,2.542,4.679.36S14.815,10.5,13.423,9.1Z></path> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=7 x2=15 y1=4 y2=4></line> <line class=ql-stroke x1=7 x2=15 y1=9 y2=9></line> <line class=ql-stroke x1=7 x2=15 y1=14 y2=14></line> <line class="ql-stroke ql-thin" x1=2.5 x2=4.5 y1=5.5 y2=5.5></line> <path class=ql-fill d=M3.5,6A0.5,0.5,0,0,1,3,5.5V3.085l-0.276.138A0.5,0.5,0,0,1,2.053,3c-0.124-.247-0.023-0.324.224-0.447l1-.5A0.5,0.5,0,0,1,4,2.5v3A0.5,0.5,0,0,1,3.5,6Z></path> <path class="ql-stroke ql-thin" d=M4.5,10.5h-2c0-.234,1.85-1.076,1.85-2.234A0.959,0.959,0,0,0,2.5,8.156></path> <path class="ql-stroke ql-thin" d=M2.5,14.846a0.959,0.959,0,0,0,1.85-.109A0.7,0.7,0,0,0,3.75,14a0.688,0.688,0,0,0,.6-0.736,0.959,0.959,0,0,0-1.85-.109></path> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class=ql-stroke x1=6 x2=15 y1=4 y2=4></line> <line class=ql-stroke x1=6 x2=15 y1=9 y2=9></line> <line class=ql-stroke x1=6 x2=15 y1=14 y2=14></line> <line class=ql-stroke x1=3 x2=3 y1=4 y2=4></line> <line class=ql-stroke x1=3 x2=3 y1=9 y2=9></line> <line class=ql-stroke x1=3 x2=3 y1=14 y2=14></line> </svg>'},function(t,e){t.exports='<svg class="" viewbox="0 0 18 18"> <line class=ql-stroke x1=9 x2=15 y1=4 y2=4></line> <polyline class=ql-stroke points="3 4 4 5 6 3"></polyline> <line class=ql-stroke x1=9 x2=15 y1=14 y2=14></line> <polyline class=ql-stroke points="3 14 4 15 6 13"></polyline> <line class=ql-stroke x1=9 x2=15 y1=9 y2=9></line> <polyline class=ql-stroke points="3 9 4 10 6 8"></polyline> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-fill d=M15.5,15H13.861a3.858,3.858,0,0,0,1.914-2.975,1.8,1.8,0,0,0-1.6-1.751A1.921,1.921,0,0,0,12.021,11.7a0.50013,0.50013,0,1,0,.957.291h0a0.914,0.914,0,0,1,1.053-.725,0.81,0.81,0,0,1,.744.762c0,1.076-1.16971,1.86982-1.93971,2.43082A1.45639,1.45639,0,0,0,12,15.5a0.5,0.5,0,0,0,.5.5h3A0.5,0.5,0,0,0,15.5,15Z /> <path class=ql-fill d=M9.65,5.241a1,1,0,0,0-1.409.108L6,7.964,3.759,5.349A1,1,0,0,0,2.192,6.59178Q2.21541,6.6213,2.241,6.649L4.684,9.5,2.241,12.35A1,1,0,0,0,3.71,13.70722q0.02557-.02768.049-0.05722L6,11.036,8.241,13.65a1,1,0,1,0,1.567-1.24277Q9.78459,12.3777,9.759,12.35L7.316,9.5,9.759,6.651A1,1,0,0,0,9.65,5.241Z /> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-fill d=M15.5,7H13.861a4.015,4.015,0,0,0,1.914-2.975,1.8,1.8,0,0,0-1.6-1.751A1.922,1.922,0,0,0,12.021,3.7a0.5,0.5,0,1,0,.957.291,0.917,0.917,0,0,1,1.053-.725,0.81,0.81,0,0,1,.744.762c0,1.077-1.164,1.925-1.934,2.486A1.423,1.423,0,0,0,12,7.5a0.5,0.5,0,0,0,.5.5h3A0.5,0.5,0,0,0,15.5,7Z /> <path class=ql-fill d=M9.651,5.241a1,1,0,0,0-1.41.108L6,7.964,3.759,5.349a1,1,0,1,0-1.519,1.3L4.683,9.5,2.241,12.35a1,1,0,1,0,1.519,1.3L6,11.036,8.241,13.65a1,1,0,0,0,1.519-1.3L7.317,9.5,9.759,6.651A1,1,0,0,0,9.651,5.241Z /> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <line class="ql-stroke ql-thin" x1=15.5 x2=2.5 y1=8.5 y2=9.5></line> <path class=ql-fill d=M9.007,8C6.542,7.791,6,7.519,6,6.5,6,5.792,7.283,5,9,5c1.571,0,2.765.679,2.969,1.309a1,1,0,0,0,1.9-.617C13.356,4.106,11.354,3,9,3,6.2,3,4,4.538,4,6.5a3.2,3.2,0,0,0,.5,1.843Z></path> <path class=ql-fill d=M8.984,10C11.457,10.208,12,10.479,12,11.5c0,0.708-1.283,1.5-3,1.5-1.571,0-2.765-.679-2.969-1.309a1,1,0,1,0-1.9.617C4.644,13.894,6.646,15,9,15c2.8,0,5-1.538,5-3.5a3.2,3.2,0,0,0-.5-1.843Z></path> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <path class=ql-stroke d=M5,3V9a4.012,4.012,0,0,0,4,4H9a4.012,4.012,0,0,0,4-4V3></path> <rect class=ql-fill height=1 rx=0.5 ry=0.5 width=12 x=3 y=15></rect> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <rect class=ql-stroke height=12 width=12 x=3 y=3></rect> <rect class=ql-fill height=12 width=1 x=5 y=3></rect> <rect class=ql-fill height=12 width=1 x=12 y=3></rect> <rect class=ql-fill height=2 width=8 x=5 y=8></rect> <rect class=ql-fill height=1 width=3 x=3 y=5></rect> <rect class=ql-fill height=1 width=3 x=3 y=7></rect> <rect class=ql-fill height=1 width=3 x=3 y=10></rect> <rect class=ql-fill height=1 width=3 x=3 y=12></rect> <rect class=ql-fill height=1 width=3 x=12 y=5></rect> <rect class=ql-fill height=1 width=3 x=12 y=7></rect> <rect class=ql-fill height=1 width=3 x=12 y=10></rect> <rect class=ql-fill height=1 width=3 x=12 y=12></rect> </svg>'},function(t,e){t.exports='<svg viewbox="0 0 18 18"> <polygon class=ql-stroke points="7 11 9 13 11 11 7 11"></polygon> <polygon class=ql-stroke points="7 7 9 5 11 7 7 7"></polygon> </svg>'},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function a(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0}),e.default=e.BubbleTooltip=void 0;var s=function t(e,n,r){null===e&&(e=Function.prototype);var i=Object.getOwnPropertyDescriptor(e,n);if(void 0===i){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,n,r)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(r):void 0},l=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),c=r(n(3)),u=r(n(8)),f=n(43),d=r(f),h=n(15),p=r(n(41)),v=[["bold","italic","link"],[{header:1},{header:2},"blockquote"]],g=function(t){function e(t,n){i(this,e),null!=n.modules.toolbar&&null==n.modules.toolbar.container&&(n.modules.toolbar.container=v);var r=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.quill.container.classList.add("ql-bubble"),r}return a(e,d.default),l(e,[{key:"extendToolbar",value:function(t){this.tooltip=new m(this.quill,this.options.bounds),this.tooltip.root.appendChild(t.container),this.buildButtons([].slice.call(t.container.querySelectorAll("button")),p.default),this.buildPickers([].slice.call(t.container.querySelectorAll("select")),p.default)}}]),e}();g.DEFAULTS=(0,c.default)(!0,{},d.default.DEFAULTS,{modules:{toolbar:{handlers:{link:function(t){t?this.quill.theme.tooltip.edit():this.quill.format("link",!1)}}}}});var m=function(t){function e(t,n){i(this,e);var r=o(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,n));return r.quill.on(u.default.events.EDITOR_CHANGE,function(t,e,n,i){if(t===u.default.events.SELECTION_CHANGE)if(null!=e&&e.length>0&&i===u.default.sources.USER){r.show(),r.root.style.left="0px",r.root.style.width="",r.root.style.width=r.root.offsetWidth+"px";var o=r.quill.getLines(e.index,e.length);if(1===o.length)r.position(r.quill.getBounds(e));else{var a=o[o.length-1],s=r.quill.getIndex(a),l=Math.min(a.length()-1,e.index+e.length-s),c=r.quill.getBounds(new h.Range(s,l));r.position(c)}}else document.activeElement!==r.textbox&&r.quill.hasFocus()&&r.hide()}),r}return a(e,f.BaseTooltip),l(e,[{key:"listen",value:function(){var t=this;s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"listen",this).call(this),this.root.querySelector(".ql-close").addEventListener("click",function(){t.root.classList.remove("ql-editing")}),this.quill.on(u.default.events.SCROLL_OPTIMIZE,function(){setTimeout(function(){if(!t.root.classList.contains("ql-hidden")){var e=t.quill.getSelection();null!=e&&t.position(t.quill.getBounds(e))}},1)})}},{key:"cancel",value:function(){this.show()}},{key:"position",value:function(t){var n=s(e.prototype.__proto__||Object.getPrototypeOf(e.prototype),"position",this).call(this,t),r=this.root.querySelector(".ql-tooltip-arrow");if(r.style.marginLeft="",0===n)return n;r.style.marginLeft=-1*n-r.offsetWidth/2+"px"}}]),e}();m.TEMPLATE=['<span class="ql-tooltip-arrow"></span>','<div class="ql-tooltip-editor">','<input type="text" data-formula="e=mc^2" data-link="https://quilljs.com" data-video="Embed URL">','<a class="ql-close"></a>',"</div>"].join(""),e.BubbleTooltip=m,e.default=g},function(t,e,n){t.exports=n(63)}]).default},t.exports=n()}).call(e,n("EuP9").Buffer)},z9ch:function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n("fhbW"),i=n("IW2Z"),o=n.n(i);e.default={components:{fileUpload:o.a},props:{resource:{required:!0,type:Object},resourceType:{required:!0,type:String},activeTab:{required:!0,type:String}},data:function(){return{faEllipsisH:r.l,faFileAlt:r.n,faFileImage:r.o,faFilePdf:r.p}}}},zqwX:function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return t.suggestionShown&&t.sortedUsers.length>0?n("div",{staticClass:"autocomplete container w-full shadow-md",class:t.suggestionHighlightDirectionInverted?"rounded-t-lg":"rounded-b-lg"},[n("div",{staticClass:"autocomplete-results"},t._l(t.sortedUsers,function(e,r){return n("div",{key:r,staticClass:"autocomplete-result flex items-center bg-white p-1 cursor-pointer hover:bg-grey-light",class:{"text-white bg-teal hover:bg-teal-dark":r===t.highlightIndex,"rounded-t-lg":0===r&&t.suggestionHighlightDirectionInverted,"rounded-b-lg":r===t.sortedUsers.length-1&&!t.suggestionHighlightDirectionInverted},on:{click:function(n){t.selectUser(e[1].target)}}},[n("div",{staticClass:"mx-2"},[n("img",{staticClass:"rounded-full align-middle w-8 h-8",attrs:{src:"/"+t.getUserAvatar(e[1].target)}})]),t._v(" "),n("div",{staticClass:"mr-2"},[n("span",{staticClass:"font-semibold"},[t._v("@"+t._s(e[1].target))]),t._v(" ("+t._s(e[0].target)+")\n ")])])}))]):t._e()},staticRenderFns:[]}}},[5]); |
|
utils.py | import pyperclip
import pandas as pd
from modulos.conecao import *
def copiar(objeto): # função para copiar os objetos para área de transferência
glob | f select(sql): # função que decta qual tipo de ação eu desejo fazer
try:
df = pd.read_sql_query(sql, con=engine).to_string(index=False)
finally:
pass
return df
| al copiar # para resolver o porblema UnboundLocalError: local variable 'copiar' referenced before assignment:
opcao = int(input('Deseja copiar para área de transferência? "1" para sim e qualquer tecla para não\n\nR: '))
if opcao == 1:
copiar = pyperclip.copy(objeto)
print('\nCopiado com sucesso!')
else:
pass
return copiar
de |
corelib.py | import ctypes
import llvmlite.ir as ir
from CodeGen import LLVMCodeGenerator
from coretypes import *
from scopes import Scope
from typelib import *
ZERO = ir.Constant(ir.IntType(64), 0)
def _eq_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fcmp_ordered("==", args[0], args[1])
def _neq_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fcmp_ordered("!=", args[0], args[1])
def _eq_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.icmp_signed("==", args[0], args[1])
def _neq_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.icmp_signed("!=", args[0], args[1])
def _lt_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fcmp_ordered("<", args[0], args[1])
def _gt_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fcmp_ordered(">", args[0], args[1])
def _lte_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fcmp_ordered("<=", args[0], args[1])
def _gte_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fcmp_ordered(">=", args[0], args[1])
def _lt_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.icmp_signed("<", args[0], args[1])
def _gt_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.icmp_signed(">", args[0], args[1])
def _lte_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.icmp_signed("<=", args[0], args[1])
def _gte_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.icmp_signed(">=", args[0], args[1])
| return cg.builder.add(args[0], args[1])
def _sub_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.sub(args[0], args[1])
def _mul_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.mul(args[0], args[1])
def _div_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.sdiv(args[0], args[1])
def _rem_Int(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.srem(args[0], args[1])
def _add_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fadd(args[0], args[1])
def _sub_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fsub(args[0], args[1])
def _mul_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fmul(args[0], args[1])
def _div_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.fdiv(args[0], args[1])
def _rem_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.frem(args[0], args[1])
def _pow_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.call(ir.Function(cg.module, ir.FunctionType(arg_types[0], arg_types), "pow"), args)
def _abs_Float(cg: LLVMCodeGenerator, args, arg_types):
return cg.builder.call(ir.Function(cg.module, ir.FunctionType(arg_types[0], arg_types), "fabs"), args)
def _index(cg: LLVMCodeGenerator, args, arg_types):
arr_ptr, index = args
return cg.builder.gep(arr_ptr, [ZERO, index])
scope = Scope()
scope.add_type(Array)
scope.add_type(Bool)
scope.add_type(Float)
scope.add_type(Int)
# Equalities
scope.add_function(FunctionType("==", [Bool, Bool], Bool, _eq_Int))
scope.add_function(FunctionType("!=", [Bool, Bool], Bool, _neq_Int))
scope.add_function(FunctionType("==", [Float, Float], Bool, _eq_Float))
scope.add_function(FunctionType("!=", [Float, Float], Bool, _neq_Float))
scope.add_function(FunctionType("==", [Int, Int], Bool, _eq_Int))
scope.add_function(FunctionType("!=", [Int, Int], Bool, _neq_Int))
# Comparisons
scope.add_function(FunctionType("<", [Float, Float], Bool, _lt_Float))
scope.add_function(FunctionType(">", [Float, Float], Bool, _gt_Float))
scope.add_function(FunctionType("<=", [Float, Float], Bool, _lte_Float))
scope.add_function(FunctionType(">=", [Float, Float], Bool, _gte_Float))
scope.add_function(FunctionType("<", [Int, Int], Bool, _lt_Int))
scope.add_function(FunctionType(">", [Int, Int], Bool, _gt_Int))
scope.add_function(FunctionType("<=", [Int, Int], Bool, _lte_Int))
scope.add_function(FunctionType(">=", [Int, Int], Bool, _gte_Int))
# Math Operators
scope.add_function(FunctionType("+", [Float, Float], Float, _add_Float))
scope.add_function(FunctionType("-", [Float, Float], Float, _sub_Float))
scope.add_function(FunctionType("*", [Float, Float], Float, _mul_Float))
scope.add_function(FunctionType("/", [Float, Float], Float, _div_Float))
scope.add_function(FunctionType("%", [Float, Float], Float, _rem_Float))
scope.add_function(FunctionType("^", [Float, Float], Float, _pow_Float))
scope.add_function(FunctionType("+", [Int, Int], Int, _add_Int))
scope.add_function(FunctionType("-", [Int, Int], Int, _sub_Int))
scope.add_function(FunctionType("*", [Int, Int], Int, _mul_Int))
scope.add_function(FunctionType("/", [Int, Int], Int, _div_Int))
scope.add_function(FunctionType("%", [Int, Int], Int, _rem_Int))
# Math Functions
scope.add_function(FunctionType("abs", [Float], Float, _abs_Float, no_mangle=True))
scope.add_function(FunctionType("floor", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("ceil", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("round", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("sqrt", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("exp", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("log", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("log10", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("log2", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("sin", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("cos", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("tan", [Float], Float, no_mangle=True))
scope.add_function(FunctionType("index", [Type("Array", [Bool], ['N']), Int], Bool.to_ref(), _index))
scope.add_function(FunctionType("index", [Type("Array", [Int], ['N']), Int], Int.to_ref(), _index))
scope.add_function(FunctionType("index", [Type("Array", [Float], ['N']), Int], Float.to_ref(), _index))
scope.add_function(FunctionType("putchar", [Int], Int, no_mangle=True))
# scope.add_function(FunctionType("sum", [Type("Array", [Int], ['N'])], Int)) | def _add_Int(cg: LLVMCodeGenerator, args, arg_types): |
root.go | package cmd
import (
"fmt"
"os"
"time"
homedir "github.com/mitchellh/go-homedir"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var cfg tmConfig
type tmConfig struct {
TimeZone string
}
var verbose, debug bool // for verbose and debug output
// rootCmd represents the root command
var rootCmd = &cobra.Command{
Use: "tblmonit",
Short: "Monitoring tool for Bigquery tables",
Long: `Monitoring BigQuery table metadata to ensure the data pipeline jobs are correctly worked.`,
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".tblmonit" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".tblmonit")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is not found, skip to set timezone.
if err := viper.ReadInConfig(); err == nil {
err := viper.Unmarshal(&cfg)
if err != nil {
fmt.Println("Failed to read Config File", viper.ConfigFileUsed(), err)
os.Exit(1)
}
}
err := loadTimezone()
if err != nil {
fmt.Printf("Failed to load timezone: %v\n", err)
os.Exit(1)
}
logOutput()
}
func loadTimezone() error {
if cfg.TimeZone == "" {
return nil
}
loc, err := time.LoadLocation(cfg.TimeZone)
if err != nil {
return fmt.Errorf("Failed to load location from config file: %s", cfg.TimeZone)
}
time.Local = loc
return nil
}
func | () {
zerolog.SetGlobalLevel(zerolog.Disabled) // default: quiet mode
switch {
case verbose:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
case debug:
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.tblmonit.yaml)")
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
// for log output
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "enable varbose log output")
rootCmd.PersistentFlags().BoolVar(&debug, "debug", false, "enable debug log output")
}
| logOutput |
loadBalancer.ts | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs, enums } from "../../types";
import * as utilities from "../../utilities";
/**
* LoadBalancer resource
*/
export class LoadBalancer extends pulumi.CustomResource {
/**
* Get an existing LoadBalancer resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, opts?: pulumi.CustomResourceOptions): LoadBalancer {
return new LoadBalancer(name, undefined as any, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'azure-native:network/v20160330:LoadBalancer';
/**
* Returns true if the given object is an instance of LoadBalancer. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is LoadBalancer {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === LoadBalancer.__pulumiType;
}
/**
* Gets or sets Pools of backend IP addresses
*/
public readonly backendAddressPools!: pulumi.Output<outputs.network.v20160330.BackendAddressPoolResponse[] | undefined>;
/**
* Gets a unique read-only string that changes whenever the resource is updated
*/
public readonly etag!: pulumi.Output<string | undefined>;
/**
* Gets or sets frontend IP addresses of the load balancer
*/
public readonly frontendIPConfigurations!: pulumi.Output<outputs.network.v20160330.FrontendIPConfigurationResponse[] | undefined>;
/**
* Gets or sets inbound NAT pools
*/
public readonly inboundNatPools!: pulumi.Output<outputs.network.v20160330.InboundNatPoolResponse[] | undefined>;
/**
* Gets or sets list of inbound rules
*/
public readonly inboundNatRules!: pulumi.Output<outputs.network.v20160330.InboundNatRuleResponse[] | undefined>;
/**
* Gets or sets load balancing rules
*/
public readonly loadBalancingRules!: pulumi.Output<outputs.network.v20160330.LoadBalancingRuleResponse[] | undefined>;
/**
* Resource location
*/
public readonly location!: pulumi.Output<string | undefined>;
/**
* Resource name
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* Gets or sets outbound NAT rules
*/
public readonly outboundNatRules!: pulumi.Output<outputs.network.v20160330.OutboundNatRuleResponse[] | undefined>;
/**
* Gets or sets list of Load balancer probes
*/
public readonly probes!: pulumi.Output<outputs.network.v20160330.ProbeResponse[] | undefined>;
/**
* Gets or sets Provisioning state of the PublicIP resource Updating/Deleting/Failed
*/
public readonly provisioningState!: pulumi.Output<string | undefined>;
/**
* Gets or sets resource GUID property of the Load balancer resource
*/
public readonly resourceGuid!: pulumi.Output<string | undefined>;
/**
* Resource tags
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Resource type
*/
public /*out*/ readonly type!: pulumi.Output<string>;
/**
* Create a LoadBalancer resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: LoadBalancerArgs, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (!opts.id) {
if ((!args || args.resourceGroupName === undefined) && !opts.urn) {
throw new Error("Missing required property 'resourceGroupName'");
}
inputs["backendAddressPools"] = args ? args.backendAddressPools : undefined;
inputs["etag"] = args ? args.etag : undefined;
inputs["frontendIPConfigurations"] = args ? args.frontendIPConfigurations : undefined;
inputs["id"] = args ? args.id : undefined;
inputs["inboundNatPools"] = args ? args.inboundNatPools : undefined;
inputs["inboundNatRules"] = args ? args.inboundNatRules : undefined;
inputs["loadBalancerName"] = args ? args.loadBalancerName : undefined;
inputs["loadBalancingRules"] = args ? args.loadBalancingRules : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["outboundNatRules"] = args ? args.outboundNatRules : undefined;
inputs["probes"] = args ? args.probes : undefined;
inputs["provisioningState"] = args ? args.provisioningState : undefined;
inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined;
inputs["resourceGuid"] = args ? args.resourceGuid : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["name"] = undefined /*out*/;
inputs["type"] = undefined /*out*/;
} else { | inputs["etag"] = undefined /*out*/;
inputs["frontendIPConfigurations"] = undefined /*out*/;
inputs["inboundNatPools"] = undefined /*out*/;
inputs["inboundNatRules"] = undefined /*out*/;
inputs["loadBalancingRules"] = undefined /*out*/;
inputs["location"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
inputs["outboundNatRules"] = undefined /*out*/;
inputs["probes"] = undefined /*out*/;
inputs["provisioningState"] = undefined /*out*/;
inputs["resourceGuid"] = undefined /*out*/;
inputs["tags"] = undefined /*out*/;
inputs["type"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
const aliasOpts = { aliases: [{ type: "azure-nextgen:network/v20160330:LoadBalancer" }, { type: "azure-native:network:LoadBalancer" }, { type: "azure-nextgen:network:LoadBalancer" }, { type: "azure-native:network/v20150501preview:LoadBalancer" }, { type: "azure-nextgen:network/v20150501preview:LoadBalancer" }, { type: "azure-native:network/v20150615:LoadBalancer" }, { type: "azure-nextgen:network/v20150615:LoadBalancer" }, { type: "azure-native:network/v20160601:LoadBalancer" }, { type: "azure-nextgen:network/v20160601:LoadBalancer" }, { type: "azure-native:network/v20160901:LoadBalancer" }, { type: "azure-nextgen:network/v20160901:LoadBalancer" }, { type: "azure-native:network/v20161201:LoadBalancer" }, { type: "azure-nextgen:network/v20161201:LoadBalancer" }, { type: "azure-native:network/v20170301:LoadBalancer" }, { type: "azure-nextgen:network/v20170301:LoadBalancer" }, { type: "azure-native:network/v20170601:LoadBalancer" }, { type: "azure-nextgen:network/v20170601:LoadBalancer" }, { type: "azure-native:network/v20170801:LoadBalancer" }, { type: "azure-nextgen:network/v20170801:LoadBalancer" }, { type: "azure-native:network/v20170901:LoadBalancer" }, { type: "azure-nextgen:network/v20170901:LoadBalancer" }, { type: "azure-native:network/v20171001:LoadBalancer" }, { type: "azure-nextgen:network/v20171001:LoadBalancer" }, { type: "azure-native:network/v20171101:LoadBalancer" }, { type: "azure-nextgen:network/v20171101:LoadBalancer" }, { type: "azure-native:network/v20180101:LoadBalancer" }, { type: "azure-nextgen:network/v20180101:LoadBalancer" }, { type: "azure-native:network/v20180201:LoadBalancer" }, { type: "azure-nextgen:network/v20180201:LoadBalancer" }, { type: "azure-native:network/v20180401:LoadBalancer" }, { type: "azure-nextgen:network/v20180401:LoadBalancer" }, { type: "azure-native:network/v20180601:LoadBalancer" }, { type: "azure-nextgen:network/v20180601:LoadBalancer" }, { type: "azure-native:network/v20180701:LoadBalancer" }, { type: "azure-nextgen:network/v20180701:LoadBalancer" }, { type: "azure-native:network/v20180801:LoadBalancer" }, { type: "azure-nextgen:network/v20180801:LoadBalancer" }, { type: "azure-native:network/v20181001:LoadBalancer" }, { type: "azure-nextgen:network/v20181001:LoadBalancer" }, { type: "azure-native:network/v20181101:LoadBalancer" }, { type: "azure-nextgen:network/v20181101:LoadBalancer" }, { type: "azure-native:network/v20181201:LoadBalancer" }, { type: "azure-nextgen:network/v20181201:LoadBalancer" }, { type: "azure-native:network/v20190201:LoadBalancer" }, { type: "azure-nextgen:network/v20190201:LoadBalancer" }, { type: "azure-native:network/v20190401:LoadBalancer" }, { type: "azure-nextgen:network/v20190401:LoadBalancer" }, { type: "azure-native:network/v20190601:LoadBalancer" }, { type: "azure-nextgen:network/v20190601:LoadBalancer" }, { type: "azure-native:network/v20190701:LoadBalancer" }, { type: "azure-nextgen:network/v20190701:LoadBalancer" }, { type: "azure-native:network/v20190801:LoadBalancer" }, { type: "azure-nextgen:network/v20190801:LoadBalancer" }, { type: "azure-native:network/v20190901:LoadBalancer" }, { type: "azure-nextgen:network/v20190901:LoadBalancer" }, { type: "azure-native:network/v20191101:LoadBalancer" }, { type: "azure-nextgen:network/v20191101:LoadBalancer" }, { type: "azure-native:network/v20191201:LoadBalancer" }, { type: "azure-nextgen:network/v20191201:LoadBalancer" }, { type: "azure-native:network/v20200301:LoadBalancer" }, { type: "azure-nextgen:network/v20200301:LoadBalancer" }, { type: "azure-native:network/v20200401:LoadBalancer" }, { type: "azure-nextgen:network/v20200401:LoadBalancer" }, { type: "azure-native:network/v20200501:LoadBalancer" }, { type: "azure-nextgen:network/v20200501:LoadBalancer" }, { type: "azure-native:network/v20200601:LoadBalancer" }, { type: "azure-nextgen:network/v20200601:LoadBalancer" }, { type: "azure-native:network/v20200701:LoadBalancer" }, { type: "azure-nextgen:network/v20200701:LoadBalancer" }, { type: "azure-native:network/v20200801:LoadBalancer" }, { type: "azure-nextgen:network/v20200801:LoadBalancer" }, { type: "azure-native:network/v20201101:LoadBalancer" }, { type: "azure-nextgen:network/v20201101:LoadBalancer" }] };
opts = pulumi.mergeOptions(opts, aliasOpts);
super(LoadBalancer.__pulumiType, name, inputs, opts);
}
}
/**
* The set of arguments for constructing a LoadBalancer resource.
*/
export interface LoadBalancerArgs {
/**
* Gets or sets Pools of backend IP addresses
*/
readonly backendAddressPools?: pulumi.Input<pulumi.Input<inputs.network.v20160330.BackendAddressPoolArgs>[]>;
/**
* Gets a unique read-only string that changes whenever the resource is updated
*/
readonly etag?: pulumi.Input<string>;
/**
* Gets or sets frontend IP addresses of the load balancer
*/
readonly frontendIPConfigurations?: pulumi.Input<pulumi.Input<inputs.network.v20160330.FrontendIPConfigurationArgs>[]>;
/**
* Resource Id
*/
readonly id?: pulumi.Input<string>;
/**
* Gets or sets inbound NAT pools
*/
readonly inboundNatPools?: pulumi.Input<pulumi.Input<inputs.network.v20160330.InboundNatPoolArgs>[]>;
/**
* Gets or sets list of inbound rules
*/
readonly inboundNatRules?: pulumi.Input<pulumi.Input<inputs.network.v20160330.InboundNatRuleArgs>[]>;
/**
* The name of the loadBalancer.
*/
readonly loadBalancerName?: pulumi.Input<string>;
/**
* Gets or sets load balancing rules
*/
readonly loadBalancingRules?: pulumi.Input<pulumi.Input<inputs.network.v20160330.LoadBalancingRuleArgs>[]>;
/**
* Resource location
*/
readonly location?: pulumi.Input<string>;
/**
* Gets or sets outbound NAT rules
*/
readonly outboundNatRules?: pulumi.Input<pulumi.Input<inputs.network.v20160330.OutboundNatRuleArgs>[]>;
/**
* Gets or sets list of Load balancer probes
*/
readonly probes?: pulumi.Input<pulumi.Input<inputs.network.v20160330.ProbeArgs>[]>;
/**
* Gets or sets Provisioning state of the PublicIP resource Updating/Deleting/Failed
*/
readonly provisioningState?: pulumi.Input<string>;
/**
* The name of the resource group.
*/
readonly resourceGroupName: pulumi.Input<string>;
/**
* Gets or sets resource GUID property of the Load balancer resource
*/
readonly resourceGuid?: pulumi.Input<string>;
/**
* Resource tags
*/
readonly tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
} | inputs["backendAddressPools"] = undefined /*out*/; |
main.rs | #![cfg_attr(
all(not(debug_assertions), target_os = "windows"),
windows_subsystem = "windows"
)]
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
web_request,
translate
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
use std::collections::HashMap;
use tauri::api::http::{ HttpRequestBuilder, ResponseType, ClientBuilder, Body, ResponseData };
#[tauri::command]
async fn web_request(
url: String,
method: String,
body: Body,
query: HashMap<String, String>,
headers: HashMap<String, String>,
response_type: ResponseType,
) -> Result<ResponseData, String> {
let method = &method;
let client = ClientBuilder::new().max_redirections(3).build().unwrap();
let mut request_builder = HttpRequestBuilder::new(method, url)
.query(query)
.headers(headers);
if method.eq("POST") {
request_builder = request_builder.body(body);
}
let request = request_builder.response_type(response_type);
if let Ok(response) = client.send(request).await {
if let Ok(result) = response.read().await {
return Ok(result);
}
return Err("response read failed".into());
}
return Err("web request failed".into());
}
#[tauri::command]
async fn | (body: Body) -> Result<ResponseData, String> {
let client = ClientBuilder::new()
.max_redirections(3)
.build()
.unwrap();
let request_builder = HttpRequestBuilder::new("POST", "https://goggletrans.blookers.repl.co/api/translate")
.body(body);
let request = request_builder.response_type(ResponseType::Json);
if let Ok(response) = client.send(request).await {
if let Ok(result) = response.read().await {
return Ok(result);
}
}
return Err("".into());
} | translate |
index.js | /*
* @flow
* Copyright (C) 2018 MetaBrainz Foundation
*
* This file is part of MusicBrainz, the open internet music database,
* and is licensed under the GPL version 2, or (at your option) any
* later version: http://www.gnu.org/licenses/gpl-2.0.txt
*/
import he from 'he';
import * as React from 'react';
import {ArtworkImage} from '../components/Artwork';
import Layout from '../layout';
import {CONTACT_URL} from '../static/scripts/common/constants';
import {reduceArtistCredit}
from '../static/scripts/common/immutable-entities';
import entityHref from '../static/scripts/common/utility/entityHref';
type Props = {
+$c: CatalystContextT,
+blogEntries: $ReadOnlyArray<BlogEntryT> | null,
+newestReleases: $ReadOnlyArray<ArtworkT>,
};
const Homepage = ({
$c,
blogEntries,
newestReleases,
}: Props): React.Element<typeof Layout> => (
<Layout
$c={$c}
fullWidth
homepage
title={l('MusicBrainz - The Open Music Encyclopedia')}
>
<div id="maincontent">
<div id="content">
<h1>{l('Welcome to MusicBrainz!')}</h1>
<p>
{l(
`MusicBrainz is an open music encyclopedia that collects
music metadata and makes it available to the public.`,
)}
</p>
<p>
{l('MusicBrainz aims to be:')}
</p>
<ol>
<li>
{exp.l(
`<strong>The ultimate source of music information</strong>
by allowing anyone to contribute and releasing the {doc|data}
under {doc2|open licenses}.`,
{
doc: '/doc/MusicBrainz_Documentation',
doc2: '/doc/About/Data_License',
},
)}
</li>
<li>
{exp.l(
`<strong>The universal lingua franca for music</strong>
by providing a reliable and unambiguous form of
{doc|music identification}, enabling both people and machines
to have meaningful conversations about music.`,
{
doc: '/doc/MusicBrainz_Identifier',
},
)}
</li>
</ol>
<p>
{exp.l(
`Like Wikipedia, MusicBrainz is maintained by a global community
of users and we want everyone — including you —
to {doc|participate and contribute}.`,
{
doc: '/doc/How_to_Contribute',
},
)}
</p>
<div className="linkbar">
{exp.l(
`{about|More Information} — {faq|FAQs} —
{contact|Contact Us}`,
{
about: '/doc/About',
contact: CONTACT_URL,
faq: '/doc/Frequently_Asked_Questions',
},
)}
</div>
<p>
{exp.l(
`MusicBrainz is operated by the {uri|MetaBrainz Foundation},
a California based 501(c)(3) tax-exempt non-profit corporation
dedicated to keeping MusicBrainz {free|free and open source}.`,
{
free: '/doc/About/Data_License',
uri: 'https://metabrainz.org',
},
)}
</p>
</div>
<div className="sidebar">
<div className="feature-column" id="blog-feed">
<h2>{l('MetaBrainz Blog')}</h2>
{blogEntries?.length ? (
<>
<p style={{margin: '1em 0 0'}}>
<strong>{l('Latest posts:')}</strong>
</p>
<ul style={{margin: '0px', paddingLeft: '20px'}}>
{blogEntries.slice(0, 6).map(item => (
<li key={item.url}>
<a href={item.url}>{he.decode(item.title)}</a>
</li>
))}
</ul>
<p style={{margin: '1em 0', textAlign: 'right'}}>
<strong>
<a href="http://blog.metabrainz.org">
{l('Read more »')}
</a>
</strong>
</p>
</>
) : (
<p style={{margin: '0px', textAlign: 'center'}}>
{l('The blog is currently unavailable.')}
</p>
)}
</div>
</div>
<div className="sidebar">
<div>
<div className="feature-column" id="taggers">
<h2 className="taggers">{l('Tag Your Music')}</h2>
<ul>
<li>
<a href="//picard.musicbrainz.org">
{l('MusicBrainz Picard')}
</a>
</li>
<li>
<a href="/doc/AudioRanger">{l('AudioRanger')}</a>
</li>
<li>
<a href="/doc/Yate_Music_Tagger">{l('Yate Music Tagger')}</a>
</li>
</ul>
</div>
<div className="feature-column" id="quick-start">
<h2>{l('Quick Start')}</h2>
<ul>
<li>
<a href="/doc/Beginners_Guide">{l('Beginners guide')}</a>
</li>
<li>
<a href="/doc/How_Editing_Works">
{l('Editing introduction')}
</a>
</li>
<li>
<a href="/doc/Style">{l('Style guidelines')}</a>
</li>
<li>
<a href="/doc/Frequently_Asked_Questions">{l('FAQs')}</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div id="triple">
<div className="feature-column" id="community">
<h2 className="community">{l('Community')}</h2>
<ul>
<li>
<a href="/doc/How_to_Contribute">{l('How to Contribute')}</a>
</li>
<li>
<a href="http://tickets.metabrainz.org/">{l('Bug Tracker')}</a>
</li>
<li>
<a href="https://community.metabrainz.org/">{l('Forums')}</a>
</li>
</ul>
</div>
<div className="feature-column" id="products">
<h2 className="products">{l('MusicBrainz Database')}</h2>
<p>
<a href="/doc/MusicBrainz_Database">
{exp.l(
`The majority of the data in the
<strong>MusicBrainz Database</strong> is released into
the <strong>Public Domain</strong> and can be | )}
</a>
</p>
</div>
<div className="feature-column" id="developers">
<h2 className="developers">{l('Developers')}</h2>
<p>
<a href="/doc/Developer_Resources">
{exp.l(
`Use our <strong>XML web service</strong> or
<strong>development libraries</strong> to create
your own MusicBrainz-enabled applications.`,
)}
</a>
</p>
</div>
</div>
<div className="feature-column" style={{clear: 'both', paddingTop: '1%'}}>
<h2>{l('Recent Additions')}</h2>
<div style={{height: '160px', overflow: 'hidden'}}>
{newestReleases.map((artwork, index) => (
<ReleaseArtwork
artwork={artwork}
key={index}
/>
))}
</div>
</div>
</Layout>
);
const ReleaseArtwork = ({
artwork,
}: {
+artwork: ArtworkT,
}) => {
const release = artwork.release;
if (!release) {
return null;
}
const releaseDescription = texp.l('{entity} by {artist}', {
artist: reduceArtistCredit(release.artistCredit),
entity: release.name,
});
return (
<div className="artwork-cont" style={{textAlign: 'center'}}>
<div className="artwork">
<a
href={entityHref(release)}
title={releaseDescription}
>
<ArtworkImage
artwork={artwork}
fallback={release.cover_art_url || ''}
/>
</a>
</div>
</div>
);
};
export default Homepage; | downloaded and used <strong>for free</strong>.`, |
bs-config.js | // http://www.browsersync.io/docs/options/
module.exports = {
// uses default browser or you can specify your own choice
// browser: ['google chrome'], | port: 3005,
// proxy: 'localhost:8005',
reloadDelay: 500,
reloadDebounce: 500,
files: [
'public/*.html',
'public/*.json'
// since we are using browser-sync-webpack-plugin
// and webpack is now building js and css, it will trigger reload
// for the following files
// 'dist/main.js',
// 'dist/style.min.css'
],
server: {
baseDir: './public',
routes: {
'/dist': './dist'
}
}
}; | // browser: ['google chrome canary'],
// browser: ['firefox'],
ghostMode: false, |
scheduler.rs | use futures::{
stream::{Fuse, FusedStream},
Stream, StreamExt,
};
use pin_project::pin_project;
use snafu::{Backtrace, ResultExt, Snafu};
use std::{
collections::{hash_map::Entry, HashMap},
hash::Hash,
pin::Pin,
task::{Context, Poll},
};
use crate::time::{
self,
delay_queue::{self, Expired, DelayQueue}
};
use std::time::Instant;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(display("timer failure: {}", source))]
TimerError {
source: time::Error,
backtrace: Backtrace,
},
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// A request to re-emit `message` at a given `Instant` (`run_at`).
#[derive(Debug)]
pub struct ScheduleRequest<T> {
pub message: T,
pub run_at: Instant,
}
/// Internal metadata for a scheduled message.
struct ScheduledEntry {
run_at: Instant,
queue_key: delay_queue::Key,
}
#[pin_project(project = SchedulerProj)]
struct Scheduler<T, R> {
/// Queue of already-scheduled messages.
///
/// To ensure that the metadata is kept up-to-date, use `schedule_message` and
/// `poll_pop_queue_message` rather than manipulating this directly.
queue: DelayQueue<T>,
/// Metadata for all currently scheduled messages. Used to detect duplicate messages.
scheduled: HashMap<T, ScheduledEntry>,
/// Incoming queue of scheduling requests.
#[pin]
requests: Fuse<R>,
}
impl<T, R: Stream> Scheduler<T, R> {
fn new(requests: R) -> Self {
Self {
queue: DelayQueue::new(),
scheduled: HashMap::new(),
requests: requests.fuse(),
}
}
}
impl<T: Hash + Eq + Clone, R> SchedulerProj<'_, T, R> {
/// Attempt to schedule a message into the queue.
///
/// If the message is already in the queue then the earlier `request.run_at` takes precedence.
fn schedule_message(&mut self, request: ScheduleRequest<T>) {
match self.scheduled.entry(request.message) {
Entry::Occupied(mut old_entry) if old_entry.get().run_at >= request.run_at => {
// Old entry will run after the new request, so replace it..
let entry = old_entry.get_mut();
// TODO: this should add a little delay here to actually debounce
self.queue.reset_at(&entry.queue_key, request.run_at);
entry.run_at = request.run_at;
}
Entry::Occupied(_old_entry) => {
// Old entry will run before the new request, so ignore the new request..
}
Entry::Vacant(entry) => {
// No old entry, we're free to go!
let message = entry.key().clone();
entry.insert(ScheduledEntry {
run_at: request.run_at,
queue_key: self.queue.insert_at(message, request.run_at),
});
}
}
}
/// Attempt to retrieve a message from the queue.
fn poll_pop_queue_message(
&mut self,
cx: &mut Context<'_>,
) -> Poll<Option<Result<delay_queue::Expired<T>, time::Error>>> {
let message = self.queue.poll_expired(cx);
if let Poll::Ready(Some(Ok(message))) = &message {
self.scheduled.remove(message.get_ref()).expect(
"Expired message was popped from the Scheduler queue, but was not in the metadata map",
);
}
message
}
}
impl<T, R> Stream for Scheduler<T, R>
where
T: Eq + Hash + Clone,
R: Stream<Item = ScheduleRequest<T>>,
{
type Item = Result<T>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.as_mut().project();
while let Poll::Ready(Some(request)) = this.requests.as_mut().poll_next(cx) {
this.schedule_message(request);
}
match this.poll_pop_queue_message(cx) {
Poll::Ready(Some(expired)) => {
Poll::Ready(Some(expired.map(Expired::into_inner).context(TimerError)))
}
Poll::Ready(None) => {
if this.requests.is_terminated() {
// The source queue has terminated, and all outstanding requests are done, so terminate
Poll::Ready(None)
} else {
// The delay queue is empty, empty, but we may get more requests in the future...
Poll::Pending
}
}
Poll::Pending => Poll::Pending,
}
}
}
/// Stream transformer that takes a message and `Instant` (in the form of a `ScheduleRequest`), and emits
/// the message at the specified `Instant`.
///
/// Objects are de-duplicated: if a message is submitted twice before being emitted then it will only be
/// emitted at the earlier of the two `Instant`s.
pub fn scheduler<T: Eq + Hash + Clone>(
requests: impl Stream<Item = ScheduleRequest<T>>,
) -> impl Stream<Item = Result<T>> {
Scheduler::new(requests)
}
#[cfg(test)]
mod tests {
use super::{scheduler, ScheduleRequest};
use futures::{channel::mpsc, poll, stream, FutureExt, SinkExt, StreamExt};
use tokio::time::{advance, pause, Duration, Instant};
#[tokio::test]
async fn | () {
pause();
let mut scheduler = scheduler(stream::iter(vec![
ScheduleRequest {
message: 1u8,
run_at: Instant::now() + Duration::from_secs(1),
},
ScheduleRequest {
message: 2,
run_at: Instant::now() + Duration::from_secs(3),
},
]));
assert!(poll!(scheduler.next()).is_pending());
advance(Duration::from_secs(2)).await;
assert_eq!(scheduler.next().now_or_never().unwrap().unwrap().unwrap(), 1);
assert!(poll!(scheduler.next()).is_pending());
advance(Duration::from_secs(2)).await;
assert_eq!(scheduler.next().now_or_never().unwrap().unwrap().unwrap(), 2);
// Stream has terminated
assert!(scheduler.next().await.is_none());
}
#[tokio::test]
async fn scheduler_dedupe_should_keep_earlier_item() {
pause();
let mut scheduler = scheduler(stream::iter(vec![
ScheduleRequest {
message: (),
run_at: Instant::now() + Duration::from_secs(1),
},
ScheduleRequest {
message: (),
run_at: Instant::now() + Duration::from_secs(3),
},
]));
assert!(poll!(scheduler.next()).is_pending());
advance(Duration::from_secs(2)).await;
assert_eq!(scheduler.next().now_or_never().unwrap().unwrap().unwrap(), ());
// Stream has terminated
assert!(scheduler.next().await.is_none());
}
#[tokio::test]
async fn scheduler_dedupe_should_replace_later_item() {
pause();
let mut scheduler = scheduler(stream::iter(vec![
ScheduleRequest {
message: (),
run_at: Instant::now() + Duration::from_secs(3),
},
ScheduleRequest {
message: (),
run_at: Instant::now() + Duration::from_secs(1),
},
]));
assert!(poll!(scheduler.next()).is_pending());
advance(Duration::from_secs(2)).await;
assert_eq!(scheduler.next().now_or_never().unwrap().unwrap().unwrap(), ());
// Stream has terminated
assert!(scheduler.next().await.is_none());
}
#[tokio::test]
async fn scheduler_dedupe_should_allow_rescheduling_emitted_item() {
pause();
let (mut schedule_tx, schedule_rx) = mpsc::unbounded();
let mut scheduler = scheduler(schedule_rx);
schedule_tx
.send(ScheduleRequest {
message: (),
run_at: Instant::now() + Duration::from_secs(1),
})
.await
.unwrap();
assert!(poll!(scheduler.next()).is_pending());
advance(Duration::from_secs(2)).await;
assert_eq!(scheduler.next().now_or_never().unwrap().unwrap().unwrap(), ());
assert!(poll!(scheduler.next()).is_pending());
schedule_tx
.send(ScheduleRequest {
message: (),
run_at: Instant::now() + Duration::from_secs(1),
})
.await
.unwrap();
assert!(poll!(scheduler.next()).is_pending());
advance(Duration::from_secs(2)).await;
assert_eq!(scheduler.next().now_or_never().unwrap().unwrap().unwrap(), ());
assert!(poll!(scheduler.next()).is_pending());
}
}
| scheduler_should_emit_items_as_requested |
settings.rs | // Copyright (c) Microsoft. All rights reserved.
use std::path::Path;
use config::{Config, Environment};
use edgelet_core::{
Certificates, Connect, Listen, ModuleSpec, Provisioning, RuntimeSettings,
Settings as BaseSettings, WatchdogSettings,
};
use edgelet_docker::{DockerConfig, DEFAULTS};
use edgelet_utils::YamlFileSource;
use failure::ResultExt;
use crate::error::Error;
use crate::ErrorKind;
#[derive(Clone, Debug, serde_derive::Deserialize, serde_derive::Serialize)]
pub struct Settings {
#[serde(flatten)]
base: BaseSettings<DockerConfig>,
namespace: String,
use_pvc: bool,
iot_hub_hostname: Option<String>,
device_id: Option<String>,
proxy_image: String,
proxy_config_path: String,
proxy_config_map_name: String,
proxy_trust_bundle_path: String,
proxy_trust_bundle_config_map_name: String,
image_pull_policy: String,
device_hub_selector: String,
}
impl Settings {
pub fn new(filename: &Path) -> Result<Self, Error> |
pub fn with_device_id(mut self, device_id: &str) -> Self {
self.device_id = Some(device_id.to_owned());
self
}
pub fn with_iot_hub_hostname(mut self, iot_hub_hostname: &str) -> Self {
self.iot_hub_hostname = Some(iot_hub_hostname.to_owned());
self
}
pub fn namespace(&self) -> &str {
&self.namespace
}
pub fn use_pvc(&self) -> bool {
self.use_pvc
}
pub fn iot_hub_hostname(&self) -> Option<&str> {
self.iot_hub_hostname.as_ref().map(String::as_str)
}
pub fn device_id(&self) -> Option<&str> {
self.device_id.as_ref().map(String::as_str)
}
pub fn proxy_image(&self) -> &str {
&self.proxy_image
}
pub fn proxy_config_path(&self) -> &str {
&self.proxy_config_path
}
pub fn proxy_config_map_name(&self) -> &str {
&self.proxy_config_map_name
}
pub fn proxy_trust_bundle_path(&self) -> &str {
&self.proxy_trust_bundle_path
}
pub fn proxy_trust_bundle_config_map_name(&self) -> &str {
&self.proxy_trust_bundle_config_map_name
}
pub fn image_pull_policy(&self) -> &str {
&self.image_pull_policy
}
pub fn device_hub_selector(&self) -> &str {
&self.device_hub_selector
}
}
impl RuntimeSettings for Settings {
type Config = DockerConfig;
fn provisioning(&self) -> &Provisioning {
self.base.provisioning()
}
fn agent(&self) -> &ModuleSpec<DockerConfig> {
self.base.agent()
}
fn agent_mut(&mut self) -> &mut ModuleSpec<DockerConfig> {
self.base.agent_mut()
}
fn hostname(&self) -> &str {
self.base.hostname()
}
fn connect(&self) -> &Connect {
self.base.connect()
}
fn listen(&self) -> &Listen {
self.base.listen()
}
fn homedir(&self) -> &Path {
self.base.homedir()
}
fn certificates(&self) -> Option<&Certificates> {
self.base.certificates()
}
fn watchdog(&self) -> &WatchdogSettings {
self.base.watchdog()
}
}
| {
let mut config = Config::default();
config
.merge(YamlFileSource::String(DEFAULTS))
.context(ErrorKind::Config)?;
config
.merge(YamlFileSource::File(filename.into()))
.context(ErrorKind::Config)?;
config
.merge(Environment::with_prefix("iotedge"))
.context(ErrorKind::Config)?;
let settings = config.try_into().context(ErrorKind::Config)?;
Ok(settings)
} |
PopupConfig.js | ///////////////////////////////////////////////////////////////////////////
// Copyright © 2014 - 2017 Esri. 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.
///////////////////////////////////////////////////////////////////////////
define([
'dojo/_base/declare',
'dijit/_WidgetBase',
'dijit/_TemplatedMixin',
'dijit/_WidgetsInTemplateMixin',
'dojo/text!./PopupConfig.html',
'dojo/_base/lang',
'dojo/_base/html',
'dojo/_base/array',
'dojo/on',
'dojo/query',
'jimu/utils',
'jimu/dijit/SimpleTable',
'jimu/dijit/Popup',
'dijit/TooltipDialog',
'dijit/Menu',
'dijit/MenuItem',
'dijit/popup',
'./SortFields',
'../utils'
],
function(declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, template, lang, html, array, on,
query, jimuUtils, SimpleTable, Popup, TooltipDialog, Menu, MenuItem, dojoPopup, SortFields, queryUtils) {
return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
baseClass: 'jimu-query-setting-popup-config',
templateString: template,
_currentOrderByFields: null,
_validSortFieldTypes: ['esriFieldTypeOID',
'esriFieldTypeString',
'esriFieldTypeDate',
'esriFieldTypeSmallInteger',
'esriFieldTypeInteger',
'esriFieldTypeSingle',
'esriFieldTypeDouble'],
//options:
nls: null,
sqs: null,
//methods:
//onLayerChange
//setConfig
//getConfig
postCreate:function(){
this.inherited(arguments);
jimuUtils.combineRadioCheckBoxWithLabel(this.portalRadio, this.portalLabel);
jimuUtils.combineRadioCheckBoxWithLabel(this.customRadio, this.customLabel);
var handles = jimuUtils.groupRadios([this.portalRadio, this.customRadio],
lang.hitch(this, this._updateClassWhenRadioChanged));
array.forEach(handles, lang.hitch(this, function(handle){
this.own(handle);
}));
this._currentOrderByFields = [];
this._initFieldsTable();
this._initAddFields();
this.onLayerChange(true);
this._updateClassWhenRadioChanged();
},
onLayerChange: function(enableWebMapRadio){
this._clear();
if(enableWebMapRadio){
this.portalRadio.disabled = false;
}else{
this.portalRadio.disabled = true;
}
this._updateClassWhenRadioChanged();
var layerDefinition = this._getLayerDefinition();
if(!layerDefinition){
return;
}
//build default UI
this._clear();
var defaultConfig = {
popupInfo: null,
orderByFields: []
};
defaultConfig.popupInfo = this._getDefaultPopupInfo();
this.setConfig(defaultConfig);
//update sorting icon
this._updateSortingIcon(layerDefinition);
},
//config: {popupInfo,orderByFields}
//popupInfo: {readFromWebMap,title,fieldInfos,description,showAttachments,mediaInfos}
setConfig:function(config){
this._clear();
this.config = lang.clone(config);
var layerDefinition = this._getLayerDefinition();
if(!layerDefinition){
return;
}
this._updateSortingIcon(layerDefinition);
this._setPopupInfoForUI(config.popupInfo);
this._setOrderByFields(config.orderByFields);
},
//{title,fields,orderByFields} => {popupInfo,orderByFields}
getConfig:function(){
var config = {
popupInfo: this._getPopupInfoByUI(),
orderByFields: this._getOrderByFields()
};
if(!config.popupInfo){
return null;
}
return config;
},
destroy:function(){
this.sqs = null;
this.titleTextBox.focusNode.blur();
this.inherited(arguments);
},
_clear:function(){
html.addClass(this.sortFieldsIcon, 'jimu-state-disabled');
this._currentOrderByFields = [];
this.titleTextBox.set('value', '');
this.displayFieldsTextBox.set('value', '');
this.fieldsTable.clear();
this._resetMenu();
this._addEmptyMenuItem();
},
_getLayerDefinition: function(){
return this.sqs._layerDefinition;
},
_updateClassWhenRadioChanged: function(){
if(!this.portalRadio.disabled && this.portalRadio.checked){
html.addClass(this.domNode, 'portal-radio-selected');
}else{
html.removeClass(this.domNode, 'portal-radio-selected');
}
},
/*-----------------------------popupInfo-------------------------------------*/
//{readFromWebMap,title,fieldInfos,description,showAttachments,mediaInfos}
_setPopupInfoForUI: function(popupInfo){
var defaultPopupInfo = this._getDefaultPopupInfo();
this._setCustomPopupInfoForUI(defaultPopupInfo);
if(!this.portalRadio.disabled && popupInfo.readFromWebMap){
this.customRadio.checked = false;
this.portalRadio.checked = true;
}else{
this.portalRadio.checked = false;
this.customRadio.checked = true;
this._setCustomPopupInfoForUI(popupInfo);
}
this._updateClassWhenRadioChanged();
},
//{title,fieldInfos,description,showAttachments,mediaInfos}
_setCustomPopupInfoForUI: function(popupInfo){
//remove Shape field
var layerDefinition = this._getLayerDefinition();
var portalFieldInfos = queryUtils.getPortalFieldInfosWithoutShape(layerDefinition, popupInfo.fieldInfos);
//update titleTextBox
var validTitle = popupInfo.title && typeof popupInfo.title === 'string';
if(validTitle){
this.titleTextBox.set('value', popupInfo.title || '');
}else{
this.titleTextBox.set('value', '');
}
//update displayFieldsTextBox
this._updateDisplayFieldsTextBox(portalFieldInfos);
//image type fields
var imageTypeFields = [];
var allFieldNames = array.map(layerDefinition.fields, lang.hitch(this, function(serviceFieldInfo){
return serviceFieldInfo.name;
}));
array.forEach(popupInfo.mediaInfos, lang.hitch(this, function(mediaInfo){
if(allFieldNames.length > 0 && mediaInfo.type === 'image' && mediaInfo.value){
// if(mediaInfo.caption){
// //mediaInfo.caption is not field name, it can be label
// var fieldName = mediaInfo.caption;
// imageTypeFields.push(fieldName);
// }
var sourceURL = mediaInfo.value.sourceURL;
var imageFieldName = null;
array.some(allFieldNames, lang.hitch(this, function(fieldName){
var url = "{" + fieldName + "}";
if(url === sourceURL){
imageFieldName = fieldName;
return true;
}else{
return false;
}
}));
if(imageFieldName){
imageTypeFields.push(imageFieldName);
}
}
}));
//update menu and fieldsTable
this._resetMenu();
this.fieldsTable.clear();
if (portalFieldInfos.length > 0) {
array.forEach(portalFieldInfos, lang.hitch(this, function(portalFieldInfo) {
this._addMenuItem(portalFieldInfo);
var isImage = imageTypeFields.indexOf(portalFieldInfo.fieldName) >= 0;
this._addRow(portalFieldInfo, isImage);
}));
} else {
this._addEmptyMenuItem();
}
},
_updateDisplayFieldsTextBox: function(portalFieldInfos){
var visiblePortalFieldInfos = array.filter(portalFieldInfos, lang.hitch(this, function(item){
return item.visible;
}));
var labels = array.map(visiblePortalFieldInfos, function(item) {
return item.label;
});
var str = labels.join("; ");
this.displayFieldsTextBox.set('value', str);
},
_addRow:function(portalFieldInfo, isImage){
//{fieldName,label,visible}
var rowData = lang.clone(portalFieldInfo);
if(isImage){
rowData.specialType = 'image';
}else{
rowData.specialType = 'none';
}
this.fieldsTable.addRow(rowData);
},
_addMenuItem:function(portalFieldInfo){
var label = portalFieldInfo.fieldName + " {" + portalFieldInfo.fieldName + "}";
var menuItem = new MenuItem({
label:label,
onClick:lang.hitch(this, function(){
var a = this.titleTextBox.get('value');
var b = a + "{" + portalFieldInfo.fieldName + "}";
this.titleTextBox.set('value', b);
var dialog = this.menu.getParent();
html.setStyle(dialog.domNode.parentNode, 'display', 'none');
})
});
this.menu.addChild(menuItem);
},
_addEmptyMenuItem:function(){
var menuItem = new MenuItem({
label:this.nls.noField,
onClick:lang.hitch(this, function(){
var dialog = this.menu.getParent();
html.setStyle(dialog.domNode.parentNode, 'display', 'none');
})
});
this.menu.addChild(menuItem);
},
//{readFromWebMap,title,fieldInfos,description,showAttachments,mediaInfos}
_getPopupInfoByUI: function(){
var popupInfo = null;
if(this.customRadio.checked){
popupInfo = this._getCustomPopupInfoByUI();
if(popupInfo){
popupInfo.readFromWebMap = false;
}
}else{
popupInfo = {
readFromWebMap: true
};
}
return popupInfo;
},
//return {title,fieldInfos,description,showAttachments,mediaInfos}
_getCustomPopupInfoByUI: function(){
var popupInfo = {
title:'',
fieldInfos:[],
description: null,
showAttachments: false,
mediaInfos: []
};
var layerDefinition = this._getLayerDefinition();
if(!this.titleTextBox.validate()){
this.sqs.showResultsSetting();
this.sqs.scrollToDom(this.titleTextBox.domNode);
jimuUtils.showValidationErrorTipForFormDijit(this.titleTextBox);
return null;
}
popupInfo.title = this.titleTextBox.get('value');
popupInfo.showAttachments = !!layerDefinition.hasAttachments;
var fieldInfosAndMediaInfos = this._getPortalFieldInfosAndMediaInfosByUI();
popupInfo.fieldInfos = fieldInfosAndMediaInfos.portalFieldInfos;
popupInfo.mediaInfos = fieldInfosAndMediaInfos.mediaInfos;
return popupInfo;
},
_getPortalFieldInfosAndMediaInfosByUI: function(){
var data = this.fieldsTable.getData();
var mediaInfos = [];
var portalFieldInfos = array.map(data, lang.hitch(this, function(rowData){
var fieldName = rowData.fieldName;
var item = this._getDefaultPortalFieldInfo(fieldName);
item.label = rowData.label || item.label;
item.visible = rowData.visible;
if(rowData.visible && rowData.specialType === 'image'){
var url = "{" + fieldName + "}";
mediaInfos.push({
title: '',
type: 'image',
caption: fieldName,
value: {
sourceURL: url,
linkURL: url
}
});
}
return item;
}));
var result = {
portalFieldInfos: portalFieldInfos,
mediaInfos: mediaInfos
};
return result;
},
//return {title,fieldInfos,description,showAttachments,mediaInfos}
_getDefaultPopupInfo: function(){
var layerDefinition = this._getLayerDefinition();
return queryUtils.getDefaultPopupInfo(layerDefinition, false);
},
//return {fieldName,label,tooltip,visible,format,stringFieldOption}
_getDefaultPortalFieldInfo: function(fieldName){
var serviceFieldInfo = this._getServiceFildInfo(fieldName);
return jimuUtils.getDefaultPortalFieldInfo(serviceFieldInfo);
},
//return {name,alias,type,domain,...}
_getServiceFildInfo: function(fieldName){
var fieldInfo = null;
var layerDefinition = this._getLayerDefinition();
fieldInfo = jimuUtils.getFieldInfoByFieldName(layerDefinition.fields, fieldName);
return fieldInfo;
},
_getSortedFieldInfos: function(fieldNames, allFieldInfos){
var result = [];
var allFieldInfosHash = {};
array.forEach(allFieldInfos, lang.hitch(this, function(fieldInfo){
allFieldInfosHash[fieldInfo.name] = fieldInfo;
}));
var sortedAllFieldNames = [];
sortedAllFieldNames = sortedAllFieldNames.concat(fieldNames);
array.forEach(allFieldInfos, lang.hitch(this, function(fieldInfo){
var fieldName = fieldInfo.name;
if(sortedAllFieldNames.indexOf(fieldName) < 0){
sortedAllFieldNames.push(fieldName);
}
}));
result = array.map(sortedAllFieldNames, lang.hitch(this, function(fieldName){
return allFieldInfosHash[fieldName];
}));
return result;
},
_onBtnSetDisplayFieldsClicked: function(){
var popup = new Popup({
width: 640,
height: 380,
titleLabel: this.nls.setDisplayFields,
content: this.displayFieldsDiv,
onClose: lang.hitch(this, function(){
html.place(this.displayFieldsDiv, this.displayFieldsSection);
popup.content = "";
}),
buttons: [{
label: this.nls.ok,
onClick: lang.hitch(this, function(){
var fieldInfosAndMediaInfos = this._getPortalFieldInfosAndMediaInfosByUI();
var portalFieldInfos = fieldInfosAndMediaInfos.portalFieldInfos;
this._updateDisplayFieldsTextBox(portalFieldInfos);
popup.close();
})
}, {
label: this.nls.cancel,
onClick: lang.hitch(this, function(){
popup.close();
})
}]
});
},
/*--------------------------orderByFields-------------------------------*/
_setOrderByFields: function(orderByFields){
//such as ["STATE_NAME DESC"]
orderByFields = orderByFields || [];
//clear UI
this.sortFieldsDiv.innerHTML = "";
var sortFieldInnerHTML = "";
orderByFields = array.map(orderByFields, lang.hitch(this, function(item, i){
var splits = item.split(' ');
var fieldName = splits[0];
var sortType = 'ASC';
if(splits[1] && typeof splits[1] === 'string'){
splits[1] = splits[1].toUpperCase();
if(splits[1] === 'DESC'){
sortType = 'DESC';
}
}
var className = sortType.toLowerCase();
//update UI
var str = '<span>' + fieldName + '</span>' +
'<span class="sort-arrow ' + className + '"></span>';
if(i !== orderByFields.length - 1){
str += "<span>, </span>";
}
sortFieldInnerHTML += str;
var result = fieldName + " " + sortType;
return result;
}));
if(sortFieldInnerHTML){
sortFieldInnerHTML = "<span> </span>" + sortFieldInnerHTML;
}
this.sortFieldsDiv.innerHTML = sortFieldInnerHTML;
this._currentOrderByFields = orderByFields;
},
_getOrderByFields: function(){
var layerDefinition = this._getLayerDefinition();
if(this._shouldEnableSorting(layerDefinition)){
return this._currentOrderByFields;
}
return [];
},
_updateSortingIcon: function(layerInfo){
| html.addClass(this.sortFieldsIcon, 'jimu-state-disabled');
}
},
_shouldEnableSorting: function(layerInfo){
return this._isServiceSupportsPagination(layerInfo) &&
this._isServiceSupportsOrderBy(layerInfo);
},
_onBtnSortFieldsClicked: function(){
var layerDefinition = this._getLayerDefinition();
if(!layerDefinition){
return;
}
if(!this._shouldEnableSorting(layerDefinition)){
return;
}
var sortFields = new SortFields({
nls: this.nls,
layerDefinition: layerDefinition,
orderByFields: lang.clone(this._currentOrderByFields),
validSortFieldTypes: this._validSortFieldTypes
});
var popup = new Popup({
width: 640,
height: 380,
titleLabel: this.nls.setSortingFields,
content: sortFields,
onClose: lang.hitch(this, function(){
sortFields.destroy();
}),
buttons: [{
label: this.nls.ok,
onClick: lang.hitch(this, function(){
var orderByFields = sortFields.getOrderByFields();
this._setOrderByFields(orderByFields);
popup.close();
})
}, {
label: this.nls.cancel,
onClick: lang.hitch(this, function(){
popup.close();
})
}]
});
},
/*-----------------------------------init---------------------------------------*/
_initFieldsTable: function(){
var args = {
autoHeight: false,
style: "height:187px",
fields: [{
name: "visible",
title: this.nls.visibility,
type: "checkbox"
}, {
name: "fieldName",
title: this.nls.name,
type: "text",
editable: false
}, {
name: "label",
title: this.nls.alias,
type: "text",
editable: true
}, {
name: "specialType",
title: this.nls.specialType,
type: "extension",
create: lang.hitch(this, this._createSpecialType),
setValue: lang.hitch(this, this._setValue4SpecialType),
getValue: lang.hitch(this, this._getValueOfSpecialType)
}, {
name: "actions",
title: this.nls.actions,
type: "actions",
actions: ["up", "down"]
}]
};
this.fieldsTable = new SimpleTable(args);
this.fieldsTable.placeAt(this.fieldsContainer);
this.fieldsTable.startup();
},
_createSpecialType: function(td){
var select = html.create('select', {}, td);
html.create('option', {
value: 'none',
label: this.nls.none,
selected: true,
innerHTML: this.nls.none
}, select);
html.create('option', {
value: 'image',
label: this.nls.image,
innerHTML: this.nls.image
}, select);
},
_setValue4SpecialType: function(td, value){
var select = query('select', td)[0];
select.value = value;
},
_getValueOfSpecialType:function(td){
var select = query('select', td)[0];
return select.value;
},
_initAddFields:function(){
var ttdContent = html.create("div");
this.tooltipDialog = new TooltipDialog({
style: "cursor:pointer",
content: ttdContent
});
this.menu = new Menu();
this.menu.placeAt(ttdContent);
this.own(on(document.body, 'click', lang.hitch(this, function(){
dojoPopup.close(this.tooltipDialog);
})));
},
_onAddClicked:function(event){
event.stopPropagation();
event.preventDefault();
dojoPopup.close(this.tooltipDialog);
dojoPopup.open({
popup: this.tooltipDialog,
around: this.btnAddFields
});
},
_resetMenu:function(){
var menuItems = this.menu.getChildren();
array.forEach(menuItems, lang.hitch(this, function(menuItem){
this.menu.removeChild(menuItem);
}));
},
_isServiceSupportsPagination: function(layerInfo){
var isSupport = false;
if(layerInfo.advancedQueryCapabilities){
if(layerInfo.advancedQueryCapabilities.supportsPagination){
isSupport = true;
}
}
return isSupport;
},
_isServiceSupportsOrderBy: function(layerInfo) {
var isSupport = false;
if (layerInfo.advancedQueryCapabilities) {
if (layerInfo.advancedQueryCapabilities.supportsOrderBy) {
isSupport = true;
}
}
return isSupport;
}
});
}); | if(this._shouldEnableSorting(layerInfo)){
html.removeClass(this.sortFieldsIcon, 'jimu-state-disabled');
}else{
|
datacenter_test.go | package mconsul
import (
"fmt"
"testing"
"github.com/treasure1993/base/micro/context"
)
func | (t *testing.T) {
ret, err := GetDatacenters()
if err != nil {
context.LogInfof("err = %v", err)
}
fmt.Println(ret)
}
| TestGetDatacenters |
models.py | import uuid
import os
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
PermissionsMixin)
from django.conf import settings
def recipe_image_file_path(instance, filename): | filename = f'{uuid.uuid4()}.{ext}'
return os.path.join('uploads/recipe/', filename)
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
'''
Creates and saves users with given email
'''
if not email:
raise ValueError('The Email must be set')
user = self.model(email=self.normalize_email(email), **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
'''
Creates and saves superusers with given email
'''
user = self.create_user(email, password)
user.is_staff = True
user.is_superuser = True
user.save(using=self.db)
return user
class User(AbstractBaseUser, PermissionsMixin):
"""Custom user model that supports using emails instead of username"""
email = models.EmailField(max_length=255, unique=True)
name = models.CharField(max_length=255)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
def __str__(self):
return self.email
class Tag(models.Model):
"""Tag to be used for a recipe"""
name = models.CharField(max_length=255)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
class Meta:
ordering = ["id"]
def __str__(self):
return self.name
class Ingredient(models.Model):
"""Ingredients to be used in a recipe"""
name = models.CharField(max_length=255)
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
def __str__(self):
return self.name
class Recipe(models.Model):
"""Recipe Object"""
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
title = models.CharField(max_length=255)
time_minutes = models.IntegerField()
price = models.DecimalField(max_digits=5, decimal_places=2)
link = models.CharField(max_length=255, blank=True)
ingredients = models.ManyToManyField('Ingredient')
tags = models.ManyToManyField('Tag')
image = models.ImageField(null=True, upload_to=recipe_image_file_path)
def __str__(self):
return self.title | """Generate file path for new recipe image"""
ext = filename.split('.')[-1] |
index.tsx | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import { getOr, uniqBy } from 'lodash/fp';
import memoizeOne from 'memoize-one';
import React from 'react';
import { Query } from 'react-apollo';
import { compose, Dispatch } from 'redux';
import { connect, ConnectedProps } from 'react-redux';
import { IIndexPattern } from '../../../../../../../src/plugins/data/common/index_patterns';
import { DEFAULT_INDEX_KEY } from '../../../common/constants';
import {
GetTimelineQuery,
PageInfo,
SortField,
TimelineEdges,
TimelineItem,
} from '../../graphql/types';
import { inputsModel, inputsSelectors, State } from '../../store';
import { withKibana, WithKibanaProps } from '../../lib/kibana';
import { createFilter } from '../helpers';
import { QueryTemplate, QueryTemplateProps } from '../query_template';
import { EventType } from '../../store/timeline/model';
import { timelineQuery } from './index.gql_query';
import { timelineActions } from '../../store/timeline';
import { SIGNALS_PAGE_TIMELINE_ID } from '../../pages/detection_engine/components/signals';
export interface TimelineArgs {
events: TimelineItem[];
id: string;
inspect: inputsModel.InspectQuery;
loading: boolean;
loadMore: (cursor: string, tieBreaker: string) => void;
pageInfo: PageInfo;
refetch: inputsModel.Refetch;
totalCount: number;
getUpdatedAt: () => number;
}
export interface CustomReduxProps {
clearSignalsState: ({ id }: { id?: string }) => void;
}
export interface OwnProps extends QueryTemplateProps {
children?: (args: TimelineArgs) => React.ReactNode;
eventType?: EventType;
id: string;
indexPattern?: IIndexPattern;
indexToAdd?: string[];
limit: number;
sortField: SortField;
fields: string[];
}
type TimelineQueryProps = OwnProps & PropsFromRedux & WithKibanaProps & CustomReduxProps;
class | extends QueryTemplate<
TimelineQueryProps,
GetTimelineQuery.Query,
GetTimelineQuery.Variables
> {
private updatedDate: number = Date.now();
private memoizedTimelineEvents: (variables: string, events: TimelineEdges[]) => TimelineItem[];
constructor(props: TimelineQueryProps) {
super(props);
this.memoizedTimelineEvents = memoizeOne(this.getTimelineEvents);
}
public render() {
const {
children,
clearSignalsState,
eventType = 'raw',
id,
indexPattern,
indexToAdd = [],
isInspected,
kibana,
limit,
fields,
filterQuery,
sourceId,
sortField,
} = this.props;
const defaultKibanaIndex = kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY);
const defaultIndex =
indexPattern == null || (indexPattern != null && indexPattern.title === '')
? [
...(['all', 'raw'].includes(eventType) ? defaultKibanaIndex : []),
...(['all', 'signal'].includes(eventType) ? indexToAdd : []),
]
: indexPattern?.title.split(',') ?? [];
const variables: GetTimelineQuery.Variables = {
fieldRequested: fields,
filterQuery: createFilter(filterQuery),
sourceId,
pagination: { limit, cursor: null, tiebreaker: null },
sortField,
defaultIndex,
inspect: isInspected,
};
return (
<Query<GetTimelineQuery.Query, GetTimelineQuery.Variables>
query={timelineQuery}
fetchPolicy="network-only"
notifyOnNetworkStatusChange
variables={variables}
>
{({ data, loading, fetchMore, refetch }) => {
this.setRefetch(refetch);
this.setExecuteBeforeRefetch(clearSignalsState);
this.setExecuteBeforeFetchMore(clearSignalsState);
const timelineEdges = getOr([], 'source.Timeline.edges', data);
this.setFetchMore(fetchMore);
this.setFetchMoreOptions((newCursor: string, tiebreaker?: string) => ({
variables: {
pagination: {
cursor: newCursor,
tiebreaker,
limit,
},
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return prev;
}
return {
...fetchMoreResult,
source: {
...fetchMoreResult.source,
Timeline: {
...fetchMoreResult.source.Timeline,
edges: uniqBy('node._id', [
...prev.source.Timeline.edges,
...fetchMoreResult.source.Timeline.edges,
]),
},
},
};
},
}));
this.updatedDate = Date.now();
return children!({
id,
inspect: getOr(null, 'source.Timeline.inspect', data),
refetch: this.wrappedRefetch,
loading,
totalCount: getOr(0, 'source.Timeline.totalCount', data),
pageInfo: getOr({}, 'source.Timeline.pageInfo', data),
events: this.memoizedTimelineEvents(JSON.stringify(variables), timelineEdges),
loadMore: this.wrappedLoadMore,
getUpdatedAt: this.getUpdatedAt,
});
}}
</Query>
);
}
private getUpdatedAt = () => this.updatedDate;
private getTimelineEvents = (variables: string, timelineEdges: TimelineEdges[]): TimelineItem[] =>
timelineEdges.map((e: TimelineEdges) => e.node);
}
const makeMapStateToProps = () => {
const getQuery = inputsSelectors.timelineQueryByIdSelector();
const mapStateToProps = (state: State, { id }: OwnProps) => {
const { isInspected } = getQuery(state, id);
return {
isInspected,
};
};
return mapStateToProps;
};
const mapDispatchToProps = (dispatch: Dispatch) => ({
clearSignalsState: ({ id }: { id?: string }) => {
if (id != null && id === SIGNALS_PAGE_TIMELINE_ID) {
dispatch(timelineActions.clearEventsLoading({ id }));
dispatch(timelineActions.clearEventsDeleted({ id }));
}
},
});
const connector = connect(makeMapStateToProps, mapDispatchToProps);
type PropsFromRedux = ConnectedProps<typeof connector>;
export const TimelineQuery = compose<React.ComponentClass<OwnProps>>(
connector,
withKibana
)(TimelineQueryComponent);
| TimelineQueryComponent |
snapshot.go | /*
* Copyright 2020-2021, Offchain Labs, 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.
*/
package snapshot
import (
"context"
"github.com/offchainlabs/arbitrum/packages/arb-util/arblog"
"math/big"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/common/math"
"github.com/ethereum/go-ethereum/core/types"
"github.com/pkg/errors"
"github.com/offchainlabs/arbitrum/packages/arb-evm/arbos"
"github.com/offchainlabs/arbitrum/packages/arb-evm/evm"
"github.com/offchainlabs/arbitrum/packages/arb-evm/message"
"github.com/offchainlabs/arbitrum/packages/arb-util/common"
"github.com/offchainlabs/arbitrum/packages/arb-util/hashing"
"github.com/offchainlabs/arbitrum/packages/arb-util/inbox"
"github.com/offchainlabs/arbitrum/packages/arb-util/machine"
"github.com/offchainlabs/arbitrum/packages/arb-util/value"
)
var logger = arblog.Logger.With().Str("component", "snapshot").Logger()
type Snapshot struct {
mach machine.Machine
time inbox.ChainTime
nextInboxSeqNum *big.Int
chainId *big.Int
arbosVersion uint64
arbosRemappingEnabled bool
}
func NewSnapshot(ctx context.Context, mach machine.Machine, time inbox.ChainTime, lastInboxSeq *big.Int) (*Snapshot, error) {
snap := &Snapshot{
mach: mach,
time: time,
nextInboxSeqNum: new(big.Int).Add(lastInboxSeq, big.NewInt(1)),
}
ver, err := snap.ArbOSVersion(ctx)
if err != nil {
return nil, err
}
snap.arbosVersion = ver.Uint64()
if snap.arbosVersion >= 27 {
chainId, err := snap.ChainId(ctx)
if err != nil {
return nil, err
}
snap.chainId = chainId
}
if snap.arbosVersion >= 40 {
arbOwnerMsg := message.ContractTransaction{
BasicTx: message.BasicTx{
MaxGas: big.NewInt(1 << 30),
GasPriceBid: snap.MaxGasPriceBid(),
DestAddress: common.NewAddressFromEth(arbos.ARB_OWNER_ADDRESS),
Payment: big.NewInt(0),
Data: arbos.GetChainParameterData(arbos.EnableL1ContractAddressAliasingParamId),
},
}
// Note: this .Call actually uses arbosRemappingEnabled which isn't set yet,
// but that's fine because the zero address is never rewritten regardless.
arbOwnerRes, _, err := snap.Call(ctx, arbOwnerMsg, common.Address{}, math.MaxUint64)
if err != nil {
return nil, err
}
if arbOwnerRes.ResultCode != evm.ReturnCode {
return nil, errors.New("failed to query ArbOS address remapping state")
}
snap.arbosRemappingEnabled = new(big.Int).SetBytes(arbOwnerRes.ReturnData).Sign() > 0
}
return snap, nil
}
func (s *Snapshot) ArbosVersion() uint64 {
return s.arbosVersion
}
func (s *Snapshot) MaxGasPriceBid() *big.Int {
if s.arbosVersion >= 42 {
return big.NewInt(1 << 60)
} else {
return big.NewInt(0)
}
}
// AddMessage can only be called if the snapshot is uniquely owned
// If an error is returned, s is unmodified
func (s *Snapshot) AddMessage(ctx context.Context, msg message.Message, sender common.Address, targetHash common.Hash) (*evm.TxResult, error) {
mach := s.mach.Clone()
res, _, err := s.addMessage(ctx, msg, sender, targetHash, addMessageMaxAVMGas)
if err != nil {
// Revert the machine
s.mach = mach
}
return res, err
}
const addMessageMaxAVMGas = 100000000000
// addMessage can only be called if the snapshot is uniquely owned
// leaves the machine in an undefined state on error
func (s *Snapshot) addMessage(ctx context.Context, msg message.Message, sender common.Address, targetHash common.Hash, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
chainTime := inbox.ChainTime{
BlockNum: common.NewTimeBlocksInt(0),
Timestamp: big.NewInt(0),
}
inboxMsg := message.NewInboxMessage(msg, sender, s.nextInboxSeqNum, big.NewInt(0), chainTime)
res, debugPrints, err := runTxUnchecked(ctx, s.mach, inboxMsg, maxAVMGas)
if err != nil {
return nil, nil, err
}
if res.IncomingRequest.MessageID != targetHash {
return nil, nil, errors.Errorf("call got unexpected result %v instead of %v", res.IncomingRequest.MessageID, targetHash)
}
s.nextInboxSeqNum = new(big.Int).Add(s.nextInboxSeqNum, big.NewInt(1))
return res, debugPrints, nil
}
// AdvanceTime can only be called if the snapshot is uniquely owned
func (s *Snapshot) AdvanceTime(time inbox.ChainTime) {
s.time = time
}
func (s *Snapshot) Clone() *Snapshot {
var chainId *big.Int
if s.chainId != nil {
chainId = new(big.Int).Set(s.chainId)
}
return &Snapshot{
mach: s.mach.Clone(),
time: inbox.ChainTime{
BlockNum: s.time.BlockNum.Clone(),
Timestamp: new(big.Int).Set(s.time.Timestamp),
},
nextInboxSeqNum: new(big.Int).Set(s.nextInboxSeqNum),
chainId: chainId,
arbosRemappingEnabled: s.arbosRemappingEnabled,
}
}
func (s *Snapshot) Height() *common.TimeBlocks {
return s.time.BlockNum
}
func (s *Snapshot) EstimateGas(ctx context.Context, tx *types.Transaction, aggregator, sender common.Address, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
if s.arbosVersion < 3 {
var dest common.Address
if tx.To() != nil {
copy(dest[:], tx.To().Bytes())
}
msg := message.ContractTransaction{
BasicTx: message.BasicTx{
MaxGas: new(big.Int).SetUint64(tx.Gas()),
GasPriceBid: tx.GasPrice(),
DestAddress: dest,
Payment: tx.Value(),
Data: tx.Data(),
},
}
return s.Call(ctx, msg, sender, maxAVMGas)
} else {
gasEstimationMessage, err := message.NewGasEstimationMessage(aggregator, big.NewInt(0), message.NewCompressedECDSAFromEth(tx))
if err != nil {
return nil, nil, err
}
var targetHash common.Hash
if s.chainId != nil {
targetHash = hashing.SoliditySHA3(hashing.Uint256(s.chainId), hashing.Uint256(s.nextInboxSeqNum))
targetHash = hashing.SoliditySHA3(hashing.Bytes32(targetHash), hashing.Uint256(big.NewInt(0)))
}
inboxMsg := s.makeInboxMessage(gasEstimationMessage, sender)
return runTx(ctx, s.mach.Clone(), inboxMsg, targetHash, maxAVMGas)
}
}
func (s *Snapshot) EstimateRetryableGas(ctx context.Context, msg message.RetryableTx, sender common.Address, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
redeemGas := new(big.Int).Set(msg.MaxGas)
redeemGasPriceBid := new(big.Int).Set(msg.GasPriceBid)
msg.MaxGas = msg.MaxGas.SetUint64(0)
msg.GasPriceBid = msg.GasPriceBid.SetUint64(0)
inboxMsg1 := message.NewInboxMessage(msg, sender, s.nextInboxSeqNum, big.NewInt(0), s.time)
var targetHash common.Hash
var ticketHash common.Hash
if s.chainId != nil {
targetHash = hashing.SoliditySHA3(hashing.Uint256(s.chainId), hashing.Uint256(s.nextInboxSeqNum))
ticketHash = hashing.SoliditySHA3(hashing.Bytes32(targetHash), hashing.Uint256(big.NewInt(0)))
}
redeemTx := types.NewTx(&types.LegacyTx{
Nonce: 0,
GasPrice: redeemGasPriceBid,
Gas: redeemGas.Uint64(),
To: &arbos.ARB_RETRYABLE_ADDRESS,
Value: big.NewInt(0),
Data: arbos.RedeemData(ticketHash),
})
gasEstimationMessage, err := message.NewGasEstimationMessage(common.Address{}, big.NewInt(0), message.NewCompressedECDSAFromEth(redeemTx))
if err != nil {
return nil, nil, err
}
estimateSeqNum := new(big.Int).Add(s.nextInboxSeqNum, big.NewInt(1))
var targetHash2 common.Hash
if s.chainId != nil {
targetHash2 = hashing.SoliditySHA3(hashing.Uint256(s.chainId), hashing.Uint256(estimateSeqNum))
targetHash2 = hashing.SoliditySHA3(hashing.Bytes32(targetHash2), hashing.Uint256(big.NewInt(0)))
}
redeemer := sender
if s.arbosRemappingEnabled {
redeemer = message.L2RemapAccount(redeemer)
}
inboxMsg2 := message.NewInboxMessage(gasEstimationMessage, redeemer, estimateSeqNum, big.NewInt(0), s.time)
mach := s.mach.Clone()
assertion, debugPrints, _, err := mach.ExecuteAssertionAdvanced(
ctx,
maxAVMGas,
false,
nil,
[]inbox.InboxMessage{inboxMsg2, inboxMsg1},
true,
false,
)
if err != nil {
return nil, nil, err
}
avmLogs := assertion.Logs
if len(avmLogs) == 0 {
return nil, nil, errors.New("no logs emitted processing retryable")
}
res, err := evm.NewTxResultFromValue(avmLogs[0])
if err != nil {
return nil, nil, err
}
if res.ResultCode != evm.ReturnCode {
return nil, nil, errors.New("ticket creation failed")
}
if res.IncomingRequest.MessageID != targetHash {
return nil, debugPrints, errors.Errorf("ticket creation got unexpected result %v instead of %v", res.IncomingRequest.MessageID, targetHash)
}
if len(avmLogs) == 2 {
// Redeem must have failed
res2, err := evm.NewTxResultFromValue(avmLogs[1])
if err != nil {
return nil, nil, err
}
if res2.ResultCode != evm.ReturnCode {
return nil, nil, evm.HandleCallError(res2, false)
} else {
return nil, nil, errors.New("Redeem succeeded, but failed to trigger redeemed tx")
}
}
if len(avmLogs) != 3 {
return nil, nil, errors.Errorf("unexpected result count %v", len(avmLogs))
}
res2, err := evm.NewTxResultFromValue(avmLogs[2])
if err != nil {
return nil, nil, err
}
if res2.IncomingRequest.MessageID != targetHash2 {
return nil, debugPrints, errors.Errorf("estimation got unexpected result %v instead of %v", res2.IncomingRequest.MessageID, targetHash2)
}
return res2, debugPrints, err
}
func (s *Snapshot) Call(ctx context.Context, msg message.ContractTransaction, sender common.Address, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
var targetHash common.Hash
if s.chainId != nil {
targetHash = hashing.SoliditySHA3(hashing.Uint256(s.chainId), hashing.Uint256(s.nextInboxSeqNum))
}
if s.arbosRemappingEnabled {
sender = message.L1RemapAccount(sender)
}
inboxMsg := s.makeInboxMessage(message.NewSafeL2Message(msg), sender)
return runTx(ctx, s.mach.Clone(), inboxMsg, targetHash, maxAVMGas)
}
type EthCallOverride struct {
Nonce *hexutil.Uint64 `json:"nonce"`
Code *hexutil.Bytes `json:"code"`
Balance *hexutil.Big `json:"balance"`
State *map[ethcommon.Hash]ethcommon.Hash `json:"state"`
StateDiff *map[ethcommon.Hash]ethcommon.Hash `json:"stateDiff"`
}
func (s *Snapshot) CallWithOverrides(ctx context.Context, msg message.ContractTransaction, sender common.Address, overrides *map[ethcommon.Address]EthCallOverride, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
snap := s.Clone()
snap.mach = snap.mach.Clone()
if overrides != nil {
// We'll be mutating this scapshot so we need to make a copy
for address, override := range *overrides {
account := common.NewAddressFromEth(address)
if override.Nonce != nil {
err := snap.setNonce(ctx, account, uint64(*override.Nonce))
if err != nil {
return nil, nil, err
}
}
if override.Balance != nil {
err := snap.setBalance(ctx, account, override.Balance.ToInt())
if err != nil {
return nil, nil, err
}
}
if override.Code != nil {
err := snap.setCode(ctx, account, *override.Code)
if err != nil {
return nil, nil, err
}
}
if override.State != nil {
storage := make(map[common.Hash]common.Hash)
for key, val := range *override.State {
storage[common.NewHashFromEth(key)] = common.NewHashFromEth(val)
}
err := snap.setState(ctx, account, storage)
if err != nil {
return nil, nil, err
}
}
if override.StateDiff != nil {
for key, val := range *override.StateDiff {
err := snap.store(ctx, account, common.NewHashFromEth(key), common.NewHashFromEth(val))
if err != nil {
return nil, nil, err
}
}
}
}
}
var targetHash common.Hash
if snap.chainId != nil {
targetHash = hashing.SoliditySHA3(hashing.Uint256(snap.chainId), hashing.Uint256(snap.nextInboxSeqNum))
}
if snap.arbosRemappingEnabled {
sender = message.L1RemapAccount(sender)
}
inboxMsg := snap.makeInboxMessage(message.NewSafeL2Message(msg), sender)
return runTx(ctx, snap.mach, inboxMsg, targetHash, maxAVMGas)
}
func (s *Snapshot) makeInboxMessage(msg message.Message, sender common.Address) inbox.InboxMessage {
return message.NewInboxMessage(msg, sender, s.nextInboxSeqNum, big.NewInt(0), s.time)
}
func runTx(ctx context.Context, mach machine.Machine, inboxMsg inbox.InboxMessage, targetHash common.Hash, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
res, debugPrints, err := runTxUnchecked(ctx, mach, inboxMsg, maxAVMGas)
if err != nil {
return nil, nil, err
}
var emptyHash common.Hash
if targetHash != emptyHash && res.IncomingRequest.MessageID != targetHash {
return nil, debugPrints, errors.Errorf("call got unexpected result %v instead of %v", res.IncomingRequest.MessageID, targetHash)
}
return res, debugPrints, nil
}
func (s *Snapshot) basicCallUnsafe(ctx context.Context, data []byte, dest common.Address) (*evm.TxResult, []value.Value, error) {
msg := message.ContractTransaction{
BasicTx: message.BasicTx{
MaxGas: big.NewInt(1000000000),
GasPriceBid: s.MaxGasPriceBid(),
DestAddress: dest,
Payment: big.NewInt(0),
Data: data,
},
}
inboxMsg := message.NewInboxMessage(message.NewSafeL2Message(msg), common.Address{}, s.nextInboxSeqNum, big.NewInt(0), s.time)
return runTxUnchecked(ctx, s.mach.Clone(), inboxMsg, 1000000000)
}
func (s *Snapshot) basicCall(ctx context.Context, data []byte, dest common.Address) (*evm.TxResult, error) {
msg := message.ContractTransaction{
BasicTx: message.BasicTx{
MaxGas: big.NewInt(1000000000),
GasPriceBid: s.MaxGasPriceBid(),
DestAddress: dest,
Payment: big.NewInt(0),
Data: data,
},
}
res, _, err := s.Call(ctx, msg, common.Address{}, math.MaxUint64)
return res, err
}
func (s *Snapshot) basicAddMessage(ctx context.Context, data []byte, dest common.Address) (*evm.TxResult, error) {
msg := message.ContractTransaction{
BasicTx: message.BasicTx{
MaxGas: big.NewInt(1000000000),
GasPriceBid: s.MaxGasPriceBid(),
DestAddress: dest,
Payment: big.NewInt(0),
Data: data,
},
}
res, _, err := s.AddContractMessage(ctx, msg, common.Address{}, addMessageMaxAVMGas)
return res, err
}
func (s *Snapshot) AddContractMessage(ctx context.Context, msg message.ContractTransaction, sender common.Address, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
if s.arbosRemappingEnabled && sender != (common.Address{}) {
sender = message.L1RemapAccount(sender)
}
var targetHash common.Hash
if s.chainId != nil {
targetHash = hashing.SoliditySHA3(hashing.Uint256(s.chainId), hashing.Uint256(s.nextInboxSeqNum))
}
return s.addMessage(ctx, message.NewSafeL2Message(msg), sender, targetHash, maxAVMGas)
}
func (s *Snapshot) addArbosTestMessage(ctx context.Context, data []byte) error {
res, err := s.basicAddMessage(ctx, (data), common.NewAddressFromEth(arbos.ARB_TEST_ADDRESS))
if err != nil {
return err
}
if err := checkValidResult(res); err != nil {
return err
}
return nil
}
func checkValidResult(res *evm.TxResult) error {
if res.ResultCode == evm.ReturnCode {
return nil
}
return errors.Errorf("error processing call %v", res.ResultCode)
}
func (s *Snapshot) GetBalance(ctx context.Context, account common.Address) (*big.Int, error) {
res, err := s.basicCall(ctx, arbos.GetBalanceData(account), common.NewAddressFromEth(arbos.ARB_INFO_ADDRESS))
if err != nil {
return nil, err
}
if err := checkValidResult(res); err != nil {
return nil, err
}
return arbos.ParseBalanceResult(res.ReturnData)
}
func (s *Snapshot) GetTransactionCount(ctx context.Context, account common.Address) (*big.Int, error) {
res, err := s.basicCall(ctx, arbos.TransactionCountData(account), common.NewAddressFromEth(arbos.ARB_SYS_ADDRESS))
if err != nil {
return nil, err
}
if err := checkValidResult(res); err != nil {
return nil, err
}
return arbos.ParseTransactionCountResult(res.ReturnData)
}
func (s *Snapshot) GetCode(ctx context.Context, account common.Address) ([]byte, error) {
res, err := s.basicCall(ctx, arbos.GetCodeData(account), common.NewAddressFromEth(arbos.ARB_INFO_ADDRESS))
if err != nil {
return nil, err
}
if err := checkValidResult(res); err != nil {
return nil, err
}
return arbos.ParseCodeResult(res.ReturnData)
}
func (s *Snapshot) GetStorageAt(ctx context.Context, account common.Address, index *big.Int) (*big.Int, error) {
res, err := s.basicCall(ctx, arbos.StorageAtData(account, index), common.NewAddressFromEth(arbos.ARB_SYS_ADDRESS))
if err != nil {
return nil, err
}
if err := checkValidResult(res); err != nil {
return nil, err
}
return arbos.ParseGetStorageAtResult(res.ReturnData)
}
func (s *Snapshot) setNonce(ctx context.Context, account common.Address, nonce uint64) error {
return s.addArbosTestMessage(ctx, arbos.SetNonceData(account, nonce))
}
func (s *Snapshot) setBalance(ctx context.Context, account common.Address, balance *big.Int) error {
return s.addArbosTestMessage(ctx, arbos.SetBalanceData(account, balance))
}
func (s *Snapshot) setState(ctx context.Context, account common.Address, storage map[common.Hash]common.Hash) error {
return s.addArbosTestMessage(ctx, arbos.SetStateData(account, storage))
}
func (s *Snapshot) setCode(ctx context.Context, account common.Address, code []byte) error {
return s.addArbosTestMessage(ctx, arbos.SetCodeData(account, code))
}
func (s *Snapshot) store(ctx context.Context, account common.Address, key, val common.Hash) error {
return s.addArbosTestMessage(ctx, arbos.StoreData(account, key, val))
}
func (s *Snapshot) ArbOSVersion(ctx context.Context) (*big.Int, error) {
res, _, err := s.basicCallUnsafe(ctx, arbos.ArbOSVersionData(), common.NewAddressFromEth(arbos.ARB_SYS_ADDRESS))
if err != nil {
return nil, err
}
if err := checkValidResult(res); err != nil {
return nil, err
}
return arbos.ParseArbOSVersionResult(res.ReturnData)
}
func (s *Snapshot) ChainId(ctx context.Context) (*big.Int, error) {
res, _, err := s.basicCallUnsafe(ctx, arbos.ChainIdData(), common.NewAddressFromEth(arbos.ARB_SYS_ADDRESS))
if err != nil {
return nil, err
}
if err := checkValidResult(res); err != nil {
return nil, err
}
return arbos.ParseChainIdResult(res.ReturnData)
}
func (s *Snapshot) GetPricesInWei(ctx context.Context) ([6]*big.Int, error) {
res, err := s.basicCall(ctx, arbos.GetPricesInWeiData(), common.NewAddressFromEth(arbos.ARB_GAS_INFO_ADDRESS))
if err != nil {
return [6]*big.Int{}, err
}
if err := checkValidResult(res); err != nil {
return [6]*big.Int{}, err
}
return arbos.ParseGetPricesInWeiResult(res.ReturnData)
}
func | (ctx context.Context, mach machine.Machine, msg inbox.InboxMessage, maxAVMGas uint64) (*evm.TxResult, []value.Value, error) {
assertion, debugPrints, steps, err := mach.ExecuteAssertionAdvanced(ctx, maxAVMGas, false, nil, []inbox.InboxMessage{msg}, true, false)
if err != nil {
return nil, nil, err
}
// If the machine wasn't able to run and it reports that it is currently
// blocked, return the block reason to give the client more information
// as opposed to just returning a general "call produced no output"
if br := mach.IsBlocked(true); steps == 0 && br != nil {
return nil, debugPrints, errors.Errorf("can't produce solution since machine is blocked %v", br)
}
avmLogs := assertion.Logs
if len(avmLogs) == 0 {
logger.Info().Uint64("gasused", assertion.NumGas).Msg("Running message didn't produce log")
return nil, debugPrints, errors.New("transaction ran out of gas")
}
res, err := evm.NewTxResultFromValue(avmLogs[len(avmLogs)-1])
return res, debugPrints, err
}
| runTxUnchecked |
check_schedule.py | # -*- coding: utf-8 -*-
""" Print accepted talks not scheduled and not accepted talks which have been
scheduled.
"""
from collections import defaultdict
from optparse import make_option
import operator
import simplejson as json
from django.core.management.base import BaseCommand, CommandError
from django.core import urlresolvers
from conference import models | from ...utils import (talk_schedule,
talk_type,
group_talks_by_type,
talk_track_title)
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--all_scheduled',
action='store_true',
dest='all_scheduled',
default=False,
help='Show a list of accepted talks which have not been scheduled',
),
make_option('--all_accepted',
action='store_true',
dest='all_accepted',
default=False,
help='Show a list of scheduled talks which have not been accepted',
),
)
def handle(self, *args, **options):
try:
conference = args[0]
except IndexError:
raise CommandError('conference not specified')
if not options['all_scheduled'] and not options['all_accepted']:
print('Please use either --all_scheduled or --all_accepted option.')
if options['all_scheduled']:
print('Checking that all accepted talks have been scheduled.')
talks = (models.Talk.objects.filter(conference=conference,
status='accepted'))
type_talks = group_talks_by_type(talks)
for type in type_talks:
for talk in type_talks[type]:
schedules = list(talk_schedule(talk))
if not schedules:
print('ERROR: {} (id: {}) "{}" is not '
'scheduled'.format(talk_type(talk), talk.id, talk))
elif len(schedules) > 1:
print('ERROR: {} (id: {}) "{}" is '
'scheduled {} times: {} in {}.'.format(talk_type(talk),
talk.id,
talk,
len(schedules),
schedules,
talk_track_title(talk)))
if options['all_accepted']:
print('Checking that all scheduled talks are accepted.')
talks = (models.Talk.objects.filter(conference=conference))
type_talks = group_talks_by_type(talks)
for type in type_talks:
for talk in type_talks[type]:
schedules = list(talk_schedule(talk))
if talk.status != 'accepted' and schedules:
print('ERROR: {} (id: {}) "{}" is scheduled but '
'not accepted.'.format(talk_type(talk),
talk.id,
talk)) | from conference import utils
from conference.models import TALK_TYPE, TALK_ADMIN_TYPE
|
GroundTruthShp.py | """
I'm copying this from some of my much older work. It's probably going to be
buggy. Yep, it was. I've done some refactoring and whatnot but it could probably
use some more. Maybe combine with `GeoDFUtils`? It would be nice to be able to
easily operate on GDF subsets and selections.
`buffer` and `rasterize` are working pretty well. Still need tests and whatnot
but those methods are the main use for this module at the moment. The two
`error_matrix` functions are useful and working too.
"""
#from error_matrix import *
from RasterDS import RasterDS
from ErrorMatrix import ErrorMatrix
from scipy.stats.stats import mode
import numpy as np
import pandas as pd
import geopandas as gpd
import os
from osgeo import ogr, gdal, osr
import shapely as shpl
from scipy.stats import mode as scipymode
from tempfile import mkdtemp
import shutil
class GroundTruthGDF(gpd.GeoDataFrame):
def __init__(self, *args, **kwargs):
hf = kwargs.pop('habfield', 'habitat')
hc = kwargs.pop('habcodefield', 'hab_num')
super(GroundTruthGDF, self).__init__(*args, **kwargs)
self.habfield = hf
self.habcodefld = hc
@classmethod
def new(cls,*args,**kwargs):
return cls(*args,**kwargs)
@classmethod
def from_file(cls, filename, **kwargs):
hf = kwargs.pop('habfield', 'habitat')
hc = kwargs.pop('habcodefield', 'hab_num')
gdf = gpd.io.file.read_file(filename, **kwargs)
return cls(gdf, habfield=hf, habcodefield=hc)
@property
def codes_habitat(self):
"""
Return a dictionary just like habitat_codes only backwards.
"""
hf = self.habfield
hcf = self.habcodefld
hcd = dict()
for cl in self[hcf].unique():
if cl > 0:
sers = self[self[hcf]==cl][hf]
if sers.count() > 1:
hcd[cl] = sers.mode().item()
elif sers.count() > 0:
hcd[cl] = sers.item()
return hcd
def __getitem__(self, key):
result = super(GroundTruthGDF, self).__getitem__(key)
if isinstance(result, gpd.GeoDataFrame):
result.__class__ = GroundTruthGDF
result.habfield = self.habfield
result.habcodefld = self.habcodefld
return result
def query(self, expr, inplace=False, **kwargs):
result = super(GroundTruthGDF, self).query(expr, inplace=False, **kwargs)
if isinstance(result, gpd.GeoDataFrame):
result.__class__ = GroundTruthGDF
result.habfield = self.habfield
result.habcodefld = self.habcodefld
return result
def comparison_df(self, rds, radius=0, generous=False, band_index=0,
out_of_bounds=np.nan, with_unclassed=False):
"""
There can be problems if there are codes in the raster that do not exist
in the geodataframe. I should probably check for this condition and
raise an exception. No time right now.
"""
pred = self.compare_raster(rds, radius=radius, generous=generous,
band_index=band_index,
out_of_bounds=out_of_bounds)
truth = self.__getitem__(self.habcodefld)
truth.name = 'truth'
pred.name = 'pred'
preddf = pd.concat((truth, pred), axis=1)
if not with_unclassed:
# Get rid of any row that has a zero in it
preddf = preddf[(preddf!=0).all(1)]
return preddf
def error_matrix(self, rds, radius=0, generous=False, band_index=0,
out_of_bounds=np.nan, with_unclassed=False):
from sklearn.metrics import confusion_matrix
compdf = self.comparison_df(rds, radius=radius, generous=generous,
band_index=band_index,
out_of_bounds=out_of_bounds,
with_unclassed=with_unclassed).dropna()
# scikit-learn returns pred on x and true on y. I want it the other
# way around so .T
em = confusion_matrix(compdf.truth, compdf.pred).T.view(ErrorMatrix)
codes = np.sort(np.unique(compdf.dropna()))
em.categories = map(lambda s: self.codes_habitat.get(s, "Unclassified"),
codes)
return em
def compare_raster(self, rds, radius=0, generous=False, band_index=0,
out_of_bounds=np.nan):
"""
Compare habitat codes in `gdf` with codes in corresponding locations of
a raster habitat map (`rds`). This can be an exact point to point
comparison (when `radius`=0) or can be more forgiving. When `radius`>0
and `generous` is `False`, the mode (most common) value within `radius`
of each point will be returned. When `radius`>0 and `generous` is True,
ground truth habitat codes will be returned if found within `radius` of
each point, and the mode will be returned if not.
Parameters
----------
rds : OpticalRS.RasterDS
The habitat map (or whatever raster) you want to compare to the
`GroundTruthShapefile` (self). The projection of this raster must
match the projection of the `GroundTruthShapefile`. If it doesn't
match, you might get results but they'll be wrong.
radius : float
The radius with which to buffer `point`. The units of this value
depend on the projection being used.
generous : boolean
If False (default), mode will be returned. If True, habitat code will be
returned if within `radius`. See function description for more info.
band_index : int
Index of the image band to sample. Zero indexed (band 1 = 0). For
single band rasters, this should be left at the default value (0).
out_of_bounds : float, int, or nan (default)
If `point` is not within `self.raster_extent`, `out_of_bounds` will
be returned.
Returns
-------
pandas Series
The values from `rds` that correspond to each point in `gdf`.
"""
column = self.habcodefld
if generous:
rcheck = lambda row: rds.radiused_point_check(row.geometry,
radius=radius,
search_value=row[column],
band_index=band_index,
out_of_bounds=out_of_bounds)
else:
rcheck = lambda row: rds.radiused_point_check(row.geometry,
radius=radius,
search_value=None,
band_index=band_index,
out_of_bounds=out_of_bounds)
return self.apply(rcheck, axis=1)
class GroundTruthShapefile(object):
"""
This class contains code for relating point ground truth shapefiles (such as
the ones generated by Benthic Photo Survey) to raster maps. The default
values (for `habfield` and `habcodefield`) assume that there's a field
called habitat that contains a text description of the habitat class for
each point.
"""
def __init__(self, file_path, habfield='habitat', habcodefield='hab_num'):
self.habfield = habfield
self.habcodefld = habcodefield
self.file_path = file_path
self.ds = open_shapefile(self.file_path)
self.hab_dict = self.__setup_hab_dict()
self.legit_habs = sorted( [ h for h in self.habitats if h ] ) # Exclude None as a habitat value
self.habitat_codes = self.__setup_hab_codes() # dict( zip( legit_habs, range( 1, len(legit_habs) + 1 ) ) )
def __setup_hab_dict(self):
"""
The hab_dict is a dictionary that contains a list of ogr features for
each habitat key.
"""
hab_dict = {}
for hab in self.habitats:
hab_dict[hab] = [f for f in self.features if f.__getattr__(self.habfield)==hab]
return hab_dict
def __setup_hab_codes(self):
"""
There should be habitat codes in the shapefile in a field called
hab_num. We need to get them and set up the matching names. This only
works for BPS shapefiles with a hab_num field set up to match the
habitat field. If `self.habfield` is set to something else, we'll just
generate integer codes.
"""
# Exclude None from list of habitats
hcd = {}
if self.habcodefld is not None:
for hab in self.legit_habs:
feat = self.hab_dict[hab][0]
hcd[hab] = feat.__getattr__(self.habcodefld)
else:
for i, hab in enumerate(self.legit_habs):
hcd[hab] = i+1 # +1 to make it not zero indexed
return hcd
@property
def features(self):
fts = [f for f in self.ds.GetLayer()]
self.ds.GetLayer().ResetReading()
return fts
@property
def habitats(self):
habs = sorted( set([f.__getattr__(self.habfield) for f in self.features]))
return habs
@property
def legit_habs_code_sorted(self):
"""
Return the legit habitats sorted by order of their numeric codes.
"""
return [v for k,v in sorted(self.codes_habitat.items())]
@property
def | (self):
"""
Return a GeoPandas GeoDataFrame object.
"""
gtgdf = GroundTruthGDF.from_file(self.file_path, habfield=self.habfield,
habcodefield=self.habcodefld)
# gtgdf = gpd.GeoDataFrame.from_file(self.file_path)
return gtgdf
def geopandas_subset(self, query, file_name=None):
"""
Create a `GroundTruthShapefile` based on a geopandas subset of
`self.geo_data_frame`. If `file_name` is `None` (default), then the file
will only be temporarily saved. It will be deleted before this function
returns. This seems to work fine for generating error matrices from
subsets but it could have unintended consequences elsewhere. If you
provide a `file_name`, a shapefile will be saved from the output.
Parameters
----------
query : string or pandas Series
If `query` is a string, `pandas.DataFrame.query` will be used to
generate the subset. Otherwise, query is assumed to be a series that
can be used to index `self.geo_data_frame`.
file_name : string file path or None
If `None`, a temporary shapefile will be created and immediately
deleted. Otherwise, the subset will be saved as a shapefile.
Returns
-------
GroundTruthShapefile
A `GroundTruthShapefile` object containing only the selected subset
of features.
"""
if file_name is None:
tdir = mkdtemp()
tfn = os.path.join(tdir, 'temp.shp')
else:
tfn = file_name
if type(query) is str:
gdf = self.geo_data_frame.query(query)
else:
gdf = self.geo_data_frame[query]
# save the subset to a file
gdf.to_file(tfn)
# make a new GroundTruthShapefile
gts = GroundTruthShapefile(tfn, self.habfield, self.habcodefld)
if file_name is None:
shutil.rmtree(tdir)
return gts
@property
def spatial_reference(self):
"""
Return the OGR spatial reference object for the shapefile.
"""
return self.ds.GetLayer().GetSpatialRef()
@property
def projection_wkt(self):
"""
Return the well known text (WKT) representation of the shapefile's projection.
"""
return self.spatial_reference.ExportToWkt()
@property
def projcs(self):
"""
Return the PROJCS value from the shapefile's spatial reference. This is
basically the name of the projection. ...I think.
"""
return self.spatial_reference.GetAttrValue('PROJCS')
@property
def geometry_type(self):
"""
Just return whether it's a type of point, line, or polygon.
"""
type_name = ogr.GeometryTypeToName( self.ds.GetLayer().GetGeomType() ).lower()
if type_name.find('point') <> -1:
return 'point'
elif type_name.find('line') <> -1:
return 'line'
elif type_name.find('polygon') <> -1:
return 'polygon'
else:
return None
@property
def hab_colors(self):
"""
return a dictionary with hab codes as keys and hab colors as values.
"""
legit_habs = sorted( [ h for h in self.habitats if h ] )
hcd = {}
for hab in legit_habs:
feat = self.hab_dict[hab][0]
hcd[hab] = feat.hab_color
return hcd
@property
def codes_habitat(self):
"""
Return a dictionary just like habitat_codes only backwards.
"""
chd = {}
for k,v in self.habitat_codes.items():
chd[v] = k
return chd
@property
def qgis_vector(self):
qvl = QgsVectorLayer(self.file_path,'grnd_truth','ogr')
if qvl.isValid():
return qvl
else:
raise Exception("Failed to create a QGis Vector Layer. QGis provider path problems, perhaps?")
def buffer(self, radius=1.0, file_path=None):
"""
Buffer the geometries in `self` and return a new `ogr` datasource. If
`file_path` is `None`, just create the datasource in memory. If a file
path is given, write out a shapefile. All fields and values (aside from
geometry) are cloned.
"""
if file_path == None:
drvname = 'Memory'
else:
drvname = 'ESRI Shapefile'
srcds = self.ds
# get projection
lyr = srcds.GetLayer(0)
sptrf = lyr.GetSpatialRef()
proj = osr.SpatialReference()
proj.ImportFromWkt(sptrf.ExportToWkt())
drv = ogr.GetDriverByName(drvname)
if file_path == None:
dst_ds = drv.CreateDataSource('out')
elif os.path.exists(file_path):
raise Exception("{} already exists!".format(file_path))
else:
dst_ds = drv.CreateDataSource(file_path)
dst_lyr = dst_ds.CreateLayer('', srs=proj, geom_type=ogr.wkbPolygon)
# copy all the fields to the destination ds
featr = lyr.GetFeature(0)
nfields = featr.GetFieldCount()
for i in range(nfields):
fld = featr.GetFieldDefnRef(i)
dst_lyr.CreateField(fld)
feat_defn = dst_lyr.GetLayerDefn()
# reset the feature counter
lyr.ResetReading()
# buffer the geometries and copy the fields
for i in range(lyr.GetFeatureCount()):
# get the feature and geometry
feat = lyr.GetFeature(i)
geom = feat.GetGeometryRef()
# create a new feature
newfeat = feat.Clone()
# get the buffered geometry
bufgeom = geom.Buffer(radius)
# set the new geometry to the buffered geom
newfeat.SetGeometry(bufgeom)
# add the new feature to the destination layer
dst_lyr.CreateFeature(newfeat)
# clean up
newfeat.Destroy()
feat.Destroy()
# ensure the new features are written
dst_lyr.SyncToDisk()
return dst_ds
def rasterize(self, buffer_radius=None, raster_template=None,
pixel_size=1.99976, value_field='hab_num', float_values=False,
array_only=False, out_file_path=None):
"""
Return a raster that can be used for classification training.
buffer_radius: A float value in projection units to buffer the
geometries by. If buffer_radius is left None then only pixels right
under points will be classified.
raster_template: A RasterDS object. If supplied, the resulting
rasterized image will have the same extent and geotransform as the
template. Also, if a raster_template is provided, the pixel_size keyword
value will be ignored and pixel size will come from the template.
pixel_size: A float value representing pixel size in projection units.
This value will be ignored if a raster_template is supplied.
value_field: A string representing the name of the field in the
shapefile that holds the numeric code that will be burned into the
raster output as the pixel value.
float_values: Boolean. If `True`, the output raster will contain floats.
If `False`, the output will be integers. Default is `False`.
array_only: A boolean. If true we'll try to just write the raster to
memory and not to disk. If you don't need to keep the raster, this will
just keep you from having to clean up useless files later. Then we'll
just return an array instead of GroundTruthRaster object.
out_file_path: String. Path to the raster file output. If `None`
(default) and `array_only=False`, a file name based on the
`GroundTruthShapefile` file name will be created. If `array_only=True`,
`out_file_path` is ignored.
"""
if float_values:
datatype = gdal.GDT_Float32
else:
datatype = gdal.GDT_Byte
# Make a copy of the layer's data source because we'll need to
# modify its attributes table
if buffer_radius:
source_ds = ogr.GetDriverByName("Memory").CopyDataSource( self.buffer(radius=buffer_radius), "" )
else:
source_ds = ogr.GetDriverByName("Memory").CopyDataSource( self.ds, "")
source_layer = source_ds.GetLayer(0)
source_srs = source_layer.GetSpatialRef()
if raster_template:
gTrans = raster_template.gdal_ds.GetGeoTransform()
pixsizeX = gTrans[1]
pixsizeY = gTrans[5]
x_res = raster_template.gdal_ds.RasterXSize
y_res = raster_template.gdal_ds.RasterYSize
rdsarr = raster_template.band_array
# if np.ma.is_masked(rdsarr):
# mask = rdsarr[...,0].mask
# else:
# mask = None
else:
x_min, x_max, y_min, y_max = source_layer.GetExtent()
# Create the destination data source
x_res = int((x_max - x_min) / pixel_size)
y_res = int((y_max - y_min) / pixel_size)
if out_file_path:
targ_fn = out_file_path
else:
# make a target ds with filename based on source filename
targ_fn = self.file_path.rsplit(os.path.extsep, 1)[0] + '_rast' + os.path.extsep + 'tif'
# print "x_res: %i, y_res: %i" % (x_res,y_res)
target_ds = gdal.GetDriverByName('GTiff').Create(targ_fn, x_res, y_res, 1, datatype)
if raster_template:
# Use the raster template supplied so that we get the same extent as the raster
# we're trying to classify
target_ds.SetGeoTransform( gTrans )
else:
# None supplied so use the pixel_size value and the extent of the shapefile
target_ds.SetGeoTransform(( x_min, pixel_size, 0, y_max, 0, -pixel_size, ))
if raster_template:
target_ds.SetProjection( raster_template.gdal_ds.GetProjection() )
elif source_srs:
# Make the target raster have the same projection as the source
target_ds.SetProjection(source_srs.ExportToWkt())
else:
# Source has no projection (needs GDAL >= 1.7.0 to work)
target_ds.SetProjection('LOCAL_CS["arbitrary"]')
# Rasterize
err = gdal.RasterizeLayer(target_ds, [1], source_layer,
burn_values=[0],
options=["ATTRIBUTE=%s" % value_field])
if err != 0:
raise Exception("error rasterizing layer: %s" % err)
# clean up
source_layer = None
source_srs = None
source_ds = None
if array_only:
out_array = target_ds.ReadAsArray()
target_ds = None
os.remove( targ_fn )
return out_array
else:
target_ds = None
return RasterDS(targ_fn)
def error_matrix(self, classification_ds, with_unclassed=False):
"""
Take a RasterDS (classification_ds) and create a user / producer
accuracy table. Return as an array so it can be displayed in multiple
ways. See the `ErrorMatrix` module for more information on the returned
object.
Parameters
----------
classification_ds : OpticalRS.RasterDS
The habitat map (or whatever raster) you want to compare to the
`GroundTruthShapefile` (self). The projection of this raster must
match the projection of the `GroundTruthShapefile`. If it doesn't
match, you might get results but they'll be wrong.
Returns
-------
ErrorMatrix
See the `ErrorMatrix` module for more information on the returned
object.
Notes
-----
This function should be merged in some way with `error_matrix_buffered`.
There's a bunch of redundancy between the two. I don't have time to do
it right now.
"""
maxcode = max(self.habitat_codes.values())
if with_unclassed:
maxcode += 1
errmat = np.zeros((maxcode, maxcode), int)
cats = list()
rext = classification_ds.raster_extent
for hab,code in self.habitat_codes.items():
for feature in self.hab_dict[hab]:
ref_val = code
geom = feature.geometry()
pnt = shpl.geometry.base.geom_from_wkb(geom.ExportToWkb())
if pnt.within(rext):
cls_val = classification_ds.value_at_point( geom )
else:
# this means that the point is not within the raster
# I think that means we don't want to count this point at
# all in the accuracy assessment.
continue
if with_unclassed:
errmat[ cls_val ][ ref_val ] += 1
elif cls_val == 0:
# If we're not including unclassified values
# we don't want this showing up in the totals.
continue
else:
errmat[ cls_val - 1 ][ ref_val - 1 ] += 1
# Get rid of all zero rows and columns. This can happen if hab codes
# skip an integer.
em = errmat.view( ErrorMatrix ).clean_zeros(with_unclassed)
# Rows and Columns of errmat end up sorted by hab code. This next line
# will give the habitat names sorted by hab code number.
if with_unclassed:
em.categories = ['Unclassified'] + sorted(self.habitat_codes, key=self.habitat_codes.get)
else:
em.categories = sorted(self.habitat_codes, key=self.habitat_codes.get)
return em
def error_matrix_buffered(self, classification_ds, radius=2.0, with_unclassed=False):
"""
Take a RasterDS (classification_ds) and create a user / producer
accuracy table. Ground Truth points will be buffered and matching
habitat codes within `radius` of a point will be considered success.
Return as an array so it can be displayed in multiple ways. See the
`ErrorMatrix` module for more information on the returned object.
Parameters
----------
classification_ds : OpticalRS.RasterDS
The habitat map (or whatever raster) you want to compare to the
`GroundTruthShapefile` (self). The projection of this raster must
match the projection of the `GroundTruthShapefile`. If it doesn't
match, you might get results but they'll be wrong.
radius : float
The radius with which to buffer points. The units of this value
depend on the projection being used. You can use
`GroundTruthShapefile.projection_wkt` to examine the projection and
find the units.
Returns
-------
ErrorMatrix
See the `ErrorMatrix` module for more information on the returned
object.
"""
maxcode = max(self.habitat_codes.values())
if with_unclassed:
maxcode += 1
errmat = np.zeros((maxcode, maxcode), int)
cats = list()
rext = classification_ds.raster_extent
for hab,code in self.habitat_codes.items():
for feature in self.hab_dict[hab]:
ref_val = code
geom = feature.geometry()
pnt = shpl.geometry.base.geom_from_wkb(geom.ExportToWkb())
if pnt.within(rext):
clsarr = classification_ds.geometry_subset(pnt.buffer(radius),
all_touched=True)
else:
# this means that the point is not within the raster
# I think that means we don't want to count this point at
# all in the accuracy assessment.
continue
if ref_val in clsarr.compressed():
cls_val = ref_val # this counts as success
elif not pnt.within(rext):
# this means that the point is not within the raster
# I think that means we don't want to count this point at
# all in the accuracy assessment.
continue
else:
# our reference value was not found within radius of point
# so we'll report it as the most common class within radius
if len(clsarr.compressed()) == 0:
cls_val = 0 # Assuming zero is code for unclassified
else:
cls_val = scipymode(clsarr.compressed()).mode.item()
if with_unclassed:
errmat[ cls_val ][ ref_val ] += 1
elif cls_val == 0:
# If we're not including unclassified values
# we don't want this showing up in the totals.
continue
else:
errmat[ cls_val - 1 ][ ref_val - 1 ] += 1
# Get rid of all zero rows and columns. This can happen if hab codes
# skip an integer.
em = errmat.view( ErrorMatrix ).clean_zeros(with_unclassed)
# Rows and Columns of errmat end up sorted by hab code. This next line
# will give the habitat names sorted by hab code number.
if with_unclassed:
em.categories = ['Unclassified'] + sorted(self.habitat_codes, key=self.habitat_codes.get)
else:
em.categories = sorted(self.habitat_codes, key=self.habitat_codes.get)
return em
@property
def hab_dict_counts(self):
ret_dict = {}
for hab in self.habitats:
ret_dict[hab] = len( self.hab_dict[hab] )
return ret_dict
def add_raster_values(self, raster_ds):
"""
The raster data source here is assumed to be a classified image. The raster
values should correspond to classes.
"""
trans = transform_dict(raster_ds)
band = raster_ds.GetRasterBand(1)
self.features = [ add_raster_value(f,trans,band) for f in self.ds.GetLayer() ]
self.ds.GetLayer().ResetReading()
self.hab_dict = self.__setup_hab_dict()
@property
def unsupervised_habitat_class_dict(self):
"""
For each habitat, give a list of raster values that correspond to the ground truth
points of that habitat type. This will be used with unsupervised classifications to
figure out which, if any, of the classes correspond to particular habitat types.
"""
try:
hcd = {}
for hab in self.habitats:
hcd[hab] = [ f.raster_value for f in self.hab_dict[hab] ]
except AttributeError:
raise AttributeError("Features need to be assigned raster values before you can create a habitat class dictionary.")
return hcd
@property
def unsupervised_habitat_class_modes(self):
hcm = {}
for hab in self.habitats:
md, cn = mode( self.unsupervised_habitat_class_dict[hab] )
if len( md )==1:
hcm[hab] = md[0]
else:
hcm[hab] = None
return hcm
def __output_training_LAN(self,img,buffer_radius=3.5,driver_str='LAN'):
"""
DEPRICATED! -> This only works for points. I think I can use the
rasterize method instead. I need to verify and then get rid of this
method. This method also has the habitat field hard coded (search for
feat.habitat). That would need to be changed to
feat.__getattr__(self.habfield) to make this work correctly.
Create a raster input for supervised classifications. img is the image
that we want to classify (in the form of a gdal datasource). Spectral
can't use tifs so we will create LAN file.
A buffer radius of 3.5 meters gives us 3 x 3 sets of pixels with our
point feature in the center. This, of course, assumes that we're dealing
with WV2 imagery and a projection with meters as the units. This works
for me on my project but might now work for others.
"""
if driver_str=='LAN':
f_ext = 'lan'
elif driver_str=='GTiff':
f_ext = 'tif'
else:
raise ValueError("At this point, the output_training_LAN method only knows how to deal with LAN and GTiff file types. Sorry.")
lyr = self.ds.GetLayer()
lyr.ResetReading()
trans = transform_dict(img)
driver = gdal.GetDriverByName(driver_str)
rows = img.RasterYSize
cols = img.RasterXSize
fname = img.GetDescription().rsplit(os.path.extsep)[0] + '_train' + os.path.extsep + f_ext
add_num = 0
while os.path.exists(fname):
add_num += 1
if add_num==1:
fname = fname.replace( os.path.extsep + f_ext, '_%i' % add_num + os.path.extsep + f_ext )
else:
old = '_%i.%s' % ( add_num - 1, f_ext )
new = '_%i.%s' % ( add_num, f_ext )
fname = fname.replace( old, new )
outDs = driver.Create(fname, cols, rows, 1, GDT_Int16)
if outDs is None:
print 'Could not create %s' % fname
sys.exit(1)
outBand = outDs.GetRasterBand(1)
pixel_count = 0
hab_pix_count = dict( zip( [h for h in self.habitats if h], np.zeros( len([h for h in self.habitats if h]), dtype=np.int ) ) )
for feat in lyr:
if not feat.habitat:
continue
if self.hab_dict_counts[feat.habitat] < 24:
continue
if buffer_radius:
geom = feat.geometry().Buffer(buffer_radius)
elp = envelope_dict(geom)
xtop = elp['xLeft']
ytop = elp['yTop']
xOffset = int( (xtop - trans['originX']) / trans['pixWidth'] )
yOffset = int( (ytop - trans['originY']) / trans['pixHeight'] )
xdist = elp['xRight'] - elp['xLeft']
ydist = elp['yBottom'] - elp['yTop']
cols = int( xdist / trans['pixWidth'] )
rows = int( ydist / trans['pixHeight'] )
pixarr = int( self.habitat_codes[feat.habitat] ) * np.ones((rows,cols), dtype=np.int16)
else:
geom = feat.geometry()
xOffset = int( (geom.GetX() - trans['originX']) / trans['pixWidth'] )
yOffset = int( (geom.GetY() - trans['originY']) / trans['pixHeight'] )
pixarr = np.array( [[ self.habitat_codes[feat.habitat] ]] )
outBand.WriteArray(pixarr,xOffset,yOffset)
pixel_count += pixarr.size
hab_pix_count[feat.habitat] += pixarr.size
outBand.FlushCache()
outBand.SetNoDataValue(0)
# georeference the image and set the projection
outDs.SetGeoTransform(img.GetGeoTransform())
outDs.SetProjection(img.GetProjection())
# build pyramids
gdal.SetConfigOption('HFA_USE_RRD', 'YES')
outDs.BuildOverviews(overviewlist=[2,4,8,16,32,64,128])
print "%i pixels total" % pixel_count
for hab in self.habitats:
if hab:
print "%i pixels for %s" % ( hab_pix_count[hab], hab )
return GroundTruthRaster( outDs.GetDescription() )
def training_classes(self, rds, buffer_radius=None,calc_stats=0):
"""
I think I should move some of this functionality over to the GroundTruthRaster class
in common.py. I'm generating classes okay from what I can tell but I get a singular
matrix error when I try to run the Gaussian Classifier. I have no idea why. Baffled,
I am.
"""
grnd_truth = self.rasterize(buffer_radius=buffer_radius,raster_template=rds,array_only=True)
sp_img = rds.spy_image.load()
return sp.create_training_classes(sp_img, grnd_truth,calc_stats=calc_stats)
def add_raster_value(feature, trans, band ):
geom = feature.geometry()
x = geom.GetX()
y = geom.GetY()
xOffset = int( (x - trans['originX']) / trans['pixWidth'] )
yOffset = int( (y - trans['originY']) / trans['pixHeight'] )
data = band.ReadAsArray(xOffset, yOffset, 1, 1)
feature.raster_value = data[0,0]
return feature
def open_shapefile(filename):
"""Take a file path string and return an ogr shape"""
# open the shapefile and get the layer
driver = ogr.GetDriverByName('ESRI Shapefile')
shp = driver.Open(filename)
if shp is None:
print 'Could not open %s' % filename
sys.exit(1)
return shp
| geo_data_frame |
stack_trace.rs | use crate::paging;
use crate::task::Task;
#[derive(Debug, Copy, Clone)]
pub struct StackFrame {
pub frame_ip: usize,
pub frame_bp: usize,
}
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
pub struct StackFrameIterator {
cur_frame: Option<StackFrame>,
}
impl StackFrameIterator {
pub fn new() -> StackFrameIterator {
unsafe {
let mut frame_ip: usize;
let mut frame_bp: usize;
llvm_asm!("mov $0, [rbp]" : "=r"(frame_bp) ::: "intel");
llvm_asm!("mov $0, [rbp+8]" : "=r"(frame_ip) ::: "intel");
StackFrameIterator {
cur_frame: Some(StackFrame { frame_ip, frame_bp }),
}
}
}
pub unsafe fn start_at(frame_ip: usize, frame_bp: usize) -> StackFrameIterator {
StackFrameIterator {
cur_frame: Some(StackFrame { frame_ip, frame_bp }),
}
}
}
|
fn next(&mut self) -> Option<Self::Item> {
if let Some(frame) = self.cur_frame.take() {
let frame_bp = frame.frame_bp;
if frame_bp < paging::KERNEL_HEAP_BASE {
return None;
}
unsafe {
if paging::direct_get_mapping(frame_bp).is_some() {
if let Some(cur_task) = Task::get_current_task() {
if !cur_task.in_stack_bounds(frame_bp + 8) {
return None;
}
}
let next_frame = frame_bp as *const usize;
let next_bp = *next_frame;
// ensure that we're always travelling _up_ the stack
if next_bp > frame_bp {
self.cur_frame = Some(StackFrame {
frame_ip: *(next_frame.offset(1)),
frame_bp: *next_frame,
});
}
}
}
Some(frame)
} else {
None
}
}
}
pub fn trace_stack() -> impl Iterator<Item = StackFrame> {
let mut it = StackFrameIterator::new();
it.next();
it.next();
it
//it.filter(|frame| frame.frame_ip >= KERNEL_BASE)
} | impl Iterator for StackFrameIterator {
type Item = StackFrame; |
cache.py | """
Cache middleware. If enabled, each Django-powered page will be cached based on
URL. The canonical way to enable cache middleware is to set
``UpdateCacheMiddleware`` as your first piece of middleware, and
``FetchFromCacheMiddleware`` as the last::
MIDDLEWARE = [
'django.middleware.cache.UpdateCacheMiddleware',
...
'django.middleware.cache.FetchFromCacheMiddleware'
]
This is counter-intuitive, but correct: ``UpdateCacheMiddleware`` needs to run
last during the response phase, which processes middleware bottom-up;
``FetchFromCacheMiddleware`` needs to run last during the request phase, which
processes middleware top-down.
The single-class ``CacheMiddleware`` can be used for some simple sites.
However, if any other piece of middleware needs to affect the cache key, you'll
need to use the two-part ``UpdateCacheMiddleware`` and
``FetchFromCacheMiddleware``. This'll most often happen when you're using
Django's ``LocaleMiddleware``.
More details about how the caching works:
* Only GET or HEAD-requests with status code 200 are cached.
* The number of seconds each page is stored for is set by the "max-age" section
of the response's "Cache-Control" header, falling back to the
CACHE_MIDDLEWARE_SECONDS setting if the section was not found.
* This middleware expects that a HEAD request is answered with the same response
headers exactly like the corresponding GET request.
* When a hit occurs, a shallow copy of the original response object is returned
from process_request.
* Pages will be cached based on the contents of the request headers listed in
the response's "Vary" header.
* This middleware also sets ETag, Last-Modified, Expires and Cache-Control
headers on the response object.
"""
from django.conf import settings
from django.core.cache import DEFAULT_CACHE_ALIAS, caches
from django.utils.cache import (
get_cache_key,
get_max_age,
has_vary_header,
learn_cache_key,
patch_response_headers,
)
from django.utils.deprecation import MiddlewareMixin
class UpdateCacheMiddleware(MiddlewareMixin):
"""
Response-phase cache middleware that updates the cache if the response is
cacheable.
Must be used as part of the two-part update/fetch cache middleware.
UpdateCacheMiddleware must be the first piece of middleware in MIDDLEWARE
so that it'll get called last during the response phase.
"""
def __init__(self, get_response):
super().__init__(get_response)
self.cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS
self.page_timeout = None
self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
self.cache = caches[self.cache_alias]
def _should_update_cache(self, request, response):
return hasattr(request, "_cache_update_cache") and request._cache_update_cache
def process_response(self, request, response):
"""Set the cache, if needed."""
if not self._should_update_cache(request, response):
# We don't need to update the cache, just return.
return response
if response.streaming or response.status_code not in (200, 304):
return response
# Don't cache responses that set a user-specific (and maybe security
# sensitive) cookie in response to a cookie-less request.
if (
not request.COOKIES
and response.cookies
and has_vary_header(response, "Cookie")
):
return response
# Don't cache a response with 'Cache-Control: private'
if "private" in response.get("Cache-Control", ()):
return response
# Page timeout takes precedence over the "max-age" and the default
# cache timeout.
timeout = self.page_timeout
if timeout is None:
# The timeout from the "max-age" section of the "Cache-Control"
# header takes precedence over the default cache timeout.
timeout = get_max_age(response)
if timeout is None:
timeout = self.cache_timeout
elif timeout == 0:
# max-age was set to 0, don't cache.
return response
patch_response_headers(response, timeout)
if timeout and response.status_code == 200:
cache_key = learn_cache_key(
request, response, timeout, self.key_prefix, cache=self.cache
)
if hasattr(response, "render") and callable(response.render):
response.add_post_render_callback(
lambda r: self.cache.set(cache_key, r, timeout)
)
else:
self.cache.set(cache_key, response, timeout)
return response
class | (MiddlewareMixin):
"""
Request-phase cache middleware that fetches a page from the cache.
Must be used as part of the two-part update/fetch cache middleware.
FetchFromCacheMiddleware must be the last piece of middleware in MIDDLEWARE
so that it'll get called last during the request phase.
"""
def __init__(self, get_response):
super().__init__(get_response)
self.key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
self.cache_alias = settings.CACHE_MIDDLEWARE_ALIAS
self.cache = caches[self.cache_alias]
def process_request(self, request):
"""
Check whether the page is already cached and return the cached
version if available.
"""
if request.method not in ("GET", "HEAD"):
request._cache_update_cache = False
return None # Don't bother checking the cache.
# try and get the cached GET response
cache_key = get_cache_key(request, self.key_prefix, "GET", cache=self.cache)
if cache_key is None:
request._cache_update_cache = True
return None # No cache information available, need to rebuild.
response = self.cache.get(cache_key)
# if it wasn't found and we are looking for a HEAD, try looking just for that
if response is None and request.method == "HEAD":
cache_key = get_cache_key(
request, self.key_prefix, "HEAD", cache=self.cache
)
response = self.cache.get(cache_key)
if response is None:
request._cache_update_cache = True
return None # No cache information available, need to rebuild.
# hit, return cached response
request._cache_update_cache = False
return response
class CacheMiddleware(UpdateCacheMiddleware, FetchFromCacheMiddleware):
"""
Cache middleware that provides basic behavior for many simple sites.
Also used as the hook point for the cache decorator, which is generated
using the decorator-from-middleware utility.
"""
def __init__(self, get_response, cache_timeout=None, page_timeout=None, **kwargs):
super().__init__(get_response)
# We need to differentiate between "provided, but using default value",
# and "not provided". If the value is provided using a default, then
# we fall back to system defaults. If it is not provided at all,
# we need to use middleware defaults.
try:
key_prefix = kwargs["key_prefix"]
if key_prefix is None:
key_prefix = ""
self.key_prefix = key_prefix
except KeyError:
pass
try:
cache_alias = kwargs["cache_alias"]
if cache_alias is None:
cache_alias = DEFAULT_CACHE_ALIAS
self.cache_alias = cache_alias
self.cache = caches[self.cache_alias]
except KeyError:
pass
if cache_timeout is not None:
self.cache_timeout = cache_timeout
self.page_timeout = page_timeout
| FetchFromCacheMiddleware |
test_nova.py | # Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright (c) 2012 X.commerce, a business unit of eBay 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.
from __future__ import absolute_import
from django.conf import settings
from django.test.utils import override_settings
import mock
from novaclient import api_versions
from novaclient import exceptions as nova_exceptions
from novaclient.v2 import flavor_access as nova_flavor_access
from novaclient.v2 import servers
from horizon import exceptions as horizon_exceptions
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
class ServerWrapperTests(test.TestCase):
use_mox = False
def test_get_base_attribute(self):
server = api.nova.Server(self.servers.first(), self.request)
self.assertEqual(self.servers.first().id, server.id)
@mock.patch.object(api.glance, 'image_get')
def test_image_name(self, mock_image_get):
image = self.images.first()
mock_image_get.return_value = image
server = api.nova.Server(self.servers.first(), self.request)
self.assertEqual(image.name, server.image_name)
mock_image_get.assert_called_once_with(test.IsHttpRequest(), image.id)
@mock.patch.object(api.glance, 'image_get')
def test_image_name_no_glance_service(self, mock_image_get):
|
class ComputeApiTests(test.APIMockTestCase):
def _mock_current_version(self, mock_novaclient, version,
min_version=None):
ver = mock.Mock()
ver.min_version = min_version or '2.1'
ver.version = version
mock_novaclient.versions.get_current.return_value = ver
# To handle upgrade_api
self.novaclient.api_version = api_versions.APIVersion(version)
def test_server_reboot(self):
server = self.servers.first()
HARDNESS = servers.REBOOT_HARD
novaclient = self.stub_novaclient()
novaclient.servers.reboot.return_value = None
ret_val = api.nova.server_reboot(self.request, server.id)
self.assertIsNone(ret_val)
novaclient.servers.reboot.assert_called_once_with(
server.id, HARDNESS)
def test_server_soft_reboot(self):
server = self.servers.first()
HARDNESS = servers.REBOOT_SOFT
novaclient = self.stub_novaclient()
novaclient.servers.reboot.return_value = None
ret_val = api.nova.server_reboot(self.request, server.id, HARDNESS)
self.assertIsNone(ret_val)
novaclient.servers.reboot.assert_called_once_with(
server.id, HARDNESS)
def test_server_vnc_console(self):
server = self.servers.first()
console = self.servers.vnc_console_data
console_type = console["console"]["type"]
novaclient = self.stub_novaclient()
novaclient.servers.get_vnc_console.return_value = console
ret_val = api.nova.server_vnc_console(self.request,
server.id,
console_type)
self.assertIsInstance(ret_val, api.nova.VNCConsole)
novaclient.servers.get_vnc_console.assert_called_once_with(
server.id, console_type)
def test_server_spice_console(self):
server = self.servers.first()
console = self.servers.spice_console_data
console_type = console["console"]["type"]
novaclient = self.stub_novaclient()
novaclient.servers.get_spice_console.return_value = console
ret_val = api.nova.server_spice_console(self.request,
server.id,
console_type)
self.assertIsInstance(ret_val, api.nova.SPICEConsole)
novaclient.servers.get_spice_console.assert_called_once_with(
server.id, console_type)
def test_server_rdp_console(self):
server = self.servers.first()
console = self.servers.rdp_console_data
console_type = console["console"]["type"]
novaclient = self.stub_novaclient()
novaclient.servers.get_rdp_console.return_value = console
ret_val = api.nova.server_rdp_console(self.request,
server.id,
console_type)
self.assertIsInstance(ret_val, api.nova.RDPConsole)
novaclient.servers.get_rdp_console.assert_called_once_with(
server.id, console_type)
def test_server_mks_console(self):
server = self.servers.first()
console = self.servers.mks_console_data
console_type = console["remote_console"]["type"]
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.53')
novaclient.servers.get_mks_console.return_value = console
ret_val = api.nova.server_mks_console(self.request,
server.id,
console_type)
self.assertIsInstance(ret_val, api.nova.MKSConsole)
novaclient.versions.get_current.assert_called_once_with()
novaclient.servers.get_mks_console.assert_called_once_with(
server.id, console_type)
def test_server_list(self):
servers = self.servers.list()
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.40')
novaclient.servers.list.return_value = servers
ret_val, has_more = api.nova.server_list(
self.request,
search_opts={'all_tenants': True})
for server in ret_val:
self.assertIsInstance(server, api.nova.Server)
novaclient.versions.get_current.assert_called_once_with()
novaclient.servers.list.assert_called_once_with(
True, {'all_tenants': True})
def test_server_list_pagination(self):
page_size = getattr(settings, 'API_RESULT_PAGE_SIZE', 20)
servers = self.servers.list()
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.45')
novaclient.servers.list.return_value = servers
ret_val, has_more = api.nova.server_list(self.request,
{'marker': None,
'paginate': True,
'all_tenants': True})
for server in ret_val:
self.assertIsInstance(server, api.nova.Server)
self.assertFalse(has_more)
novaclient.versions.get_current.assert_called_once_with()
novaclient.servers.list.assert_called_once_with(
True,
{'all_tenants': True,
'marker': None,
'limit': page_size + 1})
@override_settings(API_RESULT_PAGE_SIZE=1)
def test_server_list_pagination_more(self):
page_size = getattr(settings, 'API_RESULT_PAGE_SIZE', 1)
servers = self.servers.list()
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.45')
novaclient.servers.list.return_value = servers[:page_size + 1]
ret_val, has_more = api.nova.server_list(self.request,
{'marker': None,
'paginate': True,
'all_tenants': True})
for server in ret_val:
self.assertIsInstance(server, api.nova.Server)
self.assertEqual(page_size, len(ret_val))
self.assertTrue(has_more)
novaclient.versions.get_current.assert_called_once_with()
novaclient.servers.list.assert_called_once_with(
True,
{'all_tenants': True,
'marker': None,
'limit': page_size + 1})
def test_usage_get(self):
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.1')
novaclient.usages.get.return_value = self.usages.first()
ret_val = api.nova.usage_get(self.request, self.tenant.id,
'start', 'end')
self.assertIsInstance(ret_val, api.nova.NovaUsage)
novaclient.versions.get_current.assert_called_once_with()
novaclient.usage.get.assert_called_once_with(
self.tenant.id, 'start', 'end')
def test_usage_get_paginated(self):
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.40')
novaclient.usage.get.side_effect = [
self.usages.first(),
{},
]
ret_val = api.nova.usage_get(self.request, self.tenant.id,
'start', 'end')
self.assertIsInstance(ret_val, api.nova.NovaUsage)
novaclient.versions.get_current.assert_called_once_with()
novaclient.usage.get.assert_has_calls([
mock.call(self.tenant.id, 'start', 'end'),
mock.call(self.tenant.id, 'start', 'end',
marker=u'063cf7f3-ded1-4297-bc4c-31eae876cc93'),
])
def test_usage_list(self):
usages = self.usages.list()
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.1')
novaclient.usage.list.return_value = usages
ret_val = api.nova.usage_list(self.request, 'start', 'end')
for usage in ret_val:
self.assertIsInstance(usage, api.nova.NovaUsage)
novaclient.versions.get_current.assert_called_once_with()
novaclient.usage.list.assert_called_once_with('start', 'end', True)
def test_usage_list_paginated(self):
usages = self.usages.list()
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.40')
novaclient.usage.list.side_effect = [
usages,
{},
]
ret_val = api.nova.usage_list(self.request, 'start', 'end')
for usage in ret_val:
self.assertIsInstance(usage, api.nova.NovaUsage)
novaclient.versions.get_current.assert_called_once_with()
novaclient.usage.list.assert_has_calls([
mock.call('start', 'end', True),
mock.call('start', 'end', True,
marker=u'063cf7f3-ded1-4297-bc4c-31eae876cc93'),
])
def test_server_get(self):
server = self.servers.first()
novaclient = self.stub_novaclient()
self._mock_current_version(novaclient, '2.45')
novaclient.servers.get.return_value = server
ret_val = api.nova.server_get(self.request, server.id)
self.assertIsInstance(ret_val, api.nova.Server)
novaclient.versions.get_current.assert_called_once_with()
novaclient.servers.get.assert_called_once_with(server.id)
def test_server_metadata_update(self):
server = self.servers.first()
metadata = {'foo': 'bar'}
novaclient = self.stub_novaclient()
novaclient.servers.set_meta.return_value = None
ret_val = api.nova.server_metadata_update(self.request,
server.id,
metadata)
self.assertIsNone(ret_val)
novaclient.servers.set_meta.assert_called_once_with(server.id,
metadata)
def test_server_metadata_delete(self):
server = self.servers.first()
keys = ['a', 'b']
novaclient = self.stub_novaclient()
novaclient.servers.delete_meta.return_value = None
ret_val = api.nova.server_metadata_delete(self.request,
server.id,
keys)
self.assertIsNone(ret_val)
novaclient.servers.delete_meta.assert_called_once_with(server.id, keys)
def _test_absolute_limits(self, values, expected_results):
limits = mock.Mock()
limits.absolute = []
for key, val in values.items():
limit = mock.Mock()
limit.name = key
limit.value = val
limits.absolute.append(limit)
novaclient = self.stub_novaclient()
novaclient.limits.get.return_value = limits
ret_val = api.nova.tenant_absolute_limits(self.request, reserved=True)
for key in expected_results.keys():
self.assertEqual(expected_results[key], ret_val[key])
novaclient.limits.get.assert_called_once_with(reserved=True,
tenant_id=None)
def test_absolute_limits_handle_unlimited(self):
values = {"maxTotalCores": -1, "maxTotalInstances": 10}
expected_results = {"maxTotalCores": float("inf"),
"maxTotalInstances": 10}
self._test_absolute_limits(values, expected_results)
def test_absolute_limits_negative_used_workaround(self):
values = {"maxTotalCores": -1,
"maxTotalInstances": 10,
"totalInstancesUsed": -1,
"totalCoresUsed": -1,
"totalRAMUsed": -2048,
"totalSecurityGroupsUsed": 1,
"totalFloatingIpsUsed": 0,
}
expected_results = {"maxTotalCores": float("inf"),
"maxTotalInstances": 10,
"totalInstancesUsed": 0,
"totalCoresUsed": 0,
"totalRAMUsed": 0,
"totalSecurityGroupsUsed": 1,
"totalFloatingIpsUsed": 0,
}
self._test_absolute_limits(values, expected_results)
def test_cold_migrate_host_succeed(self):
hypervisor = self.hypervisors.first()
novaclient = self.stub_novaclient()
novaclient.hypervisors.search.return_value = [hypervisor]
novaclient.servers.migrate.return_value = None
ret_val = api.nova.migrate_host(self.request, "host", False, True,
True)
self.assertTrue(ret_val)
novaclient.hypervisors.search.assert_called_once_with('host', True)
novaclient.servers.migrate.assert_called_once_with('test_uuid')
def test_cold_migrate_host_fails(self):
hypervisor = self.hypervisors.first()
novaclient = self.stub_novaclient()
novaclient.hypervisors.search.return_value = [hypervisor]
novaclient.servers.migrate.side_effect = \
nova_exceptions.ClientException(404)
self.assertRaises(nova_exceptions.ClientException,
api.nova.migrate_host,
self.request, "host", False, True, True)
novaclient.hypervisors.search.assert_called_once_with('host', True)
novaclient.servers.migrate.assert_called_once_with('test_uuid')
def test_live_migrate_host_with_active_vm(self):
hypervisor = self.hypervisors.first()
server = self.servers.first()
novaclient = self.stub_novaclient()
server_uuid = hypervisor.servers[0]["uuid"]
self._mock_current_version(novaclient, '2.45')
novaclient.hypervisors.search.return_value = [hypervisor]
novaclient.servers.get.return_value = server
novaclient.servers.live_migrate.return_value = None
ret_val = api.nova.migrate_host(self.request, "host", True, True,
True)
self.assertTrue(ret_val)
novaclient.versions.get_current.assert_called_once_with()
novaclient.hypervisors.search.assert_called_once_with('host', True)
novaclient.servers.get.assert_called_once_with(server_uuid)
novaclient.servers.live_migrate.assert_called_once_with(
server_uuid, None, True, True)
def test_live_migrate_host_with_paused_vm(self):
hypervisor = self.hypervisors.first()
server = self.servers.list()[3]
novaclient = self.stub_novaclient()
server_uuid = hypervisor.servers[0]["uuid"]
self._mock_current_version(novaclient, '2.45')
novaclient.hypervisors.search.return_value = [hypervisor]
novaclient.servers.get.return_value = server
novaclient.servers.live_migrate.return_value = None
ret_val = api.nova.migrate_host(self.request, "host", True, True, True)
self.assertTrue(ret_val)
novaclient.versions.get_current.assert_called_once_with()
novaclient.hypervisors.search.assert_called_once_with('host', True)
novaclient.servers.get.assert_called_once_with(server_uuid)
novaclient.servers.live_migrate.assert_called_once_with(
server_uuid, None, True, True)
def test_live_migrate_host_without_running_vm(self):
hypervisor = self.hypervisors.first()
server = self.servers.list()[1]
novaclient = self.stub_novaclient()
server_uuid = hypervisor.servers[0]["uuid"]
self._mock_current_version(novaclient, '2.45')
novaclient.hypervisors.search.return_value = [hypervisor]
novaclient.servers.get.return_value = server
novaclient.servers.migrate.return_value = None
ret_val = api.nova.migrate_host(self.request, "host", True, True, True)
self.assertTrue(ret_val)
novaclient.versions.get_current.assert_called_once_with()
novaclient.hypervisors.search.assert_called_once_with('host', True)
novaclient.servers.get.assert_called_once_with(server_uuid)
novaclient.servers.migrate.assert_called_once_with(server_uuid)
"""Flavor Tests"""
def test_flavor_list_no_extras(self):
flavors = self.flavors.list()
novaclient = self.stub_novaclient()
novaclient.flavors.list.return_value = flavors
api_flavors = api.nova.flavor_list(self.request)
self.assertEqual(len(flavors), len(api_flavors))
novaclient.flavors.list.assert_called_once_with(is_public=True)
def test_flavor_get_no_extras(self):
flavor = self.flavors.list()[1]
novaclient = self.stub_novaclient()
novaclient.flavors.get.return_value = flavor
api_flavor = api.nova.flavor_get(self.request, flavor.id)
self.assertEqual(api_flavor.id, flavor.id)
novaclient.flavors.get.assert_called_once_with(flavor.id)
def _test_flavor_list_paged(self, reversed_order=False, paginate=True):
page_size = getattr(settings, 'API_RESULT_PAGE_SIZE', 20)
flavors = self.flavors.list()
order = 'asc' if reversed_order else 'desc'
novaclient = self.stub_novaclient()
novaclient.flavors.list.return_value = flavors
api_flavors, has_more, has_prev = api.nova.flavor_list_paged(
self.request, True, False, None, paginate=paginate,
reversed_order=reversed_order)
for flavor in api_flavors:
self.assertIsInstance(flavor, type(flavors[0]))
self.assertFalse(has_more)
self.assertFalse(has_prev)
if paginate:
novaclient.flavors.list.assert_called_once_with(
is_public=True, marker=None, limit=page_size + 1,
sort_key='name', sort_dir=order)
else:
novaclient.flavors.list.assert_called_once_with(
is_public=True)
@override_settings(API_RESULT_PAGE_SIZE=1)
def test_flavor_list_pagination_more_and_prev(self):
page_size = getattr(settings, 'API_RESULT_PAGE_SIZE', 1)
flavors = self.flavors.list()
marker = flavors[0].id
novaclient = self.stub_novaclient()
novaclient.flavors.list.return_value = flavors[1:page_size + 2]
api_flavors, has_more, has_prev = api.nova\
.flavor_list_paged(
self.request,
True,
False,
marker,
paginate=True)
for flavor in api_flavors:
self.assertIsInstance(flavor, type(flavors[0]))
self.assertEqual(page_size, len(api_flavors))
self.assertTrue(has_more)
self.assertTrue(has_prev)
novaclient.flavors.list.assert_called_once_with(
is_public=True, marker=marker, limit=page_size + 1,
sort_key='name', sort_dir='desc')
def test_flavor_list_paged_default_order(self):
self._test_flavor_list_paged()
def test_flavor_list_paged_reversed_order(self):
self._test_flavor_list_paged(reversed_order=True)
def test_flavor_list_paged_paginate_false(self):
self._test_flavor_list_paged(paginate=False)
def test_flavor_create(self):
flavor = self.flavors.first()
novaclient = self.stub_novaclient()
novaclient.flavors.create.return_value = flavor
api_flavor = api.nova.flavor_create(self.request,
flavor.name,
flavor.ram,
flavor.vcpus,
flavor.disk)
self.assertIsInstance(api_flavor, type(flavor))
self.assertEqual(flavor.name, api_flavor.name)
self.assertEqual(flavor.ram, api_flavor.ram)
self.assertEqual(flavor.vcpus, api_flavor.vcpus)
self.assertEqual(flavor.disk, api_flavor.disk)
self.assertEqual(0, api_flavor.ephemeral)
self.assertEqual(0, api_flavor.swap)
self.assertTrue(api_flavor.is_public)
self.assertEqual(1, api_flavor.rxtx_factor)
novaclient.flavors.create.assert_called_once_with(
flavor.name, flavor.ram, flavor.vcpus, flavor.disk,
flavorid='auto', ephemeral=0, swap=0, is_public=True,
rxtx_factor=1)
def test_flavor_delete(self):
flavor = self.flavors.first()
novaclient = self.stub_novaclient()
novaclient.flavors.delete.return_value = None
api_val = api.nova.flavor_delete(self.request, flavor.id)
self.assertIsNone(api_val)
novaclient.flavors.delete.assert_called_once_with(flavor.id)
def test_flavor_access_list(self):
flavor_access = self.flavor_access.list()
flavor = [f for f in self.flavors.list() if f.id ==
flavor_access[0].flavor_id][0]
novaclient = self.stub_novaclient()
novaclient.flavor_access.list.return_value = flavor_access
api_flavor_access = api.nova.flavor_access_list(self.request, flavor)
self.assertEqual(len(flavor_access), len(api_flavor_access))
for access in api_flavor_access:
self.assertIsInstance(access, nova_flavor_access.FlavorAccess)
self.assertEqual(access.flavor_id, flavor.id)
novaclient.flavor_access.list.assert_called_once_with(flavor=flavor)
def test_add_tenant_to_flavor(self):
flavor_access = [self.flavor_access.first()]
flavor = [f for f in self.flavors.list() if f.id ==
flavor_access[0].flavor_id][0]
tenant = [t for t in self.tenants.list() if t.id ==
flavor_access[0].tenant_id][0]
novaclient = self.stub_novaclient()
novaclient.flavor_access.add_tenant_access.return_value = flavor_access
api_flavor_access = api.nova.add_tenant_to_flavor(self.request,
flavor,
tenant)
self.assertIsInstance(api_flavor_access, list)
self.assertEqual(len(flavor_access), len(api_flavor_access))
for access in api_flavor_access:
self.assertEqual(access.flavor_id, flavor.id)
self.assertEqual(access.tenant_id, tenant.id)
novaclient.flavor_access.add_tenant_access.assert_called_once_with(
flavor=flavor, tenant=tenant)
def test_remove_tenant_from_flavor(self):
flavor_access = [self.flavor_access.first()]
flavor = [f for f in self.flavors.list() if f.id ==
flavor_access[0].flavor_id][0]
tenant = [t for t in self.tenants.list() if t.id ==
flavor_access[0].tenant_id][0]
novaclient = self.stub_novaclient()
novaclient.flavor_access.remove_tenant_access.return_value = []
api_val = api.nova.remove_tenant_from_flavor(self.request,
flavor,
tenant)
self.assertEqual(len(api_val), len([]))
self.assertIsInstance(api_val, list)
novaclient.flavor_access.remove_tenant_access.assert_called_once_with(
flavor=flavor, tenant=tenant)
def test_server_group_list(self):
server_groups = self.server_groups.list()
novaclient = self.stub_novaclient()
novaclient.server_groups.list.return_value = server_groups
ret_val = api.nova.server_group_list(self.request)
self.assertIsInstance(ret_val, list)
self.assertEqual(len(ret_val), len(server_groups))
novaclient.server_groups.list.assert_called_once_with()
| server = self.servers.first()
exc_catalog = horizon_exceptions.ServiceCatalogException('image')
mock_image_get.side_effect = exc_catalog
server = api.nova.Server(server, self.request)
self.assertIsNone(server.image_name)
mock_image_get.assert_called_once_with(test.IsHttpRequest(),
server.image['id']) |
quick_pairing_menu.rs | use crate::{Menu, *};
pub struct QuickPairingMenu {
time: u32,
}
impl Menu for QuickPairingMenu {
fn display(&mut self) -> Option<Box<dyn Menu>> {
self.choose_time();
None
}
}
impl QuickPairingMenu {
pub fn new() -> QuickPairingMenu {
QuickPairingMenu {
time: 0, | }
}
fn choose_time(&mut self) {
while self.time == 0 {
clean_screen();
self.print();
self.print_time_choice();
self.time = Input::one_to_(7);
}
}
fn print(&self) {
println!("Quick pairing:");
println!(" Variant: Standard");
}
fn print_time_choice(&self) {
println!(" 1. 5 + 0 Blitz");
println!(" 2. 5 + 3 Blitz");
println!(" 3. 10 + 0 Rapid");
println!(" 4. 10 + 5 Rapid");
println!(" 5. 15 + 10 Rapid");
println!(" 6. 30 + 0 Classical");
println!(" 7. 30 + 20 Classical");
}
} | |
url_variables.rs | #![cfg(feature = "url_variables")] | mod common;
use octane::prelude::*;
pub fn basic_url_variables() {
let mut app = Octane::new();
let value = "bar";
app.get(
"/foo/:var",
route_next!(|req, res| {
res.send("test");
assert_eq!(value, *req.vars.get("var").unwrap());
}),
)
.unwrap();
common::run(app, || async {
common::client_request(&path!(format!("foo/{}", value))).await;
});
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.